diff --git a/tests/plugins/test_scm_request_processor.py b/tests/plugins/test_scm_request_processor.py index 72ef349..a50c0b1 100644 --- a/tests/plugins/test_scm_request_processor.py +++ b/tests/plugins/test_scm_request_processor.py @@ -13,10 +13,12 @@ import pytest import toddlers.plugins.scm_request_processor as scm_request_processor from toddlers.exceptions import ValidationError + class TestAcceptsTopic: """ Test class for `toddlers.plugins.scm_request_processor.SCMRequestProcessor.accepts_topic` method. """ + toddler_cls = scm_request_processor.SCMRequestProcessor def test_accetps_topic_invalid(self, toddler): @@ -34,7 +36,7 @@ class TestAcceptsTopic: "org.fedoraproject.stg.pagure.issue.edit", "org.fedoraproject.prod.pagure.issue.new", "org.fedoraproject.prod.pagure.issue.edit", - ] + ], ) def test_accetps_topic_valid(self, topic, toddler): """ @@ -47,6 +49,7 @@ class TestProcess: """ Test class for `toddlers.plugins.scm_request_processor.SCMRequestProcessor.process` method. """ + toddler_cls = scm_request_processor.SCMRequestProcessor def test_process_invalid_project(self, caplog, toddler): @@ -56,22 +59,18 @@ class TestProcess: caplog.set_level(logging.INFO) msg = IssueNewV1() - msg.body = { - "project": { - "fullname": "foo/bar" - } - } + msg.body = {"project": {"fullname": "foo/bar"}} with patch( - "toddlers.plugins.scm_request_processor.SCMRequestProcessor.process_ticket" + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.process_ticket" ) as mock_process_ticket: toddler.process({}, msg) mock_process_ticket.assert_not_called() assert ( - caplog.records[-1].message == - "The message doesn't belong to project releng/fedora-scm-requests. Skipping message." + caplog.records[-1].message + == "The message doesn't belong to project releng/fedora-scm-requests. Skipping message." ) def test_process_issue_not_open(self, caplog, toddler): @@ -82,25 +81,19 @@ class TestProcess: msg = IssueNewV1() msg.body = { - "project": { - "fullname": scm_request_processor.PROJECT_NAMESPACE - }, - "issue": { - "id": 100, - "close_status": "Closed" - } + "project": {"fullname": scm_request_processor.PROJECT_NAMESPACE}, + "issue": {"id": 100, "close_status": "Closed"}, } with patch( - "toddlers.plugins.scm_request_processor.SCMRequestProcessor.process_ticket" + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.process_ticket" ) as mock_process_ticket: toddler.process({}, msg) mock_process_ticket.assert_not_called() assert ( - caplog.records[-1].message == - "The issue 100 is not open. Skipping message." + caplog.records[-1].message == "The issue 100 is not open. Skipping message." ) @patch("toddlers.utils.pdc.set_pdc") @@ -113,15 +106,10 @@ class TestProcess: initial processing. """ msg = IssueNewV1() - issue = { - "id": 100, - "close_status": "Open" - } + issue = {"id": 100, "close_status": "Open"} msg.body = { - "project": { - "fullname": scm_request_processor.PROJECT_NAMESPACE - }, - "issue": issue + "project": {"fullname": scm_request_processor.PROJECT_NAMESPACE}, + "issue": issue, } config = { "branch_slas": {}, @@ -130,24 +118,28 @@ class TestProcess: "pagure_namespace_to_product": {}, "temp_dir": "", "dist_git_url": "https://src.fedoraproject.org", - "dist_git_token": "Private API Key" + "dist_git_token": "Private API Key", } with patch( - "toddlers.plugins.scm_request_processor.SCMRequestProcessor.process_ticket" + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.process_ticket" ) as mock_process_ticket: toddler.process(config, msg) mock_process_ticket.assert_called_with(issue) mock_pdc.assert_called_with(config) - mock_pagure.assert_has_calls([ - call(config), - call({ - "pagure_url": "https://src.fedoraproject.org", - "pagure_api_key": "Private API Key" - }) - ]) + mock_pagure.assert_has_calls( + [ + call(config), + call( + { + "pagure_url": "https://src.fedoraproject.org", + "pagure_api_key": "Private API Key", + } + ), + ] + ) mock_fasjson.assert_called_with(config) mock_bugzilla.assert_called_with(config) @@ -172,14 +164,15 @@ class TestProcessTicket: issue = { "id": 100, "content": "invalid JSON", - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } self.toddler.process_ticket(issue) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="Invalid JSON provided", - reason="Invalid" + reason="Invalid", ) def test_process_ticket_invalid_slas(self): @@ -193,10 +186,10 @@ class TestProcessTicket: issue = { "id": 100, "content": json.dumps(content), - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } with patch( - "toddlers.plugins.scm_request_processor.SCMRequestProcessor.verify_slas" + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.verify_slas" ) as mock_verify_slas: mock_verify_slas.side_effect = ValidationError("error") self.toddler.process_ticket(issue) @@ -204,9 +197,10 @@ class TestProcessTicket: mock_verify_slas.assert_called_with("branch", {}) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="error", - reason="Invalid" + reason="Invalid", ) def test_process_ticket_missing_action(self): @@ -220,60 +214,58 @@ class TestProcessTicket: issue = { "id": 100, "content": json.dumps(content), - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } self.toddler.process_ticket(issue) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="Invalid or missing action field", - reason="Invalid" + reason="Invalid", ) def test_process_ticket_missing_sla(self): """ Assert that missing SLA for branch will end the processing. """ - content = { - "branch": "branch", - "action": "new_repo" - } + content = {"branch": "branch", "action": "new_repo"} issue = { "id": 100, "content": json.dumps(content), - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } self.toddler.process_ticket(issue) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="Couldn't find standard SLA for branch 'branch'", - reason="Invalid" + reason="Invalid", ) def test_process_ticket_invalid_branch_name(self): """ Assert that invalid name for branch in specific namespace will end the processing. """ - content = { - "branch": "branch/", - "action": "new_repo", - "namespace": "flatpaks" - } + content = {"branch": "branch/", "action": "new_repo", "namespace": "flatpaks"} issue = { "id": 100, "content": json.dumps(content), - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } self.toddler.branch_slas = {"branch/": "SLA"} self.toddler.process_ticket(issue) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, - message=("Only characters, numbers, periods, dashes, underscores, " - "and pluses are allowed in flatpak branch names"), - reason="Invalid" + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, + message=( + "Only characters, numbers, periods, dashes, underscores, " + "and pluses are allowed in flatpak branch names" + ), + reason="Invalid", ) def test_process_ticket_invalid_monitoring_setting(self): @@ -284,21 +276,22 @@ class TestProcessTicket: "branch": "branch", "action": "new_repo", "namespace": "flatpaks", - "monitor": "monitor" + "monitor": "monitor", } issue = { "id": 100, "content": json.dumps(content), - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } self.toddler.branch_slas = {"branch": "SLA"} self.toddler.process_ticket(issue) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message='The monitor choice of "monitor" is invalid', - reason="Invalid" + reason="Invalid", ) def test_process_ticket_action_new_repo(self): @@ -312,18 +305,20 @@ class TestProcessTicket: issue = { "id": 100, "content": json.dumps(content), - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } self.toddler.branch_slas = {"branch": "SLA"} with patch( - "toddlers.plugins.scm_request_processor.SCMRequestProcessor.create_new_repo" + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.create_new_repo" ) as mock_new_repo: self.toddler.process_ticket(issue) content["sls"] = "SLA" mock_new_repo.assert_called_with( - issue, content, initial_commit=True, + issue, + content, + initial_commit=True, ) def test_process_ticket_action_new_branch(self): @@ -337,18 +332,19 @@ class TestProcessTicket: issue = { "id": 100, "content": json.dumps(content), - "full_url": "https://blacklibrary.wh40k" + "full_url": "https://blacklibrary.wh40k", } self.toddler.branch_slas = {"branch": "SLA"} with patch( - "toddlers.plugins.scm_request_processor.SCMRequestProcessor.create_new_branch" + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.create_new_branch" ) as mock_new_branch: self.toddler.process_ticket(issue) content["sls"] = "SLA" mock_new_branch.assert_called_with( - issue, content, + issue, + content, ) @@ -390,13 +386,9 @@ class TestVerifySLAs: correct. """ branch = "branch" - sla = { "rawhide": "2022-06-01"} + sla = {"rawhide": "2022-06-01"} - self.toddler.branch_slas = { - branch: { - "rawhide": "2022-06-01" - } - } + self.toddler.branch_slas = {branch: {"rawhide": "2022-06-01"}} self.toddler.verify_slas(branch, sla) @@ -406,13 +398,9 @@ class TestVerifySLAs: incorrect. """ branch = "branch" - sla = { "rawhide": "2022-01-01"} + sla = {"rawhide": "2022-01-01"} - self.toddler.branch_slas = { - branch: { - "rawhide": "2022-06-01" - } - } + self.toddler.branch_slas = {branch: {"rawhide": "2022-06-01"}} error = 'The SLAs for the branch "{0}" are incorrect'.format(branch) @@ -424,9 +412,11 @@ class TestVerifySLAs: Assert that the validation will fail if provided SLA EOL is not string. """ - sla = { "rawhide": 100 } + sla = {"rawhide": 100} - error = 'The SL\'s EOL is not a string. It was type "{0}"'.format(type(100).__name__) + error = 'The SL\'s EOL is not a string. It was type "{0}"'.format( + type(100).__name__ + ) with pytest.raises(ValidationError, match=error): self.toddler.verify_slas("", sla) @@ -435,7 +425,7 @@ class TestVerifySLAs: """ Assert that the validation will fail if provided SLA EOL date is in invalid format. """ - sla = { "rawhide": "01-01-2022" } + sla = {"rawhide": "01-01-2022"} error = 'The EOL date "{0}" is in an invalid format'.format("01-01-2022") @@ -446,7 +436,7 @@ class TestVerifySLAs: """ Assert that the validation will fail if provided SLA EOL date is already expired. """ - sla = { "rawhide": "2022-01-01" } + sla = {"rawhide": "2022-01-01"} error = 'The SL "{0}" is already expired'.format("2022-01-01") @@ -457,19 +447,21 @@ class TestVerifySLAs: """ Assert that the validation will fail if provided SLA EOL date is invalid. """ - sla = { "rawhide": "2050-01-01" } + sla = {"rawhide": "2050-01-01"} - error = 'The SL "{0}" must expire on June 1st or December 1st'.format("2050-01-01") + error = 'The SL "{0}" must expire on June 1st or December 1st'.format( + "2050-01-01" + ) with pytest.raises(ValidationError, match=error): self.toddler.verify_slas("", sla) - @patch('toddlers.utils.pdc.get_sla') + @patch("toddlers.utils.pdc.get_sla") def test_verify_slas_not_in_pdc(self, mock_pdc): """ Assert that the validation will fail if SLA is not in PDC. """ - sla = { "rawhide": "2050-06-01" } + sla = {"rawhide": "2050-06-01"} error = 'The SL "{0}" is not in PDC'.format("rawhide") @@ -480,12 +472,12 @@ class TestVerifySLAs: mock_pdc.assert_called_with("rawhide") - @patch('toddlers.utils.pdc.get_sla') + @patch("toddlers.utils.pdc.get_sla") def test_verify_slas_in_pdc(self, mock_pdc): """ Assert that the validation will pass if SLA is in PDC. """ - sla = { "rawhide": "2050-06-01" } + sla = {"rawhide": "2050-06-01"} mock_pdc.return_value = sla @@ -517,21 +509,17 @@ class TestCreateNewRepo: self.toddler.create_new_repo(issue, {}) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="Invalid body, missing required field: repo", - reason="Invalid" + reason="Invalid", ) def test_create_new_repo_invalid_repo_name(self): """ Assert that ticket will be closed if provided repository name is invalid. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} json = { "repo": "+a", @@ -539,35 +527,31 @@ class TestCreateNewRepo: "namespace": "namespace", "bug_id": "123", "action": "new_repo", - "sls": { - "rawhide": "2050-06-01" - }, - "monitor": "monitor" + "sls": {"rawhide": "2050-06-01"}, + "monitor": "monitor", } self.toddler.create_new_repo(issue, json) - error = ('The repository name is invalid. It must be at least two ' - 'characters long with only letters, numbers, hyphens, ' - 'underscores, plus signs, and/or periods. Please note that ' - 'the project cannot start with a period or a plus sign.') + error = ( + "The repository name is invalid. It must be at least two " + "characters long with only letters, numbers, hyphens, " + "underscores, plus signs, and/or periods. Please note that " + "the project cannot start with a period or a plus sign." + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=error, - reason="Invalid" + reason="Invalid", ) def test_create_new_repo_missing_bug_id(self): """ Assert that ticket will be closed if Bugzilla bug id is not provided. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} json = { "repo": "repo", @@ -575,31 +559,27 @@ class TestCreateNewRepo: "namespace": "namespace", "bug_id": "", "action": "new_repo", - "sls": { - "rawhide": "2050-06-01" - }, - "monitor": "monitor" + "sls": {"rawhide": "2050-06-01"}, + "monitor": "monitor", } self.toddler.create_new_repo(issue, json) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="An invalid Bugzilla bug was provided", - reason="Invalid" + reason="Invalid", ) - @patch("toddlers.plugins.scm_request_processor.SCMRequestProcessor.validate_review_bug") + @patch( + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.validate_review_bug" + ) def test_create_new_repo_invalid_review_bug(self, mock_validate_review_bug): """ Assert that ticket will be closed if Bugzilla bug is not valid. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} json = { "repo": "repo", @@ -607,10 +587,8 @@ class TestCreateNewRepo: "namespace": "namespace", "bug_id": "123", "action": "new_repo", - "sls": { - "rawhide": "2050-06-01" - }, - "monitor": "monitor" + "sls": {"rawhide": "2050-06-01"}, + "monitor": "monitor", } mock_validate_review_bug.side_effect = ValidationError("error") @@ -618,36 +596,31 @@ class TestCreateNewRepo: self.toddler.create_new_repo(issue, json) mock_validate_review_bug.assert_called_with( - "123", "repo", "rawhide", - namespace="namespace", pagure_user="zlopez" + "123", "repo", "rawhide", namespace="namespace", pagure_user="zlopez" ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="error", - reason="Invalid" + reason="Invalid", ) - @patch("toddlers.plugins.scm_request_processor.SCMRequestProcessor.valid_epel_package") + @patch( + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.valid_epel_package" + ) def test_create_new_repo_invalid_epel(self, mock_valid_epel_package): """ Assert that ticket will be closed if repo is invalid EPEL repo. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "epel8" namespace = "rpms" bug_id = "123" action = "new_repo" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} monitor = "monitor" exception = True json = { @@ -658,42 +631,34 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } mock_valid_epel_package.return_value = False self.toddler.create_new_repo(issue, json) - mock_valid_epel_package.assert_called_with( - repo, branch - ) + mock_valid_epel_package.assert_called_with(repo, branch) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=scm_request_processor.INVALID_EPEL_ERROR, - reason="Invalid" + reason="Invalid", ) def test_create_new_repo_requester_not_in_dist_git(self): """ Assert that ticket will be commented on when requester doesn't have a valid dist git account. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" bug_id = "123" action = "new_repo" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} monitor = "monitor" exception = True json = { @@ -704,7 +669,7 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } self.toddler.dist_git.user_exists.return_value = False @@ -712,14 +677,15 @@ class TestCreateNewRepo: self.toddler.create_new_repo(issue, json) - self.toddler.dist_git.user_exists.assert_called_with( - "zlopez" + self.toddler.dist_git.user_exists.assert_called_with("zlopez") + + message = "@zlopez needs to login to {0} to sync accounts before we can proceed.".format( + self.toddler.dist_git._pagure_url ) - message = "@zlopez needs to login to {0} to sync accounts before we can proceed.".format(self.toddler.dist_git._pagure_url) - self.toddler.pagure_io.add_comment_to_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, comment=message, ) @@ -727,21 +693,14 @@ class TestCreateNewRepo: """ Assert that ticket will be closed when repo already exists in dist git. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" bug_id = "123" action = "new_repo" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} monitor = "monitor" exception = True json = { @@ -752,21 +711,20 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } self.toddler.dist_git.get_project.return_value = "project" self.toddler.create_new_repo(issue, json) - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="The Pagure project already exists", - reason="Invalid" + reason="Invalid", ) def test_create_new_repo_master_branch(self): @@ -774,21 +732,14 @@ class TestCreateNewRepo: Assert that ticket will be closed when branch is set to master branch. Master branch is no longer allowed. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "master" namespace = "rpms" bug_id = "123" action = "new_repo" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} monitor = "monitor" exception = True json = { @@ -799,41 +750,33 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } self.toddler.dist_git.get_project.return_value = None self.toddler.create_new_repo(issue, json) - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="Branch `master` cannot be created, please request the right branch.", - reason="Invalid" + reason="Invalid", ) def test_create_new_repo_unsupported_namespace(self): """ Assert that ticket will be closed when requested namespace is not recognized. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "invalid" bug_id = "123" action = "new_repo" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} monitor = "monitor" exception = True json = { @@ -844,46 +787,40 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } self.toddler.dist_git.get_project.return_value = None self.toddler.create_new_repo(issue, json) - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) - error = ("The requested namespace '{0}' is not recognized. " - "Currently supported namespaces are: " - "rpms, container, flatpaks, modules, tests.".format(namespace)) + error = ( + "The requested namespace '{0}' is not recognized. " + "Currently supported namespaces are: " + "rpms, container, flatpaks, modules, tests.".format(namespace) + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=error, - reason="Invalid" + reason="Invalid", ) - @patch('toddlers.utils.pdc.get_branch') + @patch("toddlers.utils.pdc.get_branch") def test_create_new_repo_branch_exist(self, mock_pdc_get_branch): """ Assert that ticket will be closed when branch already exist in PDC. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" bug_id = "123" action = "new_repo" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} monitor = "monitor" exception = True json = { @@ -894,22 +831,21 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } self.toddler.dist_git.get_project.return_value = None mock_pdc_get_branch.return_value = branch self.toddler.create_new_repo(issue, json) - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) - mock_pdc_get_branch.assert_called_with(repo, branch, namespace.rstrip('s')) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) + mock_pdc_get_branch.assert_called_with(repo, branch, namespace.rstrip("s")) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="The PDC branch already exists", - reason="Invalid" + reason="Invalid", ) @pytest.mark.parametrize( @@ -919,26 +855,19 @@ class TestCreateNewRepo: ("container", "rawhide"), ("flatpaks", "stable"), ("modules", "rawhide"), - ] + ], ) @patch("toddlers.plugins.scm_request_processor.pdc") def test_create_new_repo_namespaces(self, mock_pdc, namespace, branch): """ Assert that ticket will be processed when everything is in order and namespace is correct. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" bug_id = "" action = "new_repo" - sls = { - branch: "2050-06-01" - } + sls = {branch: "2050-06-01"} monitor = "monitor" exception = True json = { @@ -949,7 +878,7 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } dist_git_url = "https://src.fp.o" self.toddler.dist_git.get_project.return_value = None @@ -959,11 +888,9 @@ class TestCreateNewRepo: self.toddler.create_new_repo(issue, json) # asserts - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) self.toddler.dist_git.new_project.assert_called_with( - namespace, repo, '', '', branch, initial_commit=True, alias=True + namespace, repo, "", "", branch, initial_commit=True, alias=True ) self.toddler.dist_git.set_monitoring_status.assert_called_with( namespace, repo, monitor @@ -972,22 +899,24 @@ class TestCreateNewRepo: namespace, repo, "zlopez" ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.rstrip('s')) + mock_pdc.get_branch.assert_called_with(repo, branch, namespace.rstrip("s")) mock_pdc.new_global_component.assert_called_with( repo, "{0}/{1}/{2}".format(dist_git_url, namespace, repo) ) - mock_pdc.new_branch.assert_called_with(repo, branch, namespace.rstrip('s')) + mock_pdc.new_branch.assert_called_with(repo, branch, namespace.rstrip("s")) mock_pdc.new_sla_to_branch.assert_called_with( - branch, sls[branch], repo, branch, namespace.rstrip('s') + branch, sls[branch], repo, branch, namespace.rstrip("s") ) message = "The Pagure repository was created at {0}/{1}/{2}".format( - dist_git_url, namespace, repo) + dist_git_url, namespace, repo + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Processed" + reason="Processed", ) @patch("toddlers.plugins.scm_request_processor.pdc") @@ -995,21 +924,14 @@ class TestCreateNewRepo: """ Assert that ticket will be processed when everything is in order and namespace is set to tests. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "main" namespace = "tests" bug_id = "" action = "new_repo" - sls = { - branch: "2050-06-01" - } + sls = {branch: "2050-06-01"} monitor = "monitor" exception = True json = { @@ -1020,7 +942,7 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } dist_git_url = "https://src.fp.o" self.toddler.dist_git.get_project.return_value = None @@ -1030,11 +952,9 @@ class TestCreateNewRepo: self.toddler.create_new_repo(issue, json) # asserts - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) self.toddler.dist_git.new_project.assert_called_with( - namespace, repo, '', '', branch, initial_commit=True, alias=True + namespace, repo, "", "", branch, initial_commit=True, alias=True ) self.toddler.dist_git.set_monitoring_status.assert_called_with( namespace, repo, monitor @@ -1043,15 +963,17 @@ class TestCreateNewRepo: namespace, repo, "zlopez" ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.rstrip('s')) + mock_pdc.get_branch.assert_called_with(repo, branch, namespace.rstrip("s")) message = "The Pagure repository was created at {0}/{1}/{2}".format( - dist_git_url, namespace, repo) + dist_git_url, namespace, repo + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Processed" + reason="Processed", ) @patch("toddlers.plugins.scm_request_processor.pdc") @@ -1059,21 +981,14 @@ class TestCreateNewRepo: """ Assert that ticket will be processed when everything is in order and requested branch is not default. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "f35" namespace = "rpms" bug_id = "" action = "new_repo" - sls = { - branch: "2050-06-01" - } + sls = {branch: "2050-06-01"} monitor = "monitor" exception = True json = { @@ -1084,13 +999,9 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception - } - self.toddler.branch_slas = { - "rawhide": { - "rawhide": "2050-06-01" - } + "exception": exception, } + self.toddler.branch_slas = {"rawhide": {"rawhide": "2050-06-01"}} dist_git_url = "https://src.fp.o" self.toddler.dist_git.get_project.return_value = None @@ -1100,11 +1011,9 @@ class TestCreateNewRepo: self.toddler.create_new_repo(issue, json) # asserts - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) self.toddler.dist_git.new_project.assert_called_with( - namespace, repo, '', '', "rawhide", initial_commit=True, alias=True + namespace, repo, "", "", "rawhide", initial_commit=True, alias=True ) self.toddler.dist_git.set_monitoring_status.assert_called_with( namespace, repo, monitor @@ -1115,8 +1024,8 @@ class TestCreateNewRepo: mock_pdc.get_branch.assert_has_calls( [ - call(repo, "rawhide", namespace.rstrip('s')), - call(repo, branch, namespace.rstrip('s')), + call(repo, "rawhide", namespace.rstrip("s")), + call(repo, branch, namespace.rstrip("s")), ] ) mock_pdc.new_global_component.assert_called_with( @@ -1124,26 +1033,28 @@ class TestCreateNewRepo: ) mock_pdc.new_branch.assert_has_calls( [ - call(repo, "rawhide", namespace.rstrip('s')), - call(repo, branch, namespace.rstrip('s')), + call(repo, "rawhide", namespace.rstrip("s")), + call(repo, branch, namespace.rstrip("s")), ] ) mock_pdc.new_sla_to_branch.assert_has_calls( [ - call("rawhide", "2050-06-01", repo, "rawhide", namespace.rstrip('s')), - call(branch, sls[branch], repo, branch, namespace.rstrip('s')), + call("rawhide", "2050-06-01", repo, "rawhide", namespace.rstrip("s")), + call(branch, sls[branch], repo, branch, namespace.rstrip("s")), ] ) - message = ('The Pagure repository was created at {0}/{1}/{2}. ' - 'You may commit to the branch "{3}" in about ' - '10 minutes.'.format(dist_git_url, namespace, repo, branch) + message = ( + "The Pagure repository was created at {0}/{1}/{2}. " + 'You may commit to the branch "{3}" in about ' + "10 minutes.".format(dist_git_url, namespace, repo, branch) ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Processed" + reason="Processed", ) @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -1152,21 +1063,14 @@ class TestCreateNewRepo: """ Assert that bug will be updated if the bug_id is provided. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" bug_id = "123" action = "new_repo" - sls = { - branch: "2050-06-01" - } + sls = {branch: "2050-06-01"} monitor = "monitor" exception = True json = { @@ -1177,7 +1081,7 @@ class TestCreateNewRepo: "action": action, "sls": sls, "monitor": monitor, - "exception": exception + "exception": exception, } dist_git_url = "https://src.fp.o" @@ -1188,11 +1092,9 @@ class TestCreateNewRepo: self.toddler.create_new_repo(issue, json) # asserts - self.toddler.dist_git.get_project.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_project.assert_called_with(namespace, repo) self.toddler.dist_git.new_project.assert_called_with( - namespace, repo, '', '', branch, initial_commit=True, alias=True + namespace, repo, "", "", branch, initial_commit=True, alias=True ) self.toddler.dist_git.set_monitoring_status.assert_called_with( namespace, repo, monitor @@ -1201,26 +1103,29 @@ class TestCreateNewRepo: namespace, repo, "zlopez" ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.rstrip('s')) + mock_pdc.get_branch.assert_called_with(repo, branch, namespace.rstrip("s")) mock_pdc.new_global_component.assert_called_with( repo, "{0}/{1}/{2}".format(dist_git_url, namespace, repo) ) - mock_pdc.new_branch.assert_called_with(repo, branch, namespace.rstrip('s')) + mock_pdc.new_branch.assert_called_with(repo, branch, namespace.rstrip("s")) mock_pdc.new_sla_to_branch.assert_called_with( - branch, sls[branch], repo, branch, namespace.rstrip('s') + branch, sls[branch], repo, branch, namespace.rstrip("s") ) message = "The Pagure repository was created at {0}/{1}/{2}".format( - dist_git_url, namespace, repo) + dist_git_url, namespace, repo + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Processed" + reason="Processed", ) mock_bz.comment_on_bug.assert_called_with(bug_id, message) + class TestCreateNewBranch: """ Test class for `toddlers.plugins.scm_request_processor.SCMRequestProcessor.create_new_branch` method. @@ -1244,9 +1149,10 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, {}) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="Invalid body, missing required field: action", - reason="Invalid" + reason="Invalid", ) def test_create_new_branch_no_contributors(self): @@ -1261,9 +1167,7 @@ class TestCreateNewBranch: branch = "rawhide" namespace = "rpms" action = "new_branch" - sls = { - branch: "2050-06-01" - } + sls = {branch: "2050-06-01"} json = { "repo": repo, "branch": branch, @@ -1276,33 +1180,31 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) - - self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, - message="The dist git repository doesn't exist", - reason="Invalid" + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo ) - @patch("toddlers.plugins.scm_request_processor.SCMRequestProcessor.valid_epel_package") + self.toddler.pagure_io.close_issue.assert_called_with( + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, + message="The dist git repository doesn't exist", + reason="Invalid", + ) + + @patch( + "toddlers.plugins.scm_request_processor.SCMRequestProcessor.valid_epel_package" + ) def test_create_new_branch_invalid_epel(self, mock_valid_epel_package): """ Assert that ticket will be closed if repo is invalid EPEL repo. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "epel8" namespace = "rpms" action = "new_branch" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} json = { "repo": repo, "branch": branch, @@ -1316,16 +1218,17 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) - - mock_valid_epel_package.assert_called_with( - repo, branch + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo ) + mock_valid_epel_package.assert_called_with(repo, branch) + self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=scm_request_processor.INVALID_EPEL_ERROR, - reason="Invalid" + reason="Invalid", ) @patch("toddlers.plugins.scm_request_processor.pdc") @@ -1333,20 +1236,13 @@ class TestCreateNewBranch: """ Assert that ticket will be closed if branch already exists in PDC. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" action = "new_branch" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} json = { "repo": repo, "branch": branch, @@ -1358,45 +1254,46 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo + ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.strip().rstrip('s')) + mock_pdc.get_branch.assert_called_with( + repo, branch, namespace.strip().rstrip("s") + ) - message = \ - "The branch in PDC already exists, you can now create it yourself as follows:\n" \ - "Check in the project's settings if you have activated the git hook preventing" \ - "new git branches from being created and if you did, de-activate it.\n" \ - "Then simply run in cloned repository: " \ - "``git checkout -b && git push -u origin ``.\n" \ - "```` is the name of the branch you requested. \n" \ + message = ( + "The branch in PDC already exists, you can now create it yourself as follows:\n" + "Check in the project's settings if you have activated the git hook preventing" + "new git branches from being created and if you did, de-activate it.\n" + "Then simply run in cloned repository: " + "``git checkout -b && git push -u origin ``.\n" + "```` is the name of the branch you requested. \n" "You only need to do this once and you can then use fedpkg as you normally do." + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Invalid" + reason="Invalid", ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.pdc") - def test_create_new_branch_requester_is_not_maintainer(self, mock_pdc, mock_fedora_account): + def test_create_new_branch_requester_is_not_maintainer( + self, mock_pdc, mock_fedora_account + ): """ Assert that ticket will be closed if requester is not a maintainer of package. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" action = "new_branch" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} json = { "repo": repo, "branch": branch, @@ -1405,16 +1302,8 @@ class TestCreateNewBranch: "sls": sls, } self.toddler.dist_git.get_project_contributors.return_value = { - "users": { - "admin": [], - "commit": [], - "collaborators": [] - }, - "groups": { - "admin": ["group"], - "commit": [], - "collaborators": [] - } + "users": {"admin": [], "commit": [], "collaborators": []}, + "groups": {"admin": ["group"], "commit": [], "collaborators": []}, } mock_pdc.get_branch.return_value = None mock_fedora_account.user_member_of.return_value = False @@ -1422,43 +1311,43 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo + ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.strip().rstrip('s')) + mock_pdc.get_branch.assert_called_with( + repo, branch, namespace.strip().rstrip("s") + ) mock_fedora_account.user_member_of.assert_called_with( mock_fedora_account.get_user_by_username(), "group" ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message="zlopez is not a maintainer of the {0} package".format(repo), - reason="Invalid" + reason="Invalid", ) @patch("toddlers.plugins.scm_request_processor.TemporaryDirectory") @patch("toddlers.plugins.scm_request_processor.git") @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.pdc") - def test_create_new_branch_default_branch_missing(self, mock_pdc, mock_fedora_account, mock_git, mock_temp_dir): + def test_create_new_branch_default_branch_missing( + self, mock_pdc, mock_fedora_account, mock_git, mock_temp_dir + ): """ Assert that ticket will be closed if there is no default branch in project and new branch in git should be created. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" action = "new_branch" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} json = { "repo": repo, "branch": branch, @@ -1467,16 +1356,8 @@ class TestCreateNewBranch: "sls": sls, } self.toddler.dist_git.get_project_contributors.return_value = { - "users": { - "admin": [], - "commit": [], - "collaborators": [] - }, - "groups": { - "admin": ["group"], - "commit": [], - "collaborators": [] - } + "users": {"admin": [], "commit": [], "collaborators": []}, + "groups": {"admin": ["group"], "commit": [], "collaborators": []}, } self.toddler.dist_git.get_default_branch.return_value = None self.toddler.dist_git._pagure_url = "https://fp.o" @@ -1491,63 +1372,65 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo + ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.strip().rstrip('s')) + mock_pdc.get_branch.assert_called_with( + repo, branch, namespace.strip().rstrip("s") + ) mock_fedora_account.user_member_of.assert_called_with( mock_fedora_account.get_user_by_username(), "group" ) mock_pdc.new_global_component.assert_called_with( - repo, "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo) + repo, + "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), ) mock_pdc.new_branch.assert_called_with( - repo, branch, namespace.strip().rstrip('s') + repo, branch, namespace.strip().rstrip("s") ) mock_pdc.new_sla_to_branch.assert_called_with( - branch, "2050-06-01", repo, branch, namespace.strip().rstrip('s') + branch, "2050-06-01", repo, branch, namespace.strip().rstrip("s") ) mock_git.clone_repo.assert_called_with( - "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), "dir" + "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), + "dir", ) - self.toddler.dist_git.get_default_branch.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_default_branch.assert_called_with(namespace, repo) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, - message="There is no default branch set for {0}/{1}".format(namespace, repo), - reason="Invalid" + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, + message="There is no default branch set for {0}/{1}".format( + namespace, repo + ), + reason="Invalid", ) @patch("toddlers.plugins.scm_request_processor.TemporaryDirectory") @patch("toddlers.plugins.scm_request_processor.git") @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.pdc") - def test_create_new_branch_with_git(self, mock_pdc, mock_fedora_account, mock_git, mock_temp_dir): + def test_create_new_branch_with_git( + self, mock_pdc, mock_fedora_account, mock_git, mock_temp_dir + ): """ Assert that ticket will be processed and branch created in git. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" default_branch = "rawhide" branch = "f36" namespace = "rpms" action = "new_branch" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} json = { "repo": repo, "branch": branch, @@ -1556,16 +1439,8 @@ class TestCreateNewBranch: "sls": sls, } self.toddler.dist_git.get_project_contributors.return_value = { - "users": { - "admin": [], - "commit": [], - "collaborators": [] - }, - "groups": { - "admin": ["group"], - "commit": [], - "collaborators": [] - } + "users": {"admin": [], "commit": [], "collaborators": []}, + "groups": {"admin": ["group"], "commit": [], "collaborators": []}, } self.toddler.dist_git.get_default_branch.return_value = default_branch self.toddler.dist_git._pagure_url = "https://fp.o" @@ -1584,33 +1459,37 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo + ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.strip().rstrip('s')) + mock_pdc.get_branch.assert_called_with( + repo, branch, namespace.strip().rstrip("s") + ) mock_fedora_account.user_member_of.assert_called_with( mock_fedora_account.get_user_by_username(), "group" ) mock_pdc.new_global_component.assert_called_with( - repo, "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo) + repo, + "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), ) mock_pdc.new_branch.assert_called_with( - repo, branch, namespace.strip().rstrip('s') + repo, branch, namespace.strip().rstrip("s") ) mock_pdc.new_sla_to_branch.assert_called_with( - default_branch, "2050-06-01", repo, branch, namespace.strip().rstrip('s') + default_branch, "2050-06-01", repo, branch, namespace.strip().rstrip("s") ) mock_git.clone_repo.assert_called_with( - "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), "dir" + "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), + "dir", ) - self.toddler.dist_git.get_default_branch.assert_called_with( - namespace, repo - ) + self.toddler.dist_git.get_default_branch.assert_called_with(namespace, repo) mock_git_repo.first_commit.assert_called_with(default_branch) @@ -1618,15 +1497,17 @@ class TestCreateNewBranch: namespace, repo, branch, from_commit="SHA256" ) - - message = ('The branch was created in PDC and git. It ' - 'may take up to 10 minutes before you have ' - 'write access on the branch.') + message = ( + "The branch was created in PDC and git. It " + "may take up to 10 minutes before you have " + "write access on the branch." + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Processed" + reason="Processed", ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @@ -1635,20 +1516,13 @@ class TestCreateNewBranch: """ Assert that ticket will be processed and branch created in PDC. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" action = "new_branch" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} json = { "repo": repo, "branch": branch, @@ -1658,16 +1532,8 @@ class TestCreateNewBranch: "create_git_branch": False, } self.toddler.dist_git.get_project_contributors.return_value = { - "users": { - "admin": [], - "commit": [], - "collaborators": [] - }, - "groups": { - "admin": ["group"], - "commit": [], - "collaborators": [] - } + "users": {"admin": [], "commit": [], "collaborators": []}, + "groups": {"admin": ["group"], "commit": [], "collaborators": []}, } self.toddler.dist_git._pagure_url = "https://fp.o" mock_pdc.get_branch.return_value = None @@ -1676,57 +1542,60 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo + ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.strip().rstrip('s')) + mock_pdc.get_branch.assert_called_with( + repo, branch, namespace.strip().rstrip("s") + ) mock_fedora_account.user_member_of.assert_called_with( mock_fedora_account.get_user_by_username(), "group" ) mock_pdc.new_global_component.assert_called_with( - repo, "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo) + repo, + "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), ) mock_pdc.new_branch.assert_called_with( - repo, branch, namespace.strip().rstrip('s') + repo, branch, namespace.strip().rstrip("s") ) mock_pdc.new_sla_to_branch.assert_called_with( - branch, "2050-06-01", repo, branch, namespace.strip().rstrip('s') + branch, "2050-06-01", repo, branch, namespace.strip().rstrip("s") ) - message = ('The branch in PDC was created. Pagure is still processing ' - 'the request, but in about 10 minutes, you may create the ' - 'branch in Pagure using git.') + message = ( + "The branch in PDC was created. Pagure is still processing " + "the request, but in about 10 minutes, you may create the " + "branch in Pagure using git." + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Processed" + reason="Processed", ) @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.pdc") - def test_create_new_branch_comment_on_bug(self, mock_pdc, mock_fedora_account, mock_bz): + def test_create_new_branch_comment_on_bug( + self, mock_pdc, mock_fedora_account, mock_bz + ): """ Assert that ticket will be processed and comment added to bugzilla bug, if provided. """ - issue = { - "id": 100, - "user": { - "name": "zlopez" - } - } + issue = {"id": 100, "user": {"name": "zlopez"}} repo = "repo" branch = "rawhide" namespace = "rpms" action = "new_branch" - sls = { - "rawhide": "2050-06-01" - } + sls = {"rawhide": "2050-06-01"} bug_id = "123" json = { "repo": repo, @@ -1738,16 +1607,8 @@ class TestCreateNewBranch: "create_git_branch": False, } self.toddler.dist_git.get_project_contributors.return_value = { - "users": { - "admin": [], - "commit": [], - "collaborators": [] - }, - "groups": { - "admin": ["group"], - "commit": [], - "collaborators": [] - } + "users": {"admin": [], "commit": [], "collaborators": []}, + "groups": {"admin": ["group"], "commit": [], "collaborators": []}, } self.toddler.dist_git._pagure_url = "https://fp.o" mock_pdc.get_branch.return_value = None @@ -1756,34 +1617,42 @@ class TestCreateNewBranch: self.toddler.create_new_branch(issue, json) # Asserts - self.toddler.dist_git.get_project_contributors.assert_called_with(namespace, repo) + self.toddler.dist_git.get_project_contributors.assert_called_with( + namespace, repo + ) - mock_pdc.get_branch.assert_called_with(repo, branch, namespace.strip().rstrip('s')) + mock_pdc.get_branch.assert_called_with( + repo, branch, namespace.strip().rstrip("s") + ) mock_fedora_account.user_member_of.assert_called_with( mock_fedora_account.get_user_by_username(), "group" ) mock_pdc.new_global_component.assert_called_with( - repo, "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo) + repo, + "{0}/{1}/{2}".format(self.toddler.dist_git._pagure_url, namespace, repo), ) mock_pdc.new_branch.assert_called_with( - repo, branch, namespace.strip().rstrip('s') + repo, branch, namespace.strip().rstrip("s") ) mock_pdc.new_sla_to_branch.assert_called_with( - branch, "2050-06-01", repo, branch, namespace.strip().rstrip('s') + branch, "2050-06-01", repo, branch, namespace.strip().rstrip("s") ) - message = ('The branch in PDC was created. Pagure is still processing ' - 'the request, but in about 10 minutes, you may create the ' - 'branch in Pagure using git.') + message = ( + "The branch in PDC was created. Pagure is still processing " + "the request, but in about 10 minutes, you may create the " + "branch in Pagure using git." + ) self.toddler.pagure_io.close_issue.assert_called_with( - 100, namespace=scm_request_processor.PROJECT_NAMESPACE, + 100, + namespace=scm_request_processor.PROJECT_NAMESPACE, message=message, - reason="Processed" + reason="Processed", ) mock_bz.comment_on_bug.assert_called_with(bug_id, message) @@ -1814,8 +1683,10 @@ class TestValidateReviewBug: mock_bz.get_bug.side_effect = Exception("error") - error = ('The Bugzilla bug could not be verified. The following ' - 'error was encountered: error') + error = ( + "The Bugzilla bug could not be verified. The following " + "error was encountered: error" + ) # Method to test with pytest.raises(ValidationError, match=error): @@ -1836,7 +1707,7 @@ class TestValidateReviewBug: mock_bz.get_bug.return_value = None - error = 'The Bugzilla bug doesn\'t exist' + error = "The Bugzilla bug doesn't exist" # Method to test with pytest.raises(ValidationError, match=error): @@ -1861,8 +1732,10 @@ class TestValidateReviewBug: mock_bz.get_bug.return_value = mock_bug - error = ('The Bugzilla bug is for "Fedora" but the ' - 'requested branch is an EPEL branch') + error = ( + 'The Bugzilla bug is for "Fedora" but the ' + "requested branch is an EPEL branch" + ) # Method to test with pytest.raises(ValidationError, match=error): @@ -1887,8 +1760,9 @@ class TestValidateReviewBug: mock_bz.get_bug.return_value = mock_bug - error = ('The Bugzilla bug is for "Fedora EPEL" but the ' - 'requested branch is "{0}"').format(branch) + error = ( + 'The Bugzilla bug is for "Fedora EPEL" but the ' 'requested branch is "{0}"' + ).format(branch) # Method to test with pytest.raises(ValidationError, match=error): @@ -1914,7 +1788,7 @@ class TestValidateReviewBug: self.toddler.pagure_namespace_to_component = {} - error = 'The Bugzilla bug provided is not the proper type' + error = "The Bugzilla bug provided is not the proper type" # Method to test with pytest.raises(ValidationError, match=error): @@ -1940,12 +1814,8 @@ class TestValidateReviewBug: mock_bz.get_bug.return_value = mock_bug - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} error = 'The Bugzilla bug provided is not for "{0}" or "{0}"'.format(namespace) @@ -1974,14 +1844,10 @@ class TestValidateReviewBug: mock_bz.get_bug.return_value = mock_bug - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} - error = 'The Bugzilla bug provided is not assigned to anyone' + error = "The Bugzilla bug provided is not assigned to anyone" # Method to test with pytest.raises(ValidationError, match=error): @@ -2013,17 +1879,13 @@ class TestValidateReviewBug: mock_fas.get_user_by_email.return_value = None - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} error = ( - 'The Bugzilla review bug creator could not be found in ' - 'FAS. Make sure your FAS email address is the same as in ' - 'Bugzilla.' + "The Bugzilla review bug creator could not be found in " + "FAS. Make sure your FAS email address is the same as in " + "Bugzilla." ) # Method to test @@ -2056,20 +1918,13 @@ class TestValidateReviewBug: mock_bz.get_bug.return_value = mock_bug - mock_fas.get_user_by_email.return_value = { - "username": "not_zlopez" - } + mock_fas.get_user_by_email.return_value = {"username": "not_zlopez"} - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} error = ( - 'The Bugzilla review bug creator ' - 'didn\'t match the requester in Pagure.' + "The Bugzilla review bug creator " "didn't match the requester in Pagure." ) # Method to test @@ -2099,30 +1954,19 @@ class TestValidateReviewBug: mock_bug.product = namespace mock_bug.assigned_to = user mock_bug.creator = user - mock_bug.flags = [ - { - "name": "fedora-review", - "status": "" - } - ] + mock_bug.flags = [{"name": "fedora-review", "status": ""}] mock_bz.get_bug.return_value = mock_bug - mock_fas.get_user_by_email.side_effect = [{ - "username": user - }, None] + mock_fas.get_user_by_email.side_effect = [{"username": user}, None] - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} error = ( 'The email address "{0}" of the Bugzilla reviewer ' - 'is not tied to a user in FAS or FAS check failed. ' - 'Group membership can\'t be validated.'.format(user) + "is not tied to a user in FAS or FAS check failed. " + "Group membership can't be validated.".format(user) ) # Method to test @@ -2132,9 +1976,7 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(user) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(user)]) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -2154,32 +1996,20 @@ class TestValidateReviewBug: mock_bug.product = namespace mock_bug.assigned_to = user mock_bug.creator = user - mock_bug.flags = [ - { - "name": "fedora-review", - "status": "" - } - ] + mock_bug.flags = [{"name": "fedora-review", "status": ""}] mock_bz.get_bug.return_value = mock_bug - mock_fas.get_user_by_email.return_value = { - "username": user - } + mock_fas.get_user_by_email.return_value = {"username": user} mock_fas.user_member_of.return_value = False - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} error = ( - 'The Bugzilla bug\'s review ' + "The Bugzilla bug's review " 'is approved by a user "{0}" that is ' - 'not a packager or FAS check failed'.format( - user) + "not a packager or FAS check failed".format(user) ) # Method to test @@ -2189,13 +2019,9 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(user) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(user)]) - mock_fas.user_member_of.assert_called_with( - {"username": user}, "packager" - ) + mock_fas.user_member_of.assert_called_with({"username": user}, "packager") @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -2215,31 +2041,17 @@ class TestValidateReviewBug: mock_bug.product = namespace mock_bug.assigned_to = user mock_bug.creator = user - mock_bug.flags = [ - { - "name": "fedora-review", - "status": "" - } - ] + mock_bug.flags = [{"name": "fedora-review", "status": ""}] mock_bz.get_bug.return_value = mock_bug - mock_fas.get_user_by_email.return_value = { - "username": user - } + mock_fas.get_user_by_email.return_value = {"username": user} mock_fas.user_member_of.side_effect = [True, False] - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} - error = ( - 'The Bugzilla reporter "{0}"' - 'is not a packager'.format(user) - ) + error = 'The Bugzilla reporter "{0}"' "is not a packager".format(user) # Method to test with pytest.raises(ValidationError, match=error): @@ -2248,14 +2060,14 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(user) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(user)]) - mock_fas.user_member_of.assert_has_calls([ - call({"username": user}, "packager"), - call({"username": user}, "packager"), - ]) + mock_fas.user_member_of.assert_has_calls( + [ + call({"username": user}, "packager"), + call({"username": user}, "packager"), + ] + ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -2275,32 +2087,20 @@ class TestValidateReviewBug: mock_bug.product = namespace mock_bug.assigned_to = user mock_bug.creator = user - mock_bug.flags = [ - { - "name": "fedora-review", - "status": "", - "setter": user - } - ] + mock_bug.flags = [{"name": "fedora-review", "status": "", "setter": user}] mock_bz.get_bug.return_value = mock_bug - mock_fas.get_user_by_email.return_value = { - "username": user - } + mock_fas.get_user_by_email.return_value = {"username": user} mock_fas.user_member_of.return_value = True - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} error = ( - 'The Bugzilla bug\'s review is approved ' - 'by the person creating the bug. This is ' - 'not allowed.' + "The Bugzilla bug's review is approved " + "by the person creating the bug. This is " + "not allowed." ) # Method to test @@ -2310,14 +2110,14 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(user) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(user)]) - mock_fas.user_member_of.assert_has_calls([ - call({"username": user}, "packager"), - call({"username": user}, "packager"), - ]) + mock_fas.user_member_of.assert_has_calls( + [ + call({"username": user}, "packager"), + call({"username": user}, "packager"), + ] + ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -2338,33 +2138,18 @@ class TestValidateReviewBug: mock_bug.assigned_to = user mock_bug.creator = user mock_bug.flags = [ - { - "name": "fedora-review", - "status": "", - "setter": "not@setter.com" - } + {"name": "fedora-review", "status": "", "setter": "not@setter.com"} ] mock_bz.get_bug.return_value = mock_bug - mock_fas.get_user_by_email.return_value = { - "username": user, - "emails": [] - } + mock_fas.get_user_by_email.return_value = {"username": user, "emails": []} mock_fas.user_member_of.return_value = True - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} - error = ( - 'The review is not approved by ' - 'the assignee of the Bugzilla ' - 'bug' - ) + error = "The review is not approved by " "the assignee of the Bugzilla " "bug" # Method to test with pytest.raises(ValidationError, match=error): @@ -2373,14 +2158,14 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(user) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(user)]) - mock_fas.user_member_of.assert_has_calls([ - call({"username": user, "emails": []}, "packager"), - call({"username": user, "emails": []}, "packager"), - ]) + mock_fas.user_member_of.assert_has_calls( + [ + call({"username": user, "emails": []}, "packager"), + call({"username": user, "emails": []}, "packager"), + ] + ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -2407,7 +2192,9 @@ class TestValidateReviewBug: "name": "fedora-review", "status": "", "setter": assignee, - "modification_date": arrow.utcnow().shift(days=-61).format("YYYY-MM-DDTHH-mm-ssZ") + "modification_date": arrow.utcnow() + .shift(days=-61) + .format("YYYY-MM-DDTHH-mm-ssZ"), } ] @@ -2418,17 +2205,10 @@ class TestValidateReviewBug: } mock_fas.user_member_of.return_value = True - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} - error = ( - 'The Bugzilla bug\'s review ' - 'was approved over 60 days ago' - ) + error = "The Bugzilla bug's review " "was approved over 60 days ago" # Method to test with pytest.raises(ValidationError, match=error): @@ -2437,14 +2217,14 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(assignee) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(assignee)]) - mock_fas.user_member_of.assert_has_calls([ - call({"username": user}, "packager"), - call({"username": user}, "packager"), - ]) + mock_fas.user_member_of.assert_has_calls( + [ + call({"username": user}, "packager"), + call({"username": user}, "packager"), + ] + ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -2471,16 +2251,10 @@ class TestValidateReviewBug: "username": user, } - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} - error = ( - 'The Bugzilla bug is not approved yet' - ) + error = "The Bugzilla bug is not approved yet" # Method to test with pytest.raises(ValidationError, match=error): @@ -2489,25 +2263,27 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user)]) @pytest.mark.parametrize( "summary, error", [ ("", 'Invalid title for this Bugzilla bug (no ":" present)'), ("Review: package", 'Invalid title for this Bugzilla bug (no "-" present)'), - ("Review: package - 1.0", ( + ( + "Review: package - 1.0", + ( 'The package in the Bugzilla bug "package" doesn\'t match ' 'the one provided "repo"' - ) - ), - ] + ), + ), + ], ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") - def test_validate_review_bug_invalid_summary(self, mock_bz, mock_fas, summary, error): + def test_validate_review_bug_invalid_summary( + self, mock_bz, mock_fas, summary, error + ): """ Assert that error will be raised when bug summary is not correct. """ @@ -2531,7 +2307,7 @@ class TestValidateReviewBug: "name": "fedora-review", "status": "+", "setter": assignee, - "modification_date": arrow.utcnow().format("YYYY-MM-DDTHH-mm-ssZ") + "modification_date": arrow.utcnow().format("YYYY-MM-DDTHH-mm-ssZ"), } ] @@ -2542,12 +2318,8 @@ class TestValidateReviewBug: } mock_fas.user_member_of.return_value = True - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} # Method to test with pytest.raises(ValidationError, match=re.escape(error)): @@ -2556,14 +2328,14 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(assignee) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(assignee)]) - mock_fas.user_member_of.assert_has_calls([ - call({"username": user}, "packager"), - call({"username": user}, "packager"), - ]) + mock_fas.user_member_of.assert_has_calls( + [ + call({"username": user}, "packager"), + call({"username": user}, "packager"), + ] + ) @patch("toddlers.plugins.scm_request_processor.fedora_account") @patch("toddlers.plugins.scm_request_processor.bugzilla_system") @@ -2591,11 +2363,11 @@ class TestValidateReviewBug: "name": "fedora-review", "status": "+", "setter": assignee, - "modification_date": arrow.utcnow().format("YYYY-MM-DDTHH-mm-ssZ") + "modification_date": arrow.utcnow().format("YYYY-MM-DDTHH-mm-ssZ"), }, { "name": "random-flag", - } + }, ] mock_bz.get_bug.return_value = mock_bug @@ -2605,12 +2377,8 @@ class TestValidateReviewBug: } mock_fas.user_member_of.return_value = True - self.toddler.pagure_namespace_to_component = { - namespace: namespace - } - self.toddler.pagure_namespace_to_product = { - namespace: [namespace, namespace] - } + self.toddler.pagure_namespace_to_component = {namespace: namespace} + self.toddler.pagure_namespace_to_product = {namespace: [namespace, namespace]} # Method to test self.toddler.validate_review_bug(bug_id, repo, branch, pagure_user=user) @@ -2618,14 +2386,14 @@ class TestValidateReviewBug: # Asserts mock_bz.get_bug.assert_called_with(bug_id) - mock_fas.get_user_by_email.assert_has_calls([ - call(user), call(assignee) - ]) + mock_fas.get_user_by_email.assert_has_calls([call(user), call(assignee)]) - mock_fas.user_member_of.assert_has_calls([ - call({"username": user}, "packager"), - call({"username": user}, "packager"), - ]) + mock_fas.user_member_of.assert_has_calls( + [ + call({"username": user}, "packager"), + call({"username": user}, "packager"), + ] + ) class TestValidEpelPackage: @@ -2677,11 +2445,7 @@ class TestValidEpelPackage: mock_response.status_code = 200 mock_response.json.return_value = { "arches": ["noarch", "ppc", "i386"], - "packages": { - name: { - "arch": ["noarch"] - } - } + "packages": {name: {"arch": ["noarch"]}}, } self.toddler.requests_session.get.return_value = mock_response @@ -2707,11 +2471,7 @@ class TestValidEpelPackage: mock_response.status_code = 200 mock_response.json.return_value = { "arches": ["noarch", "ppc", "i386"], - "packages": { - name: { - "arch": ["noarch"] - } - } + "packages": {name: {"arch": ["noarch"]}}, } self.toddler.requests_session.get.return_value = mock_response @@ -2737,11 +2497,7 @@ class TestValidEpelPackage: mock_response.status_code = 200 mock_response.json.return_value = { "arches": ["noarch", "ppc", "i386"], - "packages": { - name: { - "arch": ["x86_64"] - } - } + "packages": {name: {"arch": ["x86_64"]}}, } self.toddler.requests_session.get.return_value = mock_response diff --git a/tests/utils/test_bugzilla_system.py b/tests/utils/test_bugzilla_system.py index 3a95da6..1022239 100644 --- a/tests/utils/test_bugzilla_system.py +++ b/tests/utils/test_bugzilla_system.py @@ -1078,7 +1078,9 @@ class TestCommentOnBug: assert exc.value.args == ({"id": bug_id, "comment": comment}, 50, "Fault") mock_bz.assert_called_with() - mock_bz_call.assert_called_with(server.comment, {"id": bug_id, "comment": comment}) + mock_bz_call.assert_called_with( + server.comment, {"id": bug_id, "comment": comment} + ) @patch("toddlers.utils.bugzilla_system.execute_bugzilla_call") @patch("toddlers.utils.bugzilla_system.get_bz") @@ -1100,7 +1102,9 @@ class TestCommentOnBug: assert exc.value.args == ("ProtocolError", 10, "Error message") mock_bz.assert_called_with() - mock_bz_call.assert_called_with(server.comment, {"id": bug_id, "comment": comment}) + mock_bz_call.assert_called_with( + server.comment, {"id": bug_id, "comment": comment} + ) class TestExecuteBugzillaCall: diff --git a/tests/utils/test_fedora_account_fasjson.py b/tests/utils/test_fedora_account_fasjson.py index b5fd131..c15e37b 100644 --- a/tests/utils/test_fedora_account_fasjson.py +++ b/tests/utils/test_fedora_account_fasjson.py @@ -204,15 +204,12 @@ class TestFedoraAccountFASJSON: mock_fas.return_value = server group = "group" - user = { - "username": "user" - } + user = {"username": "user"} output = toddlers.utils.fedora_account.user_member_of(user, group) server.check_membership.assert_called_with( - groupname=group, - username=user["username"] + groupname=group, username=user["username"] ) assert output is True @@ -229,15 +226,12 @@ class TestFedoraAccountFASJSON: mock_fas.return_value = server group = "group" - user = { - "username": "user" - } + user = {"username": "user"} output = toddlers.utils.fedora_account.user_member_of(user, group) server.check_membership.assert_called_with( - groupname=group, - username=user["username"] + groupname=group, username=user["username"] ) assert output is False @@ -252,9 +246,7 @@ class TestFedoraAccountFASJSON: output = toddlers.utils.fedora_account.get_user_by_username("scoady") - server.search.assert_called_with( - username="scoady" - ) + server.search.assert_called_with(username="scoady") assert output == {"username": "scoady", "emails": ["scoady@fp.o"]} @patch("toddlers.utils.fedora_account.get_fasjson") @@ -268,9 +260,7 @@ class TestFedoraAccountFASJSON: output = toddlers.utils.fedora_account.get_user_by_username("scoady") - server.search.assert_called_with( - username="scoady" - ) + server.search.assert_called_with(username="scoady") assert output is None @patch("toddlers.utils.fedora_account.get_fasjson") @@ -284,7 +274,5 @@ class TestFedoraAccountFASJSON: output = toddlers.utils.fedora_account.get_user_by_username("scoady") - server.search.assert_called_with( - username="scoady" - ) + server.search.assert_called_with(username="scoady") assert output is None diff --git a/tests/utils/test_git.py b/tests/utils/test_git.py index a7f9664..87dd855 100644 --- a/tests/utils/test_git.py +++ b/tests/utils/test_git.py @@ -5,6 +5,7 @@ from unittest.mock import Mock, patch from toddlers.utils.git import clone_repo, GitRepo + class TestCloneRepo: """ Test class for `toddlers.utils.git.clone_repo` function. @@ -70,9 +71,7 @@ class TestGitRepoFirstCommit: commit = self.repo.first_commit(branch) - self.repo.repo.git.rev_list.assert_called_with( - "--max-parents=0", branch - ) + self.repo.repo.git.rev_list.assert_called_with("--max-parents=0", branch) assert commit == "hash" @@ -88,9 +87,7 @@ class TestGitRepoFirstCommit: commit = self.repo.first_commit(branch) - self.repo.repo.git.rev_list.assert_called_with( - "--max-parents=0", branch - ) + self.repo.repo.git.rev_list.assert_called_with("--max-parents=0", branch) assert commit == "last_hash" @@ -106,8 +103,6 @@ class TestGitRepoFirstCommit: commit = self.repo.first_commit(branch) - self.repo.repo.git.rev_list.assert_called_with( - "--max-parents=0", branch - ) + self.repo.repo.git.rev_list.assert_called_with("--max-parents=0", branch) assert commit is None diff --git a/tests/utils/test_pagure.py b/tests/utils/test_pagure.py index 46b6e8c..d07ce26 100644 --- a/tests/utils/test_pagure.py +++ b/tests/utils/test_pagure.py @@ -19,7 +19,7 @@ class TestPagureSetPagure: """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } pagure_obj = pagure.set_pagure() @@ -43,9 +43,7 @@ class TestPagureSetPagure: with pytest.raises( ValueError, match=r"No pagure_api_key found in the configuration file" ): - config = { - "pagure_url": "https://pagure.io" - } + config = {"pagure_url": "https://pagure.io"} pagure.set_pagure(config) @@ -53,13 +51,14 @@ class TestPagureGetAuthHeader: """ Test class for `toddlers.pagure.Pagure.get_auth_header` function. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) @@ -68,9 +67,9 @@ class TestPagureGetAuthHeader: Assert that correct header is returned. """ exp_header = { - 'Authorization': 'token Very secret key', - 'Accept': 'application/json', - 'Content-Type': 'application/json' + "Authorization": "token Very secret key", + "Accept": "application/json", + "Content-Type": "application/json", } header = self.pagure.get_auth_header() @@ -82,13 +81,14 @@ class TestPagureCloseIssue: """ Test class for `toddlers.pagure.Pagure.close_issue` function. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -114,7 +114,7 @@ class TestPagureCloseIssue: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/test/issue/100/status", data={"status": reason}, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_close_issue_not_ok(self): @@ -134,14 +134,16 @@ class TestPagureCloseIssue: expected_error = "Couldn't close issue 'https://pagure.io/test/issue/100'" with pytest.raises(PagureError, match=expected_error): - with patch("toddlers.utils.pagure.Pagure.add_comment_to_issue") as comment_mock: + with patch( + "toddlers.utils.pagure.Pagure.add_comment_to_issue" + ) as comment_mock: comment_mock.return_value = True result = self.pagure.close_issue(issue_id, namespace, message, reason) self.pagure._requests_session.post.assert_called_with( "https://pagure.io/test/issue/100/status", data={"status": reason}, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) @@ -149,13 +151,14 @@ class TestPagureAddCommentToIssue: """ Test class for `toddlers.pagure.Pagure.add_comment_to_issue` function. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -178,7 +181,7 @@ class TestPagureAddCommentToIssue: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/test/issue/100/comment", data={"comment": message}, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_add_comment_to_issue_not_ok(self): @@ -202,7 +205,7 @@ class TestPagureAddCommentToIssue: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/test/issue/100/comment", data={"comment": message}, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) @@ -210,13 +213,14 @@ class TestPagureUserExists: """ Test class for `toddlers.pagure.Pagure.user_exists` function. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -286,13 +290,14 @@ class TestPagureNewProject: """ Test class for `toddlers.pagure.Pagure.new_project` method. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -312,19 +317,21 @@ class TestPagureNewProject: description = "description" upstream_url = "https://example.com" - self.pagure.new_project(namespace, repo, description, upstream_url, default_branch) + self.pagure.new_project( + namespace, repo, description, upstream_url, default_branch + ) self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/new", data={ - 'namespace': namespace, - 'name': repo, - 'default_branch': default_branch, - 'description': description, - 'url': upstream_url, - 'wait': True + "namespace": namespace, + "name": repo, + "default_branch": default_branch, + "description": description, + "url": upstream_url, + "wait": True, }, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_new_project_initial_commit(self): @@ -343,21 +350,26 @@ class TestPagureNewProject: upstream_url = "https://example.com" self.pagure.new_project( - namespace, repo, description, upstream_url, default_branch, initial_commit=True + namespace, + repo, + description, + upstream_url, + default_branch, + initial_commit=True, ) self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/new", data={ - 'namespace': namespace, - 'name': repo, - 'default_branch': default_branch, - 'description': description, - 'url': upstream_url, - 'wait': True, - 'create_readme': True + "namespace": namespace, + "name": repo, + "default_branch": default_branch, + "description": description, + "url": upstream_url, + "wait": True, + "create_readme": True, }, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_new_project_alias(self): @@ -379,28 +391,32 @@ class TestPagureNewProject: namespace, repo, description, upstream_url, default_branch, alias=True ) - self.pagure._requests_session.post.assert_has_calls([ - call( - "https://pagure.io/api/0/new", - data={ - 'namespace': namespace, - 'name': repo, - 'default_branch': default_branch, - 'description': description, - 'url': upstream_url, - 'wait': True - }, - headers=self.pagure.get_auth_header() - ), - call( - "https://pagure.io/api/0/{0}/{1}/git/alias/new".format(namespace, repo), - data={ - 'alias_from': 'main', - 'alias_to': 'rawhide', - }, - headers=self.pagure.get_auth_header() - ), - ]) + self.pagure._requests_session.post.assert_has_calls( + [ + call( + "https://pagure.io/api/0/new", + data={ + "namespace": namespace, + "name": repo, + "default_branch": default_branch, + "description": description, + "url": upstream_url, + "wait": True, + }, + headers=self.pagure.get_auth_header(), + ), + call( + "https://pagure.io/api/0/{0}/{1}/git/alias/new".format( + namespace, repo + ), + data={ + "alias_from": "main", + "alias_to": "rawhide", + }, + headers=self.pagure.get_auth_header(), + ), + ] + ) def test_new_project_alias_wrong_namespace(self): """ @@ -425,14 +441,14 @@ class TestPagureNewProject: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/new", data={ - 'namespace': namespace, - 'name': repo, - 'default_branch': default_branch, - 'description': description, - 'url': upstream_url, - 'wait': True + "namespace": namespace, + "name": repo, + "default_branch": default_branch, + "description": description, + "url": upstream_url, + "wait": True, }, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_new_project_failure(self): @@ -460,14 +476,14 @@ class TestPagureNewProject: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/new", data={ - 'namespace': namespace, - 'name': repo, - 'default_branch': default_branch, - 'description': description, - 'url': upstream_url, - 'wait': True + "namespace": namespace, + "name": repo, + "default_branch": default_branch, + "description": description, + "url": upstream_url, + "wait": True, }, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_new_project_alias_failure(self): @@ -480,7 +496,10 @@ class TestPagureNewProject: response_mock_fail = Mock() response_mock_fail.status_code = 500 - self.pagure._requests_session.post.side_effect = [response_mock_ok, response_mock_fail] + self.pagure._requests_session.post.side_effect = [ + response_mock_ok, + response_mock_fail, + ] namespace = "rpms" repo = "repo" @@ -488,48 +507,55 @@ class TestPagureNewProject: description = "description" upstream_url = "https://example.com" - expected_error = "Couldn't create alias for project '{0}/{1}'".format(namespace, repo) + expected_error = "Couldn't create alias for project '{0}/{1}'".format( + namespace, repo + ) with pytest.raises(PagureError, match=expected_error): self.pagure.new_project( namespace, repo, description, upstream_url, default_branch, alias=True ) - self.pagure._requests_session.post.assert_has_calls([ - call( - "https://pagure.io/api/0/new", - data={ - 'namespace': namespace, - 'name': repo, - 'default_branch': default_branch, - 'description': description, - 'url': upstream_url, - 'wait': True - }, - headers=self.pagure.get_auth_header() - ), - call( - "https://pagure.io/api/0/{0}/{1}/git/alias/new".format(namespace, repo), - data={ - 'alias_from': 'main', - 'alias_to': 'rawhide', - }, - headers=self.pagure.get_auth_header() - ), - ]) + self.pagure._requests_session.post.assert_has_calls( + [ + call( + "https://pagure.io/api/0/new", + data={ + "namespace": namespace, + "name": repo, + "default_branch": default_branch, + "description": description, + "url": upstream_url, + "wait": True, + }, + headers=self.pagure.get_auth_header(), + ), + call( + "https://pagure.io/api/0/{0}/{1}/git/alias/new".format( + namespace, repo + ), + data={ + "alias_from": "main", + "alias_to": "rawhide", + }, + headers=self.pagure.get_auth_header(), + ), + ] + ) class TestPagureNewBranch: """ Test class for `toddlers.pagure.Pagure.new_branch` method. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -553,10 +579,10 @@ class TestPagureNewBranch: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/{0}/{1}/git/branch".format(namespace, repo), data={ - 'branch': branch, - 'from_commit': from_commit, + "branch": branch, + "from_commit": from_commit, }, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_new_branch_from_branch(self): @@ -578,10 +604,10 @@ class TestPagureNewBranch: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/{0}/{1}/git/branch".format(namespace, repo), data={ - 'branch': branch, - 'from_branch': from_branch, + "branch": branch, + "from_branch": from_branch, }, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) def test_new_branch_missing_required_params(self): @@ -597,13 +623,10 @@ class TestPagureNewBranch: repo = "repo" branch = "branch" - expected_error = ("You must specify either `from_commit` or " - "`from_branch`") + expected_error = "You must specify either `from_commit` or " "`from_branch`" with pytest.raises(RuntimeError, match=expected_error): - self.pagure.new_branch( - namespace, repo, branch - ) + self.pagure.new_branch(namespace, repo, branch) def test_new_branch_missing_required_params(self): """ @@ -620,12 +643,17 @@ class TestPagureNewBranch: from_branch = "existing_branch" from_commit = "commit" - expected_error = ("`from_commit` and `from_branch` were both " - "specified. Only use one.") + expected_error = ( + "`from_commit` and `from_branch` were both " "specified. Only use one." + ) with pytest.raises(RuntimeError, match=expected_error): self.pagure.new_branch( - namespace, repo, branch, from_branch=from_branch, from_commit=from_commit + namespace, + repo, + branch, + from_branch=from_branch, + from_commit=from_commit, ) def test_new_branch_failure(self): @@ -642,20 +670,20 @@ class TestPagureNewBranch: branch = "branch" from_branch = "existing_branch" - expected_error = "Couldn't create branch in project '{0}/{1}'".format(namespace, repo) + expected_error = "Couldn't create branch in project '{0}/{1}'".format( + namespace, repo + ) with pytest.raises(PagureError, match=expected_error): - self.pagure.new_branch( - namespace, repo, branch, from_branch=from_branch - ) + self.pagure.new_branch(namespace, repo, branch, from_branch=from_branch) self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/{0}/{1}/git/branch".format(namespace, repo), data={ - 'branch': branch, - 'from_branch': from_branch, + "branch": branch, + "from_branch": from_branch, }, - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) @@ -663,13 +691,14 @@ class TestPagureSetMonitoringStatus: """ Test class for `toddlers.pagure.Pagure.set_monitoring_status` method. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -691,10 +720,8 @@ class TestPagureSetMonitoringStatus: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/_dg/anitya/{0}/{1}".format(namespace, repo), - data={ - 'anitya_status': monitoring_level - }, - headers=self.pagure.get_auth_header() + data={"anitya_status": monitoring_level}, + headers=self.pagure.get_auth_header(), ) def test_set_monitoring_status_failure(self): @@ -710,19 +737,17 @@ class TestPagureSetMonitoringStatus: repo = "repo" monitoring_level = "no_monitoring" - expected_error = "Couldn't set monitoring on project '{0}/{1}'".format(namespace, repo) + expected_error = "Couldn't set monitoring on project '{0}/{1}'".format( + namespace, repo + ) with pytest.raises(PagureError, match=expected_error): - self.pagure.set_monitoring_status( - namespace, repo, monitoring_level - ) + self.pagure.set_monitoring_status(namespace, repo, monitoring_level) self.pagure._requests_session.post.assert_called_with( "https://pagure.io/_dg/anitya/{0}/{1}".format(namespace, repo), - data={ - 'anitya_status': monitoring_level - }, - headers=self.pagure.get_auth_header() + data={"anitya_status": monitoring_level}, + headers=self.pagure.get_auth_header(), ) @@ -730,13 +755,14 @@ class TestPagureChangeProjectMainAdmin: """ Test class for `toddlers.pagure.Pagure.change_project_main_admin` method. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -758,10 +784,8 @@ class TestPagureChangeProjectMainAdmin: self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/{0}/{1}".format(namespace, repo), - data={ - 'main_admin': main_admin - }, - headers=self.pagure.get_auth_header() + data={"main_admin": main_admin}, + headers=self.pagure.get_auth_header(), ) def test_change_project_main_admin_failure(self): @@ -777,19 +801,17 @@ class TestPagureChangeProjectMainAdmin: repo = "repo" main_admin = "zlopez" - expected_error = "Couldn't set new admin on project '{0}/{1}'".format(namespace, repo) + expected_error = "Couldn't set new admin on project '{0}/{1}'".format( + namespace, repo + ) with pytest.raises(PagureError, match=expected_error): - self.pagure.change_project_main_admin( - namespace, repo, main_admin - ) + self.pagure.change_project_main_admin(namespace, repo, main_admin) self.pagure._requests_session.post.assert_called_with( "https://pagure.io/api/0/{0}/{1}".format(namespace, repo), - data={ - 'main_admin': main_admin - }, - headers=self.pagure.get_auth_header() + data={"main_admin": main_admin}, + headers=self.pagure.get_auth_header(), ) @@ -797,13 +819,14 @@ class TestPagureGetProjectContributors: """ Test class for `toddlers.pagure.Pagure.get_project_contributors` method. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -829,7 +852,7 @@ class TestPagureGetProjectContributors: self.pagure._requests_session.get.assert_called_with( "https://pagure.io/api/0/{0}/{1}/contributors".format(namespace, repo), - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) assert result == data @@ -846,16 +869,16 @@ class TestPagureGetProjectContributors: namespace = "namespace" repo = "repo" - expected_error = "Couldn't get contributors for project '{0}/{1}'".format(namespace, repo) + expected_error = "Couldn't get contributors for project '{0}/{1}'".format( + namespace, repo + ) with pytest.raises(PagureError, match=expected_error): - self.pagure.get_project_contributors( - namespace, repo - ) + self.pagure.get_project_contributors(namespace, repo) self.pagure._requests_session.get.assert_called_with( "https://pagure.io/api/0/{0}/{1}/contributors".format(namespace, repo), - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) @@ -863,13 +886,14 @@ class TestPagureGetDefaultBranch: """ Test class for `toddlers.pagure.Pagure.get_default_branch` method. """ + def setup(self): """ Setup method for the test class. """ config = { "pagure_url": "https://pagure.io", - "pagure_api_key": "Very secret key" + "pagure_api_key": "Very secret key", } self.pagure = pagure.set_pagure(config) self.pagure._requests_session = Mock() @@ -895,7 +919,7 @@ class TestPagureGetDefaultBranch: self.pagure._requests_session.get.assert_called_with( "https://pagure.io/api/0/{0}/{1}/git/branches".format(namespace, repo), - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) assert result == branch @@ -920,7 +944,7 @@ class TestPagureGetDefaultBranch: self.pagure._requests_session.get.assert_called_with( "https://pagure.io/api/0/{0}/{1}/git/branches".format(namespace, repo), - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) assert result is None @@ -937,14 +961,14 @@ class TestPagureGetDefaultBranch: namespace = "namespace" repo = "repo" - expected_error = "Couldn't get default branch for project '{0}/{1}'".format(namespace, repo) + expected_error = "Couldn't get default branch for project '{0}/{1}'".format( + namespace, repo + ) with pytest.raises(PagureError, match=expected_error): - self.pagure.get_default_branch( - namespace, repo - ) + self.pagure.get_default_branch(namespace, repo) self.pagure._requests_session.get.assert_called_with( "https://pagure.io/api/0/{0}/{1}/git/branches".format(namespace, repo), - headers=self.pagure.get_auth_header() + headers=self.pagure.get_auth_header(), ) diff --git a/tests/utils/test_pdc.py b/tests/utils/test_pdc.py index 7180f88..e1911f5 100644 --- a/tests/utils/test_pdc.py +++ b/tests/utils/test_pdc.py @@ -19,7 +19,7 @@ class TestPdcSetPdc: "pdc_config": { "server": "https://pdc.fedoraproject.org/rest_api/v1/", "ssl_verify": False, - "token": "token" + "token": "token", } } pdc_client = pdc.set_pdc(config) @@ -41,13 +41,14 @@ class TestPdcPdcClientForConfig: "pdc_config": { "server": "https://pdc.fedoraproject.org/rest_api/v1/", "ssl_verify": False, - "token": "token" + "token": "token", } } pdc_client = pdc.pdc_client_for_config(config) assert pdc_client + class TestPdcGetSla: """ Test class for `toddlers.utils.pdc.get_sla` function. @@ -63,7 +64,7 @@ class TestPdcGetSla: """ Assert that correct response is handled. """ - response = {"count": 1, "results":[{"id": 3}]} + response = {"count": 1, "results": [{"id": 3}]} pdc._PDC["component-sla-types"]._.return_value = response @@ -75,7 +76,7 @@ class TestPdcGetSla: """ Assert that incorrect response is handled. """ - response = {"count": 0, "results":[]} + response = {"count": 0, "results": []} pdc._PDC["component-sla-types"]._.return_value = response @@ -110,18 +111,18 @@ class TestPdcNewSLAToBranch: eol=eol, global_component=global_component, branch=branch_name, - branch_type=branch_type + branch_type=branch_type, ) pdc._PDC["component-branch-slas"]._.assert_called_with( { - 'sla': sla, - 'eol': eol, - 'branch': { - 'global_component': global_component, - 'name': branch_name, - 'type': branch_type - } + "sla": sla, + "eol": eol, + "branch": { + "global_component": global_component, + "name": branch_name, + "type": branch_type, + }, } ) @@ -141,7 +142,7 @@ class TestPdcGetBranch: """ Assert that correct response is handled. """ - response = {"count": 1, "results":[{"id": 3}]} + response = {"count": 1, "results": [{"id": 3}]} global_component = "global_component" name = "branch" @@ -154,16 +155,14 @@ class TestPdcGetBranch: assert result == {"id": 3} pdc._PDC["component-branches"]._.assert_called_with( - global_component=global_component, - name=name, - type=branch_type + global_component=global_component, name=name, type=branch_type ) def test_get_branch_not_found(self): """ Assert that incorrect response is handled. """ - response = {"count": 0, "results":[]} + response = {"count": 0, "results": []} global_component = "global_component" name = "branch" @@ -176,9 +175,7 @@ class TestPdcGetBranch: assert not result pdc._PDC["component-branches"]._.assert_called_with( - global_component=global_component, - name=name, - type=branch_type + global_component=global_component, name=name, type=branch_type ) @@ -197,7 +194,7 @@ class TestPdcNewBranch: """ Assert that component is not created when it doesn't exist. """ - response = {"count": 1, "results":[{"id": 3}]} + response = {"count": 1, "results": [{"id": 3}]} global_component = "global_component" branch = "branch" @@ -208,16 +205,14 @@ class TestPdcNewBranch: pdc.new_branch(global_component, branch, branch_type) pdc._PDC["component-branches"]._.assert_called_with( - global_component=global_component, - name=branch, - type=branch_type + global_component=global_component, name=branch, type=branch_type ) def test_new_branch_not_found(self): """ Assert that component is created when not found. """ - response = {"count": 0, "results":[]} + response = {"count": 0, "results": []} global_component = "global_component" branch = "branch" @@ -229,18 +224,14 @@ class TestPdcNewBranch: pdc._PDC["component-branches"]._.assert_has_calls( [ - call( - global_component=global_component, - name=branch, - type=branch_type - ), + call(global_component=global_component, name=branch, type=branch_type), call( { "global_component": global_component, "name": branch, - "type": branch_type + "type": branch_type, } - ) + ), ] ) @@ -260,7 +251,7 @@ class TestPdcGetGlobalComponent: """ Assert that correct response is handled. """ - response = {"count": 1, "results":[{"id": 3}]} + response = {"count": 1, "results": [{"id": 3}]} global_component = "global_component" @@ -278,7 +269,7 @@ class TestPdcGetGlobalComponent: """ Assert that incorrect response is handled. """ - response = {"count": 0, "results":[]} + response = {"count": 0, "results": []} global_component = "global_component" @@ -308,7 +299,7 @@ class TestPdcNewGlobalComponent: """ Assert that component is not created when it doesn't exist. """ - response = {"count": 1, "results":[{"id": 3}]} + response = {"count": 1, "results": [{"id": 3}]} global_component = "global_component" dist_git_url = "https://src.fedoraproject.org/example" @@ -325,7 +316,7 @@ class TestPdcNewGlobalComponent: """ Assert that component is created when not found. """ - response = {"count": 0, "results":[]} + response = {"count": 0, "results": []} global_component = "global_component" dist_git_url = "https://src.fedoraproject.org/example" @@ -337,11 +328,6 @@ class TestPdcNewGlobalComponent: pdc._PDC["global-components"]._.assert_has_calls( [ call(name=global_component), - call( - { - "name": global_component, - "dist_git_web_url": dist_git_url - } - ) + call({"name": global_component, "dist_git_web_url": dist_git_url}), ] ) diff --git a/toddlers/exceptions/pagure_error.py b/toddlers/exceptions/pagure_error.py index cdf84dd..ccddbb0 100644 --- a/toddlers/exceptions/pagure_error.py +++ b/toddlers/exceptions/pagure_error.py @@ -1,5 +1,7 @@ """ Exception that is raised by pagure module. """ + + class PagureError(Exception): pass diff --git a/toddlers/exceptions/validation_error.py b/toddlers/exceptions/validation_error.py index e1483e1..405b65e 100644 --- a/toddlers/exceptions/validation_error.py +++ b/toddlers/exceptions/validation_error.py @@ -1,5 +1,7 @@ """ Exception that is raised when validation fails. """ + + class ValidationError(Exception): pass diff --git a/toddlers/plugins/scm_request_processor.py b/toddlers/plugins/scm_request_processor.py index ae3d690..340366d 100644 --- a/toddlers/plugins/scm_request_processor.py +++ b/toddlers/plugins/scm_request_processor.py @@ -21,21 +21,22 @@ from toddlers.utils import bugzilla_system, fedora_account, git, pagure, pdc, re from toddlers.exceptions import ValidationError # Regex for branch name validation -STREAM_NAME_REGEX=r'^[a-zA-Z0-9.\-_+]+$' +STREAM_NAME_REGEX = r"^[a-zA-Z0-9.\-_+]+$" # Regex for project name validation -PROJECT_NAME_REGEX=r'^[a-zA-Z0-9_][a-zA-Z0-9-_.+]*$' +PROJECT_NAME_REGEX = r"^[a-zA-Z0-9_][a-zA-Z0-9-_.+]*$" # Regex for epel branch validation -EPEL_REGEX=r'^epel\d+(?:-playground|-next)?$' +EPEL_REGEX = r"^epel\d+(?:-playground|-next)?$" # Where to look for the scm-requests tickets -PROJECT_NAMESPACE="releng/fedora-scm-requests" +PROJECT_NAMESPACE = "releng/fedora-scm-requests" # ERROR returned for invalid EPEL request INVALID_EPEL_ERROR = ( - 'This package is already an EL package and is built on all supported ' - 'arches, therefore, it cannot be in EPEL. If this is a mistake or you ' - 'have an exception, please contact the Release Engineering team at' - 'https://pagure.io/releng/issues') + "This package is already an EL package and is built on all supported " + "arches, therefore, it cannot be in EPEL. If this is a mistake or you " + "have an exception, please contact the Release Engineering team at" + "https://pagure.io/releng/issues" +) _log = logging.getLogger(__name__) @@ -50,7 +51,7 @@ class SCMRequestProcessor(ToddlerBase): amqp_topics = [ "org.fedoraproject.*.pagure.issue.new", - "org.fedoraproject.*.pagure.issue.edit" + "org.fedoraproject.*.pagure.issue.edit", ] # SLAs for branches @@ -107,7 +108,9 @@ class SCMRequestProcessor(ToddlerBase): if project_name is not PROJECT_NAMESPACE: _log.info( - "The message doesn't belong to project {0}. Skipping message.".format(PROJECT_NAMESPACE) + "The message doesn't belong to project {0}. Skipping message.".format( + PROJECT_NAMESPACE + ) ) return @@ -135,7 +138,7 @@ class SCMRequestProcessor(ToddlerBase): _log.info("Setting up connection to Dist-Git") dist_git_config = { "pagure_url": config.get("dist_git_url"), - "pagure_api_key": config.get("dist_git_token") + "pagure_api_key": config.get("dist_git_token"), } self.dist_git = pagure.set_pagure(dist_git_config) @@ -157,91 +160,103 @@ class SCMRequestProcessor(ToddlerBase): _log.info("Handling pagure ticket '{0}'".format(issue["full_url"])) try: # If a ValueError is raised, that means it isn't valid JSON - issue_body = json.loads(issue['content'].strip('`').strip('\n')) + issue_body = json.loads(issue["content"].strip("`").strip("\n")) except ValueError: _log.info("Invalid JSON in ticket. Closing '{0}'".format(issue["full_url"])) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message="Invalid JSON provided", - reason="Invalid" + reason="Invalid", ) return - if 'sls' in issue_body: + if "sls" in issue_body: try: # If a ValueError is raised, that means they aren't valid SLAs - _log.info('- Verifying service-levels from the ticket.') - self.verify_slas(issue_body.get('branch', None), issue_body['sls']) + _log.info("- Verifying service-levels from the ticket.") + self.verify_slas(issue_body.get("branch", None), issue_body["sls"]) except ValidationError as error: - _log.info("Couldn't verify SLAs. Closing '{0}'".format(issue["full_url"])) + _log.info( + "Couldn't verify SLAs. Closing '{0}'".format(issue["full_url"]) + ) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=str(error), - reason="Invalid" + reason="Invalid", ) return else: - branch = issue_body.get('branch', '').strip() - if issue_body.get('action') in ['new_repo', 'new_branch'] and branch: + branch = issue_body.get("branch", "").strip() + if issue_body.get("action") in ["new_repo", "new_branch"] and branch: try: # If the SLAs aren't defined and the branch is a standard # branch, an SLA will be assigned. Otherwise, close this ticket # as bad for missing the SLA. - issue_body['sls'] = self.branch_slas[branch] + issue_body["sls"] = self.branch_slas[branch] except KeyError: - _log.info("Couldn't find standard SLAs. Closing '{0}'".format(issue["full_url"])) + _log.info( + "Couldn't find standard SLAs. Closing '{0}'".format( + issue["full_url"] + ) + ) error = "Couldn't find standard SLA for branch '{0}'".format(branch) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=error, - reason="Invalid" + reason="Invalid", ) return - if 'branch' in issue_body and 'namespace' in issue_body: - branch = issue_body['branch'] - ns = issue_body['namespace'] - if ns in ['modules', 'test-modules', 'flatpaks']: + if "branch" in issue_body and "namespace" in issue_body: + branch = issue_body["branch"] + ns = issue_body["namespace"] + if ns in ["modules", "test-modules", "flatpaks"]: # Validate that branch meets naming standards if not re.match(STREAM_NAME_REGEX, branch): - error_msg = ('Only characters, numbers, periods, dashes, underscores, ' - 'and pluses are allowed in {} branch names' - .format('flatpak' if ns == 'flatpaks' else 'module')) + error_msg = ( + "Only characters, numbers, periods, dashes, underscores, " + "and pluses are allowed in {} branch names".format( + "flatpak" if ns == "flatpaks" else "module" + ) + ) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=error_msg, - reason="Invalid" + reason="Invalid", ) return - if 'monitor' in issue_body \ - and issue_body['monitor'].strip() not in self.monitoring_choices: - error_msg = ('The monitor choice of "{0}" is invalid' - .format(issue_body['monitor'])) + if ( + "monitor" in issue_body + and issue_body["monitor"].strip() not in self.monitoring_choices + ): + error_msg = 'The monitor choice of "{0}" is invalid'.format( + issue_body["monitor"] + ) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=error_msg, - reason="Invalid" + reason="Invalid", ) return - if issue_body.get('action') == 'new_repo': - self.create_new_repo(issue, issue_body, - initial_commit=issue_body.get( - 'initial_commit', True)) - elif issue_body.get('action') == 'new_branch': + if issue_body.get("action") == "new_repo": + self.create_new_repo( + issue, issue_body, initial_commit=issue_body.get("initial_commit", True) + ) + elif issue_body.get("action") == "new_branch": self.create_new_branch(issue, issue_body) else: self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message="Invalid or missing action field", - reason="Invalid" + reason="Invalid", ) def verify_slas(self, branch: str, sla_dict: dict): @@ -257,38 +272,45 @@ class SCMRequestProcessor(ToddlerBase): couldn't be validated """ if not isinstance(sla_dict, dict): - raise ValueError('The object provided is not a dict') + raise ValueError("The object provided is not a dict") if branch is not None and branch in self.branch_slas: standard_branch_sla_dict = self.branch_slas.get(branch) if standard_branch_sla_dict == sla_dict: return else: - raise ValidationError('The SLAs for the branch "{0}" are ' - 'incorrect'.format(branch)) + raise ValidationError( + 'The SLAs for the branch "{0}" are ' "incorrect".format(branch) + ) for sla, eol in sla_dict.items(): if not isinstance(eol, str): raise ValidationError( - 'The SL\'s EOL is not a string. It was type "{0}".'.format(type(eol).__name__)) + 'The SL\'s EOL is not a string. It was type "{0}".'.format( + type(eol).__name__ + ) + ) try: - eol_date = arrow.get(eol, 'YYYY-MM-DD') + eol_date = arrow.get(eol, "YYYY-MM-DD") except ValueError: raise ValidationError( - 'The EOL date "{0}" is in an invalid format'.format(eol)) + 'The EOL date "{0}" is in an invalid format'.format(eol) + ) today = arrow.utcnow() if eol_date < today: - raise ValidationError( - 'The SL "{0}" is already expired'.format(eol)) + raise ValidationError('The SL "{0}" is already expired'.format(eol)) elif eol_date.month not in [6, 12] or eol_date.day != 1: raise ValidationError( - 'The SL "{0}" must expire on June 1st or December 1st'.format(eol)) + 'The SL "{0}" must expire on June 1st or December 1st'.format(eol) + ) sla_obj = pdc.get_sla(sla) if not sla_obj: raise ValidationError('The SL "{0}" is not in PDC'.format(sla)) - def create_new_repo(self, issue: dict, issue_body_json: dict, initial_commit:bool = True): + def create_new_repo( + self, issue: dict, issue_body_json: dict, initial_commit: bool = True + ): """ A helper function that process request for new repo. @@ -300,210 +322,255 @@ class SCMRequestProcessor(ToddlerBase): """ _log.info("New repo was requested. Validating request.") required_keys = [ - 'repo', 'branch', 'bug_id', 'action', 'namespace', 'sls', - 'monitor'] + "repo", + "branch", + "bug_id", + "action", + "namespace", + "sls", + "monitor", + ] for key in required_keys: if key not in issue_body_json.keys(): self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message="Invalid body, missing required field: {}".format(key), - reason="Invalid" + reason="Invalid", ) return - requester = issue['user']['name'] - namespace = issue_body_json['namespace'].strip() - repo = issue_body_json['repo'].strip() - bug_id = str(issue_body_json['bug_id']).strip() - branch_name = issue_body_json['branch'].strip() - exception = issue_body_json.get('exception', False) + requester = issue["user"]["name"] + namespace = issue_body_json["namespace"].strip() + repo = issue_body_json["repo"].strip() + bug_id = str(issue_body_json["bug_id"]).strip() + branch_name = issue_body_json["branch"].strip() + exception = issue_body_json.get("exception", False) if not re.match(PROJECT_NAME_REGEX, repo): - error = ('The repository name is invalid. It must be at least two ' - 'characters long with only letters, numbers, hyphens, ' - 'underscores, plus signs, and/or periods. Please note that ' - 'the project cannot start with a period or a plus sign.') + error = ( + "The repository name is invalid. It must be at least two " + "characters long with only letters, numbers, hyphens, " + "underscores, plus signs, and/or periods. Please note that " + "the project cannot start with a period or a plus sign." + ) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=error, - reason="Invalid" + reason="Invalid", ) return - if exception is True or namespace in ('modules', 'flatpaks', 'tests', 'container'): - skip_msg = '- Skipping verification of RHBZ' + if exception is True or namespace in ( + "modules", + "flatpaks", + "tests", + "container", + ): + skip_msg = "- Skipping verification of RHBZ" if bug_id: - skip_msg = '{0} #{1}'.format(skip_msg, bug_id) + skip_msg = "{0} #{1}".format(skip_msg, bug_id) _log.info(skip_msg) else: if not bug_id: self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, - message='An invalid Bugzilla bug was provided', - reason="Invalid" + message="An invalid Bugzilla bug was provided", + reason="Invalid", ) return try: - _log.info('- Checking that #{0} is a valid RHBZ.'.format(bug_id)) + _log.info("- Checking that #{0} is a valid RHBZ.".format(bug_id)) self.validate_review_bug( - bug_id, repo, branch_name, - namespace=namespace, pagure_user=requester) + bug_id, + repo, + branch_name, + namespace=namespace, + pagure_user=requester, + ) except ValidationError as error: # pragma: no cover self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=str(error), - reason="Invalid" + reason="Invalid", ) return # This should never trigger because if the user requested an EPEL branch # here, it'd have to be accompanied by a Bugzilla bug for the "Fedora EPEL" # product. So this will only trigger if the reviewer made a mistake. - if re.match(EPEL_REGEX, branch_name) and not self.valid_epel_package(repo, branch_name): + if re.match(EPEL_REGEX, branch_name) and not self.valid_epel_package( + repo, branch_name + ): self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=INVALID_EPEL_ERROR, - reason="Invalid" + reason="Invalid", ) return - issue_id = issue['id'] - _log.info('- Checking if user {0} has an account in dist-git.'.format( - requester)) + issue_id = issue["id"] + _log.info( + "- Checking if user {0} has an account in dist-git.".format(requester) + ) if not self.dist_git.user_exists(requester): - sync_comment = ('@{0} needs to login to {1} to sync accounts ' - 'before we can proceed.'.format(requester, self.dist_git._pagure_url)) + sync_comment = ( + "@{0} needs to login to {1} to sync accounts " + "before we can proceed.".format(requester, self.dist_git._pagure_url) + ) self.pagure_io.add_comment_to_issue( - issue["id"], - namespace=PROJECT_NAMESPACE, - comment=sync_comment + issue["id"], namespace=PROJECT_NAMESPACE, comment=sync_comment ) return - _log.info('- Checking if {0}/{1} already exists in dist-git.'.format( - namespace, repo)) + _log.info( + "- Checking if {0}/{1} already exists in dist-git.".format(namespace, repo) + ) project = self.dist_git.get_project(namespace, repo) if project: self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, - message='The Pagure project already exists', - reason="Invalid" + message="The Pagure project already exists", + reason="Invalid", ) return - description = issue_body_json.get('description', '').strip() - upstreamurl = issue_body_json.get('upstreamurl', '').strip() + description = issue_body_json.get("description", "").strip() + upstreamurl = issue_body_json.get("upstreamurl", "").strip() # Convert a component type to it's singular form - component_type = namespace.strip().rstrip('s') + component_type = namespace.strip().rstrip("s") # Close the ticket if the requested default branch is master - if branch_name == 'master': + if branch_name == "master": self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, - message='Branch `master` cannot be created, please request the right branch.', - reason="Invalid" + message="Branch `master` cannot be created, please request the right branch.", + reason="Invalid", ) return - if namespace in ['rpms', 'container']: - default_branch = 'rawhide' - elif namespace in ['flatpaks']: - default_branch = 'stable' - elif namespace in ['modules']: + if namespace in ["rpms", "container"]: + default_branch = "rawhide" + elif namespace in ["flatpaks"]: + default_branch = "stable" + elif namespace in ["modules"]: default_branch = branch_name - elif namespace in ['tests']: - default_branch = 'main' + elif namespace in ["tests"]: + default_branch = "main" else: - error = ("The requested namespace '{0}' is not recognized. " - "Currently supported namespaces are: " - "rpms, container, flatpaks, modules, tests.".format(namespace)) + error = ( + "The requested namespace '{0}' is not recognized. " + "Currently supported namespaces are: " + "rpms, container, flatpaks, modules, tests.".format(namespace) + ) _log.warning(error) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=error, - reason="Invalid" + reason="Invalid", ) return existing_branch = None if branch_name != default_branch: - _log.info('- Checking if {0} default branch already exists in PDC.'.format(default_branch)) - existing_branch = pdc.get_branch( - repo, default_branch, component_type) + _log.info( + "- Checking if {0} default branch already exists in PDC.".format( + default_branch + ) + ) + existing_branch = pdc.get_branch(repo, default_branch, component_type) - _log.info('- Checking if {0} already exists in PDC.'.format(branch_name)) + _log.info("- Checking if {0} already exists in PDC.".format(branch_name)) branch = pdc.get_branch(repo, branch_name, component_type) if existing_branch or branch: self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, - message='The PDC branch already exists', - reason="Invalid" + message="The PDC branch already exists", + reason="Invalid", ) return _log.info("Ticket passed all validations. Creating repository.") # Create the PDC SLA entry - dist_git_url = '{0}/{1}/{2}'.format( - self.dist_git._pagure_url.rstrip('/'), namespace, repo) + dist_git_url = "{0}/{1}/{2}".format( + self.dist_git._pagure_url.rstrip("/"), namespace, repo + ) # If the global component already exists, this will not create another # Skip for tests namespace - if namespace != 'tests': + if namespace != "tests": _log.debug("Creating repo '{0}' in PDC".format(repo)) pdc.new_global_component(repo, dist_git_url) # If the branch requested isn't default branch, still create a default branch # in PDC anyways. # Skip pdc magic for tests namespace - if namespace != 'tests': + if namespace != "tests": if branch_name != default_branch: _log.debug("Creating branch '{0}' in PDC".format(default_branch)) pdc.new_branch(repo, default_branch, component_type) for sla, eol in self.branch_slas[default_branch].items(): - _log.debug("Adding SLA {0}:{1} to branch '{2}' in PDC".format(sla, eol, default_branch)) + _log.debug( + "Adding SLA {0}:{1} to branch '{2}' in PDC".format( + sla, eol, default_branch + ) + ) pdc.new_sla_to_branch( - sla, eol, repo, default_branch, component_type) + sla, eol, repo, default_branch, component_type + ) _log.debug("Creating branch '{0}' in PDC".format(branch_name)) pdc.new_branch(repo, branch_name, component_type) - for sla, eol in issue_body_json['sls'].items(): - _log.debug("Adding SLA {0}:{1} to branch '{2}' in PDC".format(sla, eol, branch_name)) - pdc.new_sla_to_branch( - sla, eol, repo, branch_name, component_type) + for sla, eol in issue_body_json["sls"].items(): + _log.debug( + "Adding SLA {0}:{1} to branch '{2}' in PDC".format( + sla, eol, branch_name + ) + ) + pdc.new_sla_to_branch(sla, eol, repo, branch_name, component_type) # Create the Pagure repo _log.debug("Creating a repo '{0}' in dist-git".format(repo)) self.dist_git.new_project( - namespace, repo, description, upstreamurl, default_branch, - initial_commit=initial_commit, alias=True) + namespace, + repo, + description, + upstreamurl, + default_branch, + initial_commit=initial_commit, + alias=True, + ) # If the branch requested isn't default branch, create that branch in git. The # default branch is already created at this point. if branch_name != default_branch: - self.dist_git.new_branch(namespace, repo, branch_name, from_branch=default_branch) + self.dist_git.new_branch( + namespace, repo, branch_name, from_branch=default_branch + ) self.dist_git.set_monitoring_status( - namespace, repo, issue_body_json['monitor'].strip()) - self.dist_git.change_project_main_admin( - namespace, repo, requester) + namespace, repo, issue_body_json["monitor"].strip() + ) + self.dist_git.change_project_main_admin(namespace, repo, requester) if branch_name == default_branch: - new_repo_comment = ('The Pagure repository was created at {0}' - .format(dist_git_url)) + new_repo_comment = "The Pagure repository was created at {0}".format( + dist_git_url + ) else: - new_repo_comment = ('The Pagure repository was created at {0}. ' - 'You may commit to the branch "{1}" in about ' - '10 minutes.'.format(dist_git_url, - branch_name)) + new_repo_comment = ( + "The Pagure repository was created at {0}. " + 'You may commit to the branch "{1}" in about ' + "10 minutes.".format(dist_git_url, branch_name) + ) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=new_repo_comment, - reason="Processed" + reason="Processed", ) if bug_id: bugzilla_system.comment_on_bug(bug_id, new_repo_comment) @@ -517,21 +584,21 @@ class SCMRequestProcessor(ToddlerBase): issue_body_json: a partially validated dictionary of the JSON in the issue body """ - required_keys = ['action', 'namespace', 'branch', 'sls', 'repo'] + required_keys = ["action", "namespace", "branch", "sls", "repo"] for key in required_keys: if key not in issue_body_json.keys(): self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message="Invalid body, missing required field: %s" % key, - reason="Invalid" + reason="Invalid", ) return - namespace = issue_body_json['namespace'].strip() - repo = issue_body_json['repo'].strip() - bug_id = str(issue_body_json.get('bug_id', '')).strip() - create_git_branch = issue_body_json.get('create_git_branch', True) + namespace = issue_body_json["namespace"].strip() + repo = issue_body_json["repo"].strip() + bug_id = str(issue_body_json.get("bug_id", "")).strip() + create_git_branch = issue_body_json.get("create_git_branch", True) contributors = self.dist_git.get_project_contributors(namespace, repo) if not contributors: @@ -539,87 +606,106 @@ class SCMRequestProcessor(ToddlerBase): issue["id"], namespace=PROJECT_NAMESPACE, message="The dist git repository doesn't exist", - reason="Invalid" + reason="Invalid", ) return - branch_name = issue_body_json['branch'].strip() - if re.match(EPEL_REGEX, branch_name) and not self.valid_epel_package(repo, branch_name): + branch_name = issue_body_json["branch"].strip() + if re.match(EPEL_REGEX, branch_name) and not self.valid_epel_package( + repo, branch_name + ): self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=INVALID_EPEL_ERROR, - reason="Invalid" + reason="Invalid", ) return # Pagure uses plural names for namespaces, but PDC does not use the # plural version for branch types - branch_type = namespace.strip().rstrip('s') - _log.info('- Checking if {0} already exists in PDC.'.format(branch_name)) + branch_type = namespace.strip().rstrip("s") + _log.info("- Checking if {0} already exists in PDC.".format(branch_name)) pdc_branch = pdc.get_branch(repo, branch_name, branch_type) if pdc_branch: - ticket_text = \ - "The branch in PDC already exists, you can now create it yourself as follows:\n" \ - "Check in the project's settings if you have activated the git hook preventing" \ - "new git branches from being created and if you did, de-activate it.\n" \ - "Then simply run in cloned repository: " \ - "``git checkout -b && git push -u origin ``.\n" \ - "```` is the name of the branch you requested. \n" \ + ticket_text = ( + "The branch in PDC already exists, you can now create it yourself as follows:\n" + "Check in the project's settings if you have activated the git hook preventing" + "new git branches from being created and if you did, de-activate it.\n" + "Then simply run in cloned repository: " + "``git checkout -b && git push -u origin ``.\n" + "```` is the name of the branch you requested. \n" "You only need to do this once and you can then use fedpkg as you normally do." + ) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=ticket_text, - reason="Invalid" + reason="Invalid", ) return - issue_id = issue['id'] - issue_owner = issue['user']['name'] + issue_id = issue["id"] + issue_owner = issue["user"]["name"] # Check if the branch requestor is one of the maintainers or part of the groups - _log.info('- Checking if {0} is one of the maintainers of the package'.format(issue_owner)) + _log.info( + "- Checking if {0} is one of the maintainers of the package".format( + issue_owner + ) + ) # Get the list of maintainers of the package - maintainers = set(contributors['users']['admin']) | \ - set(contributors['users']['commit']) | \ - set(u['user'] - for u in contributors['users']['collaborators'] - if fnmatch.fnmatch(branch_name, u['branches'])) + maintainers = ( + set(contributors["users"]["admin"]) + | set(contributors["users"]["commit"]) + | set( + u["user"] + for u in contributors["users"]["collaborators"] + if fnmatch.fnmatch(branch_name, u["branches"]) + ) + ) # Get the list of FAS groups who can maintain the package - access_groups = set(contributors['groups']['admin']) | \ - set(contributors['groups']['commit']) | \ - set(g['user'] - for g in contributors['groups']['collaborators'] - if fnmatch.fnmatch(branch_name, g['branches'])) + access_groups = ( + set(contributors["groups"]["admin"]) + | set(contributors["groups"]["commit"]) + | set( + g["user"] + for g in contributors["groups"]["collaborators"] + if fnmatch.fnmatch(branch_name, g["branches"]) + ) + ) group_member = False for access_group in access_groups: # Check if the requestor is part of any of the FAS groups who can maintain the package - if fedora_account.user_member_of(fedora_account.get_user_by_username(issue_owner), access_group): + if fedora_account.user_member_of( + fedora_account.get_user_by_username(issue_owner), access_group + ): group_member = True break if issue_owner not in maintainers and not group_member: self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, - message='{0} is not a maintainer of the {1} package'.format(issue_owner, repo), - reason="Invalid" + message="{0} is not a maintainer of the {1} package".format( + issue_owner, repo + ), + reason="Invalid", ) return _log.info("Ticket passed all validations. Creating repository.") # Create the PDC entry - dist_git_url = '{0}/{1}/{2}'.format( - self.dist_git._pagure_url.rstrip('/'), namespace, repo) + dist_git_url = "{0}/{1}/{2}".format( + self.dist_git._pagure_url.rstrip("/"), namespace, repo + ) # If the global component already exists, this will not try to create # it pdc.new_global_component(repo, dist_git_url) pdc.new_branch(repo, branch_name, branch_type) - for sla, eol in issue_body_json['sls'].items(): - pdc.new_sla_to_branch( - sla, eol, repo, branch_name, branch_type) + for sla, eol in issue_body_json["sls"].items(): + pdc.new_sla_to_branch(sla, eol, repo, branch_name, branch_type) if create_git_branch: with TemporaryDirectory(dir=self.temp_dir) as tmp_dir: @@ -629,32 +715,44 @@ class SCMRequestProcessor(ToddlerBase): self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, - message='There is no default branch set for {0}/{1}'.format(namespace, repo), - reason="Invalid" + message="There is no default branch set for {0}/{1}".format( + namespace, repo + ), + reason="Invalid", ) return commit = git_repo.first_commit(default_branch) - self.dist_git.new_branch(namespace, repo, branch_name, from_commit=commit) - new_branch_comment = ('The branch was created in PDC and git. It ' - 'may take up to 10 minutes before you have ' - 'write access on the branch.') + self.dist_git.new_branch( + namespace, repo, branch_name, from_commit=commit + ) + new_branch_comment = ( + "The branch was created in PDC and git. It " + "may take up to 10 minutes before you have " + "write access on the branch." + ) else: new_branch_comment = ( - 'The branch in PDC was created. Pagure is still processing ' - 'the request, but in about 10 minutes, you may create the ' - 'branch in Pagure using git.') + "The branch in PDC was created. Pagure is still processing " + "the request, but in about 10 minutes, you may create the " + "branch in Pagure using git." + ) self.pagure_io.close_issue( issue["id"], namespace=PROJECT_NAMESPACE, message=new_branch_comment, - reason="Processed" + reason="Processed", ) if bug_id: bugzilla_system.comment_on_bug(bug_id, new_branch_comment) - def validate_review_bug(self, bug_id: str, pkg: str, branch: str, - namespace: str = 'rpms', pagure_user: Optional[str] = None - ): + def validate_review_bug( + self, + bug_id: str, + pkg: str, + branch: str, + namespace: str = "rpms", + pagure_user: Optional[str] = None, + ): """ Checks the validity of a Bugzilla bug representing a Fedora package review. This function was inspired by: @@ -672,104 +770,120 @@ class SCMRequestProcessor(ToddlerBase): bug = bugzilla_system.get_bug(bug_id) except Exception as error: raise ValidationError( - 'The Bugzilla bug could not be verified. The following ' - 'error was encountered: {0}'.format(str(error))) + "The Bugzilla bug could not be verified. The following " + "error was encountered: {0}".format(str(error)) + ) if not bug: - raise ValidationError( - 'The Bugzilla bug doesn\'t exist.') + raise ValidationError("The Bugzilla bug doesn't exist.") # Check that the bug is valid bz_proper_component = self.pagure_namespace_to_component.get(namespace) bz_proper_products = self.pagure_namespace_to_product.get(namespace) - if namespace == 'rpms' and (branch != 'rawhide' and branch != 'main'): - if re.match(EPEL_REGEX, branch) and bug.product != 'Fedora EPEL': + if namespace == "rpms" and (branch != "rawhide" and branch != "main"): + if re.match(EPEL_REGEX, branch) and bug.product != "Fedora EPEL": raise ValidationError( 'The Bugzilla bug is for "{0}" but the ' - 'requested branch is an EPEL branch'.format(bug.product)) - elif not re.match(EPEL_REGEX, branch) and bug.product == 'Fedora EPEL': + "requested branch is an EPEL branch".format(bug.product) + ) + elif not re.match(EPEL_REGEX, branch) and bug.product == "Fedora EPEL": raise ValidationError( 'The Bugzilla bug is for "Fedora EPEL" but the ' - 'requested branch is "{0}"'.format(branch)) + 'requested branch is "{0}"'.format(branch) + ) if bz_proper_component is None or bug.component != bz_proper_component: - raise ValidationError( - 'The Bugzilla bug provided is not the proper type') + raise ValidationError("The Bugzilla bug provided is not the proper type") elif bug.product not in bz_proper_products: raise ValidationError( - 'The Bugzilla bug provided is not for "{0}"' - .format('" or "'.join(bz_proper_products))) - elif bug.assigned_to in ['', None, 'nobody@fedoraproject.org']: - raise ValidationError( - 'The Bugzilla bug provided is not assigned to anyone') + 'The Bugzilla bug provided is not for "{0}"'.format( + '" or "'.join(bz_proper_products) + ) + ) + elif bug.assigned_to in ["", None, "nobody@fedoraproject.org"]: + raise ValidationError("The Bugzilla bug provided is not assigned to anyone") fas_submitter = fedora_account.get_user_by_email(bug.creator) if not fas_submitter: raise ValidationError( - 'The Bugzilla review bug creator could not be found in ' - 'FAS. Make sure your FAS email address is the same as in ' - 'Bugzilla.') + "The Bugzilla review bug creator could not be found in " + "FAS. Make sure your FAS email address is the same as in " + "Bugzilla." + ) if pagure_user: - if fas_submitter['username'] != pagure_user: - raise ValidationError('The Bugzilla review bug creator ' - 'didn\'t match the requester in Pagure.') + if fas_submitter["username"] != pagure_user: + raise ValidationError( + "The Bugzilla review bug creator " + "didn't match the requester in Pagure." + ) # Check if the review was approved and by whom flag_set = False for flag in bug.flags: - if flag.get('name') == 'fedora-review': - if flag.get('status') == '+': + if flag.get("name") == "fedora-review": + if flag.get("status") == "+": flag_set = True fas_reviewer = fedora_account.get_user_by_email(bug.assigned_to) if not fas_reviewer: raise ValidationError( 'The email address "{0}" of the Bugzilla reviewer ' - 'is not tied to a user in FAS or FAS check failed. ' - 'Group membership can\'t be validated.'.format(bug.assigned_to)) - if not fedora_account.user_member_of(fas_reviewer, 'packager'): - raise ValidationError('The Bugzilla bug\'s review ' - 'is approved by a user "{0}" that is ' - 'not a packager or FAS check failed'.format( - bug.assigned_to)) - if not fedora_account.user_member_of(fas_submitter, 'packager'): - raise ValidationError('The Bugzilla reporter "{0}"' - 'is not a packager'.format(bug.creator)) + "is not tied to a user in FAS or FAS check failed. " + "Group membership can't be validated.".format(bug.assigned_to) + ) + if not fedora_account.user_member_of(fas_reviewer, "packager"): + raise ValidationError( + "The Bugzilla bug's review " + 'is approved by a user "{0}" that is ' + "not a packager or FAS check failed".format(bug.assigned_to) + ) + if not fedora_account.user_member_of(fas_submitter, "packager"): + raise ValidationError( + 'The Bugzilla reporter "{0}"' + "is not a packager".format(bug.creator) + ) - if flag['setter'] == bug.creator: - error = ('The Bugzilla bug\'s review is approved ' - 'by the person creating the bug. This is ' - 'not allowed.') + if flag["setter"] == bug.creator: + error = ( + "The Bugzilla bug's review is approved " + "by the person creating the bug. This is " + "not allowed." + ) raise ValidationError(error) assigned_to_emails = [bug.assigned_to] if "emails" in fas_reviewer: - assigned_to_emails.append( - fas_reviewer["emails"]) + assigned_to_emails.append(fas_reviewer["emails"]) - if flag['setter'] not in assigned_to_emails: - raise ValidationError('The review is not approved by ' - 'the assignee of the Bugzilla ' - 'bug') + if flag["setter"] not in assigned_to_emails: + raise ValidationError( + "The review is not approved by " + "the assignee of the Bugzilla " + "bug" + ) - update_dt = flag.get('modification_date') + update_dt = flag.get("modification_date") if update_dt: - dt = arrow.get(update_dt, 'YYYY-MM-DDTHH-mm-ssZ') + dt = arrow.get(update_dt, "YYYY-MM-DDTHH-mm-ssZ") delta = arrow.utcnow().date() - dt.date() if delta.days > 60: - raise ValidationError('The Bugzilla bug\'s review ' - 'was approved over 60 days ago') + raise ValidationError( + "The Bugzilla bug's review " "was approved over 60 days ago" + ) break if not flag_set: - raise ValidationError( - 'The Bugzilla bug is not approved yet') + raise ValidationError("The Bugzilla bug is not approved yet") # Check the format of the Bugzilla bug title - tmp_summary = bug.summary.partition(':')[2] + tmp_summary = bug.summary.partition(":")[2] if not tmp_summary: raise ValidationError( - 'Invalid title for this Bugzilla bug (no ":" present)') - if ' - ' not in tmp_summary: + 'Invalid title for this Bugzilla bug (no ":" present)' + ) + if " - " not in tmp_summary: raise ValidationError( - 'Invalid title for this Bugzilla bug (no "-" present)') - pkg_in_bug = tmp_summary.split(' - ', 1)[0].strip() + 'Invalid title for this Bugzilla bug (no "-" present)' + ) + pkg_in_bug = tmp_summary.split(" - ", 1)[0].strip() if pkg != pkg_in_bug: - error = ('The package in the Bugzilla bug "{0}" doesn\'t match ' - 'the one provided "{1}"'.format(pkg_in_bug, pkg)) + error = ( + 'The package in the Bugzilla bug "{0}" doesn\'t match ' + 'the one provided "{1}"'.format(pkg_in_bug, pkg) + ) raise ValidationError(error) def valid_epel_package(self, name: str, branch: str) -> bool: @@ -787,8 +901,8 @@ class SCMRequestProcessor(ToddlerBase): `ValidationError`: When we can't retrieve list of official EL packages. """ # Extract any digits in the branch name to determine the EL version - version = ''.join([i for i in branch if re.match(r'\d', i)]) - url = f'https://infrastructure.fedoraproject.org/repo/json/pkg_el{version}.json' + version = "".join([i for i in branch if re.match(r"\d", i)]) + url = f"https://infrastructure.fedoraproject.org/repo/json/pkg_el{version}.json" response = self.requests_session.get(url) if response.status_code != 200: @@ -796,20 +910,20 @@ class SCMRequestProcessor(ToddlerBase): rv_json = response.json() # Remove noarch from this because noarch is treated specially - all_arches = set(rv_json['arches']) - set(['noarch']) + all_arches = set(rv_json["arches"]) - set(["noarch"]) # On EL6, also remove ppc and i386 as many packages will # have these arches missing and cause false positives if int(version) == 6: - all_arches = all_arches - set(['ppc', 'i386']) + all_arches = all_arches - set(["ppc", "i386"]) # On EL7 and later, also remove ppc and i686 as many packages will # have these arches missing and cause false positives elif int(version) >= 7: - all_arches = all_arches - set(['ppc', 'i686']) - for pkg_name, pkg_info in rv_json['packages'].items(): + all_arches = all_arches - set(["ppc", "i686"]) + for pkg_name, pkg_info in rv_json["packages"].items(): # If the EL package is noarch only or is available on all supported # arches, then don't allow an EPEL branch if pkg_name == name: - pkg_arches = set(pkg_info['arch']) - if pkg_arches == set(['noarch']) or not (all_arches - pkg_arches): + pkg_arches = set(pkg_info["arch"]) + if pkg_arches == set(["noarch"]) or not (all_arches - pkg_arches): return False return True diff --git a/toddlers/utils/bugzilla_system.py b/toddlers/utils/bugzilla_system.py index 8526ab4..45c5135 100644 --- a/toddlers/utils/bugzilla_system.py +++ b/toddlers/utils/bugzilla_system.py @@ -576,7 +576,7 @@ def get_bug(bug_id: str) -> Optional[Bug]: bz = get_bz() try: - bug = execute_bugzilla_call(bz.getbug, {"id": bug_id}) + bug = execute_bugzilla_call(bz.getbug, {"id": bug_id}) except xmlrpc.client.Fault as e: # Output something useful in args e.args = (bug_id, e.faultCode, e.faultString) @@ -603,10 +603,7 @@ def comment_on_bug(bug_id: str, comment: str) -> None: bz = get_bz() _log.info("Adding comment `%s` to `%s`", comment, bug_id) - data = { - "id": bug_id, - "comment": comment - } + data = {"id": bug_id, "comment": comment} try: execute_bugzilla_call(bz.comment, data) diff --git a/toddlers/utils/fedora_account.py b/toddlers/utils/fedora_account.py index 9892247..10882a1 100644 --- a/toddlers/utils/fedora_account.py +++ b/toddlers/utils/fedora_account.py @@ -122,8 +122,7 @@ def user_member_of(user: dict, group: str) -> bool: is_member = False try: is_member = fasjson.check_membership( - groupname=group, - username=user["username"] + groupname=group, username=user["username"] ).result except ClientError: pass diff --git a/toddlers/utils/git.py b/toddlers/utils/git.py index d47f269..ba31e68 100644 --- a/toddlers/utils/git.py +++ b/toddlers/utils/git.py @@ -6,7 +6,7 @@ Author: mkonecny@redhat.com import git -def clone_repo(remote: str, destination: str) -> 'GitRepo': +def clone_repo(remote: str, destination: str) -> "GitRepo": """ Clone the remote repository. @@ -58,4 +58,3 @@ class GitRepo: return commits[-1] else: return None - diff --git a/toddlers/utils/pagure.py b/toddlers/utils/pagure.py index 15e45ec..0f25b91 100644 --- a/toddlers/utils/pagure.py +++ b/toddlers/utils/pagure.py @@ -38,6 +38,7 @@ class Pagure: """ Object that is a wrapper above pagure API. """ + # URL to pagure _pagure_url: str = None # API key for pagure instance @@ -73,12 +74,14 @@ class Pagure: A dictionary of the HTTP header """ return { - 'Authorization': 'token {0}'.format(self._pagure_api_key), - 'Accept': 'application/json', - 'Content-Type': 'application/json' + "Authorization": "token {0}".format(self._pagure_api_key), + "Accept": "application/json", + "Content-Type": "application/json", } - def close_issue(self, issue_id: int, namespace: str, message: str, reason: str = 'Closed'): + def close_issue( + self, issue_id: int, namespace: str, message: str, reason: str = "Closed" + ): """ Close the issue defined by the id with provided message and reason. @@ -93,22 +96,21 @@ class Pagure: toddlers.utils.exceptions.PagureError when the issue couldn't be closed. """ issue_url = "{0}/{1}/issue/{2}".format(self._pagure_url, namespace, issue_id) - api_url = '{0}/status'.format(issue_url) - status_payload = {'status': reason} + api_url = "{0}/status".format(issue_url) + status_payload = {"status": reason} headers = self.get_auth_header() if message: - self.add_comment_to_issue( - issue_id, - namespace=namespace, - comment=message - ) + self.add_comment_to_issue(issue_id, namespace=namespace, comment=message) log.debug( "Closing issue '{0}' with reason '{1}' adding message '{2}'".format( - issue_url, reason, message) + issue_url, reason, message + ) + ) + response = self._requests_session.post( + api_url, data=status_payload, headers=headers ) - response = self._requests_session.post(api_url, data=status_payload, headers=headers) if response.status_code == 200: return @@ -121,7 +123,6 @@ class Pagure: raise PagureError("Couldn't close issue '{0}'".format(issue_url)) - def add_comment_to_issue(self, issue_id: str, namespace: str, comment: str) -> bool: """ Comment on issue defined by the id. @@ -135,15 +136,16 @@ class Pagure: toddlers.utils.exceptions.PagureError: When the issue couldn't be commented on. """ issue_url = "{0}/{1}/issue/{2}".format(self._pagure_url, namespace, issue_id) - api_url = '{0}/comment'.format(issue_url) - comment_payload = {'comment': comment} + api_url = "{0}/comment".format(issue_url) + comment_payload = {"comment": comment} headers = self.get_auth_header() log.debug( - "Commenting on issue '{0}' with message '{1}'".format( - issue_url, comment) + "Commenting on issue '{0}' with message '{1}'".format(issue_url, comment) + ) + response = self._requests_session.post( + api_url, data=comment_payload, headers=headers ) - response = self._requests_session.post(api_url, data=comment_payload, headers=headers) if response.status_code == 200: return @@ -156,7 +158,6 @@ class Pagure: raise PagureError("Couldn't comment on issue '{0}'".format(issue_url)) - def user_exists(self, username: str) -> bool: """ Check if the user exists in Pagure. @@ -173,9 +174,9 @@ class Pagure: if response.status_code == 200: data = response.json() - if not data['users']: + if not data["users"]: return False - return username in data['users'] + return username in data["users"] log.error( "Error when checking for user '{0}'. Got status_code '{1}'.".format( @@ -186,14 +187,14 @@ class Pagure: raise PagureError("Couldn't get user '{0}'".format(username)) def new_project( - self, - namespace: str, - repo: str, - description: str, - upstream_url: str, - default_branch: str, - initial_commit: bool = False, - alias: bool = False + self, + namespace: str, + repo: str, + description: str, + upstream_url: str, + default_branch: str, + initial_commit: bool = False, + alias: bool = False, ) -> None: """ Create mew project in Pagure. @@ -214,16 +215,16 @@ class Pagure: pagure_new_project_url = "{0}/api/0/new".format(self._pagure_url) headers = self.get_auth_header() payload = { - 'namespace': namespace, - 'name': repo, - 'default_branch': default_branch, - 'description': description or 'The {0} package\n'.format(repo), - 'url': upstream_url or '', - 'wait': True + "namespace": namespace, + "name": repo, + "default_branch": default_branch, + "description": description or "The {0} package\n".format(repo), + "url": upstream_url or "", + "wait": True, } if initial_commit: - payload['create_readme'] = True + payload["create_readme"] = True log.debug("Creating project '{0}/{1}'".format(namespace, repo)) response = self._requests_session.post( @@ -236,18 +237,23 @@ class Pagure: namespace, repo, response.status_code ) ) - raise PagureError("Couldn't create project '{0}/{1}'".format(namespace, repo)) + raise PagureError( + "Couldn't create project '{0}/{1}'".format(namespace, repo) + ) if alias: # Only create alias for rpms and container namespace - if namespace in ['rpms', 'container']: - pagure_new_git_alias_url = \ - '{0}/api/0/{1}/{2}/git/alias/new'.format(self._pagure_url, namespace, repo) + if namespace in ["rpms", "container"]: + pagure_new_git_alias_url = "{0}/api/0/{1}/{2}/git/alias/new".format( + self._pagure_url, namespace, repo + ) payload = { - 'alias_from': 'main', - 'alias_to': 'rawhide', + "alias_from": "main", + "alias_to": "rawhide", } - log.debug("Creating alias for project '{0}/{1}'".format(namespace, repo)) + log.debug( + "Creating alias for project '{0}/{1}'".format(namespace, repo) + ) response = self._requests_session.post( pagure_new_git_alias_url, data=payload, headers=headers ) @@ -258,15 +264,19 @@ class Pagure: namespace, repo, response.status_code ) ) - raise PagureError("Couldn't create alias for project '{0}/{1}'".format(namespace, repo)) + raise PagureError( + "Couldn't create alias for project '{0}/{1}'".format( + namespace, repo + ) + ) def new_branch( - self, - namespace: str, - repo: str, - branch: str, - from_commit: str = "", - from_branch: str = "" + self, + namespace: str, + repo: str, + branch: str, + from_commit: str = "", + from_branch: str = "", ) -> None: """ Create a new branch in pagure repository. @@ -284,20 +294,23 @@ class Pagure: `toddlers.utils.exceptions.PagureError``: When the branch creation fails. """ if from_commit and from_branch: - raise RuntimeError('`from_commit` and `from_branch` were both ' - 'specified. Only use one.') + raise RuntimeError( + "`from_commit` and `from_branch` were both " "specified. Only use one." + ) elif not from_commit and not from_branch: - raise RuntimeError('You must specify either `from_commit` or ' - '`from_branch`') + raise RuntimeError( + "You must specify either `from_commit` or " "`from_branch`" + ) - branch_api_url = '{0}/api/0/{1}/{2}/git/branch'.format( - self._pagure_url, namespace, repo) + branch_api_url = "{0}/api/0/{1}/{2}/git/branch".format( + self._pagure_url, namespace, repo + ) headers = self.get_auth_header() - payload = {'branch': branch} + payload = {"branch": branch} if from_commit: - payload['from_commit'] = from_commit + payload["from_commit"] = from_commit else: - payload['from_branch'] = from_branch + payload["from_branch"] = from_branch log.debug("Creating branch for project '{0}/{1}'".format(namespace, repo)) response = self._requests_session.post( @@ -310,13 +323,15 @@ class Pagure: namespace, repo, response.status_code ) ) - raise PagureError("Couldn't create branch in project '{0}/{1}'".format(namespace, repo)) + raise PagureError( + "Couldn't create branch in project '{0}/{1}'".format(namespace, repo) + ) def set_monitoring_status( - self, - namespace: str, - repo: str, - monitoring_level: str, + self, + namespace: str, + repo: str, + monitoring_level: str, ) -> None: """ Set a monitoring status for pagure repository. This will work only on dist git. @@ -329,12 +344,17 @@ class Pagure: Raises: `toddlers.utils.exceptions.PagureError``: When setting the monitoring level fails. """ - monitoring_api_url = '{0}/_dg/anitya/{1}/{2}'.format(self._pagure_url, namespace, repo) + monitoring_api_url = "{0}/_dg/anitya/{1}/{2}".format( + self._pagure_url, namespace, repo + ) headers = self.get_auth_header() - payload = {'anitya_status': monitoring_level} + payload = {"anitya_status": monitoring_level} - log.debug("Setting monitoring to '{0}' for project '{1}/{2}'".format( - monitoring_level, namespace, repo)) + log.debug( + "Setting monitoring to '{0}' for project '{1}/{2}'".format( + monitoring_level, namespace, repo + ) + ) response = self._requests_session.post( monitoring_api_url, data=payload, headers=headers ) @@ -345,9 +365,13 @@ class Pagure: namespace, repo, response.status_code ) ) - raise PagureError("Couldn't set monitoring on project '{0}/{1}'".format(namespace, repo)) + raise PagureError( + "Couldn't set monitoring on project '{0}/{1}'".format(namespace, repo) + ) - def change_project_main_admin(self, namespace: str, repo: str, new_main_admin: str) -> None: + def change_project_main_admin( + self, namespace: str, repo: str, new_main_admin: str + ) -> None: """ Change the main admin of a project in pagure. @@ -359,12 +383,15 @@ class Pagure: Raises: `toddlers.utils.exceptions.PagureError``: When setting new admin fails. """ - admin_api_url = '{0}/api/0/{1}/{2}'.format(self._pagure_url, namespace, repo) + admin_api_url = "{0}/api/0/{1}/{2}".format(self._pagure_url, namespace, repo) headers = self.get_auth_header() - payload = {'main_admin': new_main_admin} + payload = {"main_admin": new_main_admin} - log.debug("Setting new admin to '{0}' for project '{1}/{2}'".format( - new_main_admin, namespace, repo)) + log.debug( + "Setting new admin to '{0}' for project '{1}/{2}'".format( + new_main_admin, namespace, repo + ) + ) response = self._requests_session.post( admin_api_url, data=payload, headers=headers ) @@ -375,7 +402,9 @@ class Pagure: namespace, repo, response.status_code ) ) - raise PagureError("Couldn't set new admin on project '{0}/{1}'".format(namespace, repo)) + raise PagureError( + "Couldn't set new admin on project '{0}/{1}'".format(namespace, repo) + ) def get_project_contributors(self, namespace: str, repo: str) -> dict: """ @@ -391,14 +420,13 @@ class Pagure: Raises: `toddlers.utils.exceptions.PagureError``: When getting contributors fails. """ - contributors_api_url = '{0}/api/0/{1}/{2}/contributors'.format(self._pagure_url, namespace, repo) + contributors_api_url = "{0}/api/0/{1}/{2}/contributors".format( + self._pagure_url, namespace, repo + ) headers = self.get_auth_header() - log.debug("Getting contributors for project '{0}/{1}'".format( - namespace, repo)) - response = self._requests_session.get( - contributors_api_url, headers=headers - ) + log.debug("Getting contributors for project '{0}/{1}'".format(namespace, repo)) + response = self._requests_session.get(contributors_api_url, headers=headers) if response.status_code != 200: log.error( @@ -406,7 +434,11 @@ class Pagure: namespace, repo, response.status_code ) ) - raise PagureError("Couldn't get contributors for project '{0}/{1}'".format(namespace, repo)) + raise PagureError( + "Couldn't get contributors for project '{0}/{1}'".format( + namespace, repo + ) + ) return response.json() @@ -424,14 +456,15 @@ class Pagure: Raises: `toddlers.utils.exceptions.PagureError``: When getting default branch fails. """ - branches_api_url = '{0}/api/0/{1}/{2}/git/branches'.format(self._pagure_url, namespace, repo) + branches_api_url = "{0}/api/0/{1}/{2}/git/branches".format( + self._pagure_url, namespace, repo + ) headers = self.get_auth_header() - log.debug("Getting default branch for project '{0}/{1}'".format( - namespace, repo)) - response = self._requests_session.get( - branches_api_url, headers=headers + log.debug( + "Getting default branch for project '{0}/{1}'".format(namespace, repo) ) + response = self._requests_session.get(branches_api_url, headers=headers) if response.status_code != 200: log.error( @@ -439,6 +472,10 @@ class Pagure: namespace, repo, response.status_code ) ) - raise PagureError("Couldn't get default branch for project '{0}/{1}'".format(namespace, repo)) + raise PagureError( + "Couldn't get default branch for project '{0}/{1}'".format( + namespace, repo + ) + ) return response.json().get("default", None) diff --git a/toddlers/utils/pdc.py b/toddlers/utils/pdc.py index 9f02adc..ea6961f 100644 --- a/toddlers/utils/pdc.py +++ b/toddlers/utils/pdc.py @@ -43,11 +43,7 @@ def get_sla(sla_name: str) -> Optional[dict]: def new_sla_to_branch( - sla_name: str, - eol: str, - global_component: str, - branch: str, - branch_type: str + sla_name: str, eol: str, global_component: str, branch: str, branch_type: str ) -> None: """ Create a new SLA to branch mapping in PDC. @@ -60,13 +56,13 @@ def new_sla_to_branch( branch_type: Type of the branch (e.g. rpm, module, etc.) """ payload = { - 'sla': sla_name, - 'eol': eol, - 'branch': { - 'global_component': global_component, - 'name': branch, - 'type': branch_type - } + "sla": sla_name, + "eol": eol, + "branch": { + "global_component": global_component, + "name": branch, + "type": branch_type, + }, } _PDC["component-branch-slas"]._(payload) @@ -86,16 +82,16 @@ def get_branch(global_component: str, branch: str, branch_type: str) -> Optional A dictionary of the branch in PDC """ query_args = { - 'global_component': global_component, - 'name': branch, - 'type': branch_type + "global_component": global_component, + "name": branch, + "type": branch_type, } branch_query = _PDC["component-branches"]._(**query_args) - if branch_query['count'] == 0: + if branch_query["count"] == 0: return None else: - return branch_query['results'][0] + return branch_query["results"][0] def new_branch(global_component: str, branch: str, branch_type: str) -> None: @@ -115,9 +111,9 @@ def new_branch(global_component: str, branch: str, branch_type: str) -> None: return payload = { - 'global_component': global_component, - 'name': branch, - 'type': branch_type + "global_component": global_component, + "name": branch, + "type": branch_type, } _PDC["component-branches"]._(payload) @@ -154,10 +150,7 @@ def new_global_component(global_component: str, dist_git_url: str) -> None: if existing_global_component: return - payload = { - "name": global_component, - "dist_git_web_url": dist_git_url - } + payload = {"name": global_component, "dist_git_web_url": dist_git_url} # If it doesn't exist create one _PDC["global-components"]._(payload)