Repository: packit/packit-service
Issue: Bug: test jobs are not filtered by trigger/branch

# Why is this a bug?

Lets consider the following configuration:
```yaml
jobs:
  - job: tests
    trigger: pull_request
  - job: copr_build
    trigger: pull_request
    project: CI
  - job: tests
    trigger: commit
    branch: main
  - job: copr_build
    trigger: commit
    branch: main
    project: nightly
  - job: copr_build
    trigger: release
    project: releases
```

Here `copr_build.commit` is only triggered on branch `main` which is only intended for actual nightly releases. There you also want to check if the nightly release is functional, e.g. after a PR is merged. So far so good. Then you also have a PR workflow that pushes to a separate project so that it doesn't interfere with the nightly builds, so you also include a test job for PR, and that works all fine.

The issue appears when you combine them and you are working on the same repository and not a fork. Because `tests.commit` is not filtered by branch (or trigger apparently), it always requests a test job on pushes to e.g. `fix/issue23` (and waits indefinitely). It pollutes the commit status, but that is not the main issue. The issue is when you then do a PR. Because the `test.commit` jobs are waiting for a `copr_build.commit` which is never executed, the CI checks never finish, and if the branch is protected, you cannot merge without force.

Changed files:
tests/integration/test_handler.py, packit_service/worker/handlers/koji.py, packit_service/worker/checker/testing_farm.py, tests/integration/test_pr_comment.py, tests/unit/test_checkers.py, tests/unit/test_build_helper.py, packit_service/worker/handlers/testing_farm.py, tests/integration/test_check_rerun.py, packit_service/worker/handlers/copr.py, packit_service/worker/checker/koji.py, tests/integration/test_listen_to_fedmsg.py, packit_service/worker/checker/copr.py, packit_service/worker/helpers/build/build_helper.py

diff --git a/packit_service/worker/checker/copr.py b/packit_service/worker/checker/copr.py
index ae7777a5..aa4960ef 100644
--- a/packit_service/worker/checker/copr.py
+++ b/packit_service/worker/checker/copr.py
@@ -2,29 +2,33 @@
 # SPDX-License-Identifier: MIT
 
 import logging
-import re
 
-from packit_service.worker.checker.abstract import ActorChecker, Checker
-from packit_service.worker.events.enums import GitlabEventAction
+from packit_service.constants import (
+    INTERNAL_TF_BUILDS_AND_TESTS_NOT_ALLOWED,
+)
+from packit_service.worker.checker.abstract import (
+    ActorChecker,
+    Checker,
+)
 from packit_service.worker.events import (
     MergeRequestGitlabEvent,
-    PushGitHubEvent,
-    PushGitlabEvent,
-    PushPagureEvent,
 )
+from packit_service.worker.events.enums import GitlabEventAction
 from packit_service.worker.handlers.mixin import (
     GetCoprBuildJobHelperForIdMixin,
     GetCoprBuildJobHelperMixin,
     GetCoprSRPMBuildMixin,
 )
-from packit_service.constants import (
-    INTERNAL_TF_BUILDS_AND_TESTS_NOT_ALLOWED,
-)
 from packit_service.worker.reporting import BaseCommitStatus
 
 logger = logging.getLogger(__name__)
 
 
+class IsJobConfigTriggerMatching(Checker, GetCoprBuildJobHelperMixin):
+    def pre_check(self) -> bool:
+        return self.copr_build_helper.is_job_config_trigger_matching(self.job_config)
+
+
 class IsGitForgeProjectAndEventOk(Checker, GetCoprBuildJobHelperMixin):
     def pre_check(
         self,
@@ -36,19 +40,6 @@ class IsGitForgeProjectAndEventOk(Checker, GetCoprBuildJobHelperMixin):
             # Not interested in closed merge requests
             return False
 
-        if self.data.event_type in (
-            PushGitHubEvent.__name__,
-            PushGitlabEvent.__name__,
-            PushPagureEvent.__name__,
-        ):
-            configured_branch = self.copr_build_helper.job_build_branch
-            if not re.match(configured_branch, self.data.git_ref):
-                logger.info(
-                    f"Skipping build on '{self.data.git_ref}'. "
-                    f"Push configured only for '{configured_branch}'."
-                )
-                return False
-
         if not (
             self.copr_build_helper.job_build or self.copr_build_helper.job_tests_all
         ):
diff --git a/packit_service/worker/checker/koji.py b/packit_service/worker/checker/koji.py
index df295234..89c959a5 100644
--- a/packit_service/worker/checker/koji.py
+++ b/packit_service/worker/checker/koji.py
@@ -2,27 +2,28 @@
 # SPDX-License-Identifier: MIT
 
 import logging
-import re
 
+from packit_service.constants import (
+    KOJI_PRODUCTION_BUILDS_ISSUE,
+    PERMISSIONS_ERROR_WRITE_OR_ADMIN,
+)
 from packit_service.worker.checker.abstract import Checker
-from packit_service.worker.events.enums import GitlabEventAction
 from packit_service.worker.events import (
     MergeRequestGitlabEvent,
     PullRequestGithubEvent,
-    PushGitHubEvent,
-    PushGitlabEvent,
-    PushPagureEvent,
 )
-from packit_service.constants import (
-    KOJI_PRODUCTION_BUILDS_ISSUE,
-    PERMISSIONS_ERROR_WRITE_OR_ADMIN,
-)
-from packit_service.worker.reporting import BaseCommitStatus
+from packit_service.worker.events.enums import GitlabEventAction
 from packit_service.worker.handlers.mixin import GetKojiBuildJobHelperMixin
+from packit_service.worker.reporting import BaseCommitStatus
 
 logger = logging.getLogger(__name__)
 
 
+class IsJobConfigTriggerMatching(Checker, GetKojiBuildJobHelperMixin):
+    def pre_check(self) -> bool:
+        return self.koji_build_helper.is_job_config_trigger_matching(self.job_config)
+
+
 class PermissionOnKoji(Checker, GetKojiBuildJobHelperMixin):
     def pre_check(self) -> bool:
         if (
@@ -32,19 +33,6 @@ class PermissionOnKoji(Checker, GetKojiBuildJobHelperMixin):
             # Not interested in closed merge requests
             return False
 
-        if self.data.event_type in (
-            PushGitHubEvent.__name__,
-            PushGitlabEvent.__name__,
-            PushPagureEvent.__name__,
-        ):
-            configured_branch = self.koji_build_helper.job_build_branch
-            if not re.match(configured_branch, self.data.git_ref):
-                logger.info(
-                    f"Skipping build on '{self.data.git_ref}'. "
-                    f"Push configured only for '{configured_branch}'."
-                )
-                return False
-
         if self.data.event_type in (
             PullRequestGithubEvent.__name__,
             MergeRequestGitlabEvent.__name__,
diff --git a/packit_service/worker/checker/testing_farm.py b/packit_service/worker/checker/testing_farm.py
index d2c7a71d..41f5caef 100644
--- a/packit_service/worker/checker/testing_farm.py
+++ b/packit_service/worker/checker/testing_farm.py
@@ -2,14 +2,17 @@
 # SPDX-License-Identifier: MIT
 
 import logging
+
 from packit_service.constants import (
     INTERNAL_TF_BUILDS_AND_TESTS_NOT_ALLOWED,
     INTERNAL_TF_TESTS_NOT_ALLOWED,
 )
-
-from packit_service.worker.checker.abstract import ActorChecker, Checker
-from packit_service.worker.events.gitlab import MergeRequestGitlabEvent
+from packit_service.worker.checker.abstract import (
+    ActorChecker,
+    Checker,
+)
 from packit_service.worker.events.enums import GitlabEventAction
+from packit_service.worker.events.gitlab import MergeRequestGitlabEvent
 from packit_service.worker.handlers.mixin import (
     GetTestingFarmJobHelperMixin,
     GetCoprBuildMixin,
@@ -20,6 +23,13 @@ from packit_service.worker.reporting import BaseCommitStatus
 logger = logging.getLogger(__name__)
 
 
+class IsJobConfigTriggerMatching(Checker, GetTestingFarmJobHelperMixin):
+    def pre_check(self) -> bool:
+        return self.testing_farm_job_helper.is_job_config_trigger_matching(
+            self.job_config
+        )
+
+
 class IsEventOk(
     Checker, GetTestingFarmJobHelperMixin, GetCoprBuildMixin, GetGithubCommentEventMixin
 ):
diff --git a/packit_service/worker/handlers/copr.py b/packit_service/worker/handlers/copr.py
index e2b45720..043f7f64 100644
--- a/packit_service/worker/handlers/copr.py
+++ b/packit_service/worker/handlers/copr.py
@@ -6,9 +6,9 @@ from datetime import datetime, timezone
 from typing import Tuple, Type, Optional
 
 from celery import signature, Task
+
 from ogr.services.github import GithubProject
 from ogr.services.gitlab import GitlabProject
-
 from packit.config import (
     JobConfig,
     JobType,
@@ -35,6 +35,7 @@ from packit_service.worker.checker.copr import (
     AreOwnerAndProjectMatchingJob,
     IsGitForgeProjectAndEventOk,
     BuildNotAlreadyStarted,
+    IsJobConfigTriggerMatching,
 )
 from packit_service.worker.events import (
     CoprBuildEndEvent,
@@ -59,12 +60,12 @@ from packit_service.worker.handlers.abstract import (
     run_for_check_rerun,
     RetriableJobHandler,
 )
-from packit_service.worker.mixin import PackitAPIWithDownstreamMixin
 from packit_service.worker.handlers.mixin import (
     GetCoprBuildEventMixin,
     GetCoprBuildJobHelperForIdMixin,
     GetCoprBuildJobHelperMixin,
 )
+from packit_service.worker.mixin import PackitAPIWithDownstreamMixin
 from packit_service.worker.reporting import BaseCommitStatus, DuplicateCheckMode
 from packit_service.worker.result import TaskResults
 
@@ -109,7 +110,11 @@ class CoprBuildHandler(
 
     @staticmethod
     def get_checkers() -> Tuple[Type[Checker], ...]:
-        return IsGitForgeProjectAndEventOk, CanActorRunTestsJob
+        return (
+            IsJobConfigTriggerMatching,
+            IsGitForgeProjectAndEventOk,
+            CanActorRunTestsJob,
+        )
 
     def run(self) -> TaskResults:
         return self.copr_build_helper.run_copr_build_from_source_script()
diff --git a/packit_service/worker/handlers/koji.py b/packit_service/worker/handlers/koji.py
index 2f9ea722..7e2f7669 100644
--- a/packit_service/worker/handlers/koji.py
+++ b/packit_service/worker/handlers/koji.py
@@ -19,13 +19,15 @@ from packit_service.constants import (
     KojiBuildState,
 )
 from packit_service.constants import KojiTaskState
-from packit_service.worker.mixin import ConfigFromEventMixin
 from packit_service.models import AbstractTriggerDbType, KojiBuildTargetModel
 from packit_service.service.urls import (
     get_koji_build_info_url,
 )
 from packit_service.worker.checker.abstract import Checker
-from packit_service.worker.helpers.build.koji_build import KojiBuildJobHelper
+from packit_service.worker.checker.koji import (
+    PermissionOnKoji,
+    IsJobConfigTriggerMatching,
+)
 from packit_service.worker.events import (
     CheckRerunCommitEvent,
     CheckRerunPullRequestEvent,
@@ -47,11 +49,12 @@ from packit_service.worker.handlers.abstract import (
     run_for_check_rerun,
     run_for_comment,
 )
+from packit_service.worker.handlers.mixin import GetKojiBuildJobHelperMixin
+from packit_service.worker.helpers.build.koji_build import KojiBuildJobHelper
+from packit_service.worker.mixin import ConfigFromEventMixin
+from packit_service.worker.mixin import PackitAPIWithDownstreamMixin
 from packit_service.worker.reporting import BaseCommitStatus
 from packit_service.worker.result import TaskResults
-from packit_service.worker.checker.koji import PermissionOnKoji
-from packit_service.worker.mixin import PackitAPIWithDownstreamMixin
-from packit_service.worker.handlers.mixin import GetKojiBuildJobHelperMixin
 
 logger = logging.getLogger(__name__)
 
@@ -94,7 +97,10 @@ class KojiBuildHandler(
 
     @staticmethod
     def get_checkers() -> Tuple[Type[Checker], ...]:
-        return (PermissionOnKoji,)
+        return (
+            IsJobConfigTriggerMatching,
+            PermissionOnKoji,
+        )
 
     def run(self) -> TaskResults:
         return self.koji_build_helper.run_koji_build()
diff --git a/packit_service/worker/handlers/testing_farm.py b/packit_service/worker/handlers/testing_farm.py
index bed6e251..e347eb8d 100644
--- a/packit_service/worker/handlers/testing_farm.py
+++ b/packit_service/worker/handlers/testing_farm.py
@@ -32,6 +32,7 @@ from packit_service.worker.checker.testing_farm import (
     CanActorRunJob,
     IsEventForJob,
     IsEventOk,
+    IsJobConfigTriggerMatching,
 )
 from packit_service.worker.events import (
     TestingFarmResultsEvent,
@@ -116,6 +117,7 @@ class TestingFarmHandler(
     @staticmethod
     def get_checkers() -> Tuple[Type[Checker], ...]:
         return (
+            IsJobConfigTriggerMatching,
             IsEventOk,
             CanActorRunJob,
         )
diff --git a/packit_service/worker/helpers/build/build_helper.py b/packit_service/worker/helpers/build/build_helper.py
index fe2b6630..c344ea9a 100644
--- a/packit_service/worker/helpers/build/build_helper.py
+++ b/packit_service/worker/helpers/build/build_helper.py
@@ -2,6 +2,7 @@
 # SPDX-License-Identifier: MIT
 import datetime
 import logging
+import re
 from io import StringIO
 from pathlib import Path
 from typing import List, Optional, Set, Tuple, Dict, Callable
@@ -101,11 +102,26 @@ class BaseBuildJobHelper(BaseJobHelper):
 
         return targets or {DEFAULT_VERSION}
 
-    def is_job_config_trigger_matching(self, job_config: JobConfig):
-        return (
-            self.db_trigger
-            and self.db_trigger.job_config_trigger_type == job_config.trigger
+    def is_job_config_trigger_matching(self, job_config: JobConfig) -> bool:
+        """
+        Check whether the job config matches the DB trigger type.
+        In case the job config trigger is commit, also check that the branch
+        matches.
+        """
+        if (
+            not self.db_trigger
+            or self.db_trigger.job_config_trigger_type != job_config.trigger
+        ):
+            return False
+
+        if job_config.trigger != JobConfigTriggerType.commit:
+            return True
+
+        configured_branch = job_config.branch or self.project.default_branch
+        logger.info(
+            f"Configured branch: {configured_branch}, branch from trigger: {self.db_trigger.name}"
         )
+        return bool(re.match(configured_branch, self.db_trigger.name))
 
     @property
     def job_build(self) -> Optional[JobConfig]:
@@ -128,16 +144,6 @@ class BaseBuildJobHelper(BaseJobHelper):
     def job_build_or_job_config(self):
         return self.job_build or self.job_config
 
-    @property
-    def job_build_branch(self) -> Optional[str]:
-        """
-        Branch used for the build job or project's default branch.
-        """
-        if self.job_build and self.job_build.branch:
-            return self.job_build.branch
-
-        return self.project.default_branch
-
     @property
     def job_tests_all(self) -> List[JobConfig]:
         """
diff --git a/tests/integration/test_check_rerun.py b/tests/integration/test_check_rerun.py
index 65eba402..58b4594d 100644
--- a/tests/integration/test_check_rerun.py
+++ b/tests/integration/test_check_rerun.py
@@ -170,7 +170,11 @@ def mock_push_functionality(request):
         namespace="packit",
         repo_name="hello-world",
         project_url="https://github.com/packit/hello-world",
-    ).and_return(flexmock(id=12, job_config_trigger_type=JobConfigTriggerType.commit))
+    ).and_return(
+        flexmock(
+            id=12, job_config_trigger_type=JobConfigTriggerType.commit, name="main"
+        )
+    )
     flexmock(JobTriggerModel).should_receive("get_or_create").and_return(
         flexmock(id=123456)
     )
@@ -428,6 +432,7 @@ def test_check_rerun_pr_koji_build_handler_old_job_name(
                 {
                     "trigger": "commit",
                     "job": "tests",
+                    "branch": "main",
                     "targets": [
                         "fedora-all",
                     ],
@@ -501,7 +506,9 @@ def test_check_rerun_push_testing_farm_handler(
                 {
                     "trigger": "commit",
                     "job": "upstream_koji_build",
-                    "metadata": {"targets": "fedora-all", "scratch": "true"},
+                    "targets": "fedora-all",
+                    "scratch": "true",
+                    "branch": "main",
                 }
             ]
         ]
diff --git a/tests/integration/test_handler.py b/tests/integration/test_handler.py
index 372f4744..d3251f17 100644
--- a/tests/integration/test_handler.py
+++ b/tests/integration/test_handler.py
@@ -165,6 +165,7 @@ def test_precheck_push(github_push_event):
             id=1,
             job_config_trigger_type=JobConfigTriggerType.commit,
             job_trigger_model_type=JobTriggerModelType.branch_push,
+            name="build-branch",
         )
     )
     jc = JobConfig(
@@ -203,7 +204,9 @@ def test_precheck_push(github_push_event):
 
 def test_precheck_push_to_a_different_branch(github_push_event):
     flexmock(GitBranchModel).should_receive("get_or_create").and_return(
-        flexmock(id=1, job_config_trigger_type=JobConfigTriggerType.commit)
+        flexmock(
+            id=1, job_config_trigger_type=JobConfigTriggerType.commit, name="branch"
+        )
     )
 
     package_config = PackageConfig(
@@ -254,7 +257,7 @@ def test_precheck_push_actor_check(github_push_event):
         packages={"package": CommonPackageConfig(branch="branch")},
     )
     event = github_push_event.get_dict()
-    actor_checker = CoprBuildHandler.get_checkers()[1]
+    actor_checker = CoprBuildHandler.get_checkers()[2]
     assert actor_checker(package_config, job_config, event).pre_check()
 
 
diff --git a/tests/integration/test_listen_to_fedmsg.py b/tests/integration/test_listen_to_fedmsg.py
index bc236043..bda11888 100644
--- a/tests/integration/test_listen_to_fedmsg.py
+++ b/tests/integration/test_listen_to_fedmsg.py
@@ -175,6 +175,7 @@ def pc_build_push():
                     "package": CommonPackageConfig(
                         _targets=["fedora-all"],
                         specfile_path="test.spec",
+                        branch="build-branch",
                     )
                 },
             )
@@ -768,6 +769,217 @@ def test_copr_build_end_testing_farm(copr_build_end, copr_build_pr):
     )
 
 
+def test_copr_build_end_push_testing_farm(copr_build_end_push, copr_build_branch_push):
+    config = PackageConfig(
+        packages={
+            "package": CommonPackageConfig(
+                specfile_path="test.spec",
+            )
+        },
+        jobs=[
+            JobConfig(
+                type=JobType.copr_build,
+                trigger=JobConfigTriggerType.commit,
+                packages={
+                    "package": CommonPackageConfig(
+                        _targets=["fedora-all"],
+                        specfile_path="test.spec",
+                        branch="build-branch",
+                    )
+                },
+            ),
+            JobConfig(
+                type=JobType.tests,
+                trigger=JobConfigTriggerType.commit,
+                packages={
+                    "package": CommonPackageConfig(
+                        _targets=["fedora-all"],
+                        specfile_path="test.spec",
+                        branch="build-branch",
+                    )
+                },
+            ),
+        ],
+    )
+
+    flexmock(AbstractCoprBuildEvent).should_receive("get_packages_config").and_return(
+        config
+    )
+    flexmock(PackageConfigGetter).should_receive(
+        "get_package_config_from_repo"
+    ).and_return(config)
+
+    flexmock(GithubProject).should_receive("is_private").and_return(False)
+    flexmock(GithubProject).should_receive("get_pr").and_return(
+        # we cannot comment for branch push events
+        flexmock(source_project=flexmock())
+        .should_receive("comment")
+        .never()
+    )
+    flexmock(CoprHelper).should_receive("get_copr_client").and_return(
+        Client(config={"username": "packit", "copr_url": "https://dummy.url"})
+    )
+
+    flexmock(CoprBuildTargetModel).should_receive("get_by_build_id").and_return(
+        copr_build_branch_push
+    )
+
+    copr_build_branch_push.should_receive("set_status").with_args(BuildStatus.success)
+    copr_build_branch_push.should_receive("set_end_time").once()
+    url = get_copr_build_info_url(1)
+    flexmock(requests).should_receive("get").and_return(requests.Response())
+    flexmock(requests.Response).should_receive("raise_for_status").and_return(None)
+    flexmock(CoprBuildJobHelper).should_receive(
+        "report_status_to_build_for_chroot"
+    ).with_args(
+        state=BaseCommitStatus.success,
+        description="RPMs were built successfully.",
+        url=url,
+        chroot=copr_build_end_push["chroot"],
+    ).once()
+    flexmock(CoprBuildJobHelper).should_receive(
+        "report_status_to_all_test_jobs_for_chroot"
+    ).with_args(
+        state=BaseCommitStatus.pending,
+        description="RPMs were built successfully.",
+        url=url,
+        chroot=copr_build_end_push["chroot"],
+    ).once()
+
+    flexmock(Signature).should_receive("apply_async").twice()
+
+    # skip SRPM url since it touches multiple classes
+    flexmock(CoprBuildEndHandler).should_receive("set_srpm_url").and_return(None)
+
+    (
+        flexmock(CoprBuildJobHelper)
+        .should_receive("get_build_chroot")
+        .with_args(1, "some-target")
+        .and_return(flexmock(ended_on=1666889710))
+        .at_least()
+        .once()
+    )
+
+    flexmock(Pushgateway).should_receive("push").once().and_return()
+
+    processing_results = SteveJobs().process_message(copr_build_end_push)
+    event_dict, job, job_config, package_config = get_parameters_from_results(
+        processing_results
+    )
+    assert json.dumps(event_dict)
+
+    flexmock(CoprBuildJobHelper).should_receive("get_built_packages").and_return([])
+
+    run_copr_build_end_handler(
+        package_config=package_config,
+        event=event_dict,
+        job_config=job_config,
+    )
+
+
+def test_copr_build_end_push_testing_farm_different_branch(
+    copr_build_end_push, copr_build_branch_push
+):
+    config = PackageConfig(
+        packages={
+            "package": CommonPackageConfig(
+                specfile_path="test.spec",
+            )
+        },
+        jobs=[
+            JobConfig(
+                type=JobType.copr_build,
+                trigger=JobConfigTriggerType.commit,
+                packages={
+                    "package": CommonPackageConfig(
+                        _targets=["fedora-all"],
+                        specfile_path="test.spec",
+                        branch="build-branch",
+                    )
+                },
+            ),
+            JobConfig(
+                type=JobType.tests,
+                trigger=JobConfigTriggerType.commit,
+                packages={
+                    "package": CommonPackageConfig(
+                        _targets=["fedora-all"],
+                        specfile_path="test.spec",
+                        branch="test-branch",
+                    )
+                },
+            ),
+        ],
+    )
+
+    flexmock(AbstractCoprBuildEvent).should_receive("get_packages_config").and_return(
+        config
+    )
+    flexmock(PackageConfigGetter).should_receive(
+        "get_package_config_from_repo"
+    ).and_return(config)
+
+    flexmock(GithubProject).should_receive("is_private").and_return(False)
+    flexmock(GithubProject).should_receive("get_pr").and_return(
+        # we cannot comment for branch push events
+        flexmock(source_project=flexmock())
+        .should_receive("comment")
+        .never()
+    )
+    flexmock(CoprHelper).should_receive("get_copr_client").and_return(
+        Client(config={"username": "packit", "copr_url": "https://dummy.url"})
+    )
+
+    flexmock(CoprBuildTargetModel).should_receive("get_by_build_id").and_return(
+        copr_build_branch_push
+    )
+
+    copr_build_branch_push.should_receive("set_status").with_args(BuildStatus.success)
+    copr_build_branch_push.should_receive("set_end_time").once()
+    url = get_copr_build_info_url(1)
+    flexmock(requests).should_receive("get").and_return(requests.Response())
+    flexmock(requests.Response).should_receive("raise_for_status").and_return(None)
+    # check if packit-service set correct PR status
+    flexmock(CoprBuildJobHelper).should_receive(
+        "report_status_to_build_for_chroot"
+    ).with_args(
+        state=BaseCommitStatus.success,
+        description="RPMs were built successfully.",
+        url=url,
+        chroot=copr_build_end_push["chroot"],
+    ).once()
+
+    flexmock(Signature).should_receive("apply_async").once()
+
+    # skip SRPM url since it touches multiple classes
+    flexmock(CoprBuildEndHandler).should_receive("set_srpm_url").and_return(None)
+
+    (
+        flexmock(CoprBuildJobHelper)
+        .should_receive("get_build_chroot")
+        .with_args(1, "some-target")
+        .and_return(flexmock(ended_on=1666889710))
+        .at_least()
+        .once()
+    )
+
+    flexmock(Pushgateway).should_receive("push").once().and_return()
+
+    processing_results = SteveJobs().process_message(copr_build_end_push)
+    event_dict, job, job_config, package_config = get_parameters_from_results(
+        processing_results
+    )
+    assert json.dumps(event_dict)
+
+    flexmock(CoprBuildJobHelper).should_receive("get_built_packages").and_return([])
+
+    run_copr_build_end_handler(
+        package_config=package_config,
+        event=event_dict,
+        job_config=job_config,
+    )
+
+
 def test_copr_build_end_report_multiple_testing_farm_jobs(
     copr_build_end, copr_build_pr
 ):
diff --git a/tests/integration/test_pr_comment.py b/tests/integration/test_pr_comment.py
index fc4a88f0..9e3b882f 100644
--- a/tests/integration/test_pr_comment.py
+++ b/tests/integration/test_pr_comment.py
@@ -1797,7 +1797,9 @@ def test_pr_test_command_handler_not_allowed_external_contributor_on_internal_TF
         project_url="https://github.com/packit-service/hello-world",
     ).and_return(
         flexmock(id=9, job_config_trigger_type=JobConfigTriggerType.pull_request)
-    ).twice()
+    ).times(
+        3
+    )
     pr_embedded_command_comment_event["comment"]["body"] = "/packit test"
     flexmock(
         GithubProject, get_files=lambda ref, recursive: ["foo.spec", ".packit.yaml"]
@@ -1865,7 +1867,7 @@ def test_pr_build_command_handler_not_allowed_external_contributor_on_internal_T
     ).and_return(
         flexmock(id=9, job_config_trigger_type=JobConfigTriggerType.pull_request)
     ).times(
-        4
+        6
     )
     pr_embedded_command_comment_event["comment"]["body"] = "/packit build"
     flexmock(
diff --git a/tests/unit/test_build_helper.py b/tests/unit/test_build_helper.py
index 97346dd9..97310716 100644
--- a/tests/unit/test_build_helper.py
+++ b/tests/unit/test_build_helper.py
@@ -42,6 +42,13 @@ def _mock_targets(jobs, job, job_type):
     job_config_trigger_type, job_trigger_model_type = job_type
 
     project_service = flexmock(instance_url="https://github.com")
+    db_trigger = flexmock(
+        job_config_trigger_type=job_config_trigger_type,
+        job_trigger_model_type=job_trigger_model_type,
+    )
+    if job_config_trigger_type == JobConfigTriggerType.commit:
+        db_trigger.name = "main"
+
     return CoprBuildJobHelper(
         service_config=ServiceConfig.get_service_config(),
         package_config=PackageConfig(
@@ -49,13 +56,13 @@ def _mock_targets(jobs, job, job_type):
         ),
         job_config=job,  # BuildHelper looks at all jobs in the end
         project=flexmock(
-            service=project_service, namespace="packit", repo="testing_package"
+            service=project_service,
+            namespace="packit",
+            repo="testing_package",
+            default_branch="main",
         ),
         metadata=flexmock(pr_id=None, identifier=None),
-        db_trigger=flexmock(
-            job_config_trigger_type=job_config_trigger_type,
-            job_trigger_model_type=job_trigger_model_type,
-        ),
+        db_trigger=db_trigger,
     )
 
 
@@ -134,7 +141,7 @@ def _mock_targets(jobs, job, job_type):
                     packages={
                         "package": CommonPackageConfig(
                             _targets=STABLE_VERSIONS,
-                        )
+                        ),
                     },
                 ),
                 JobConfig(
@@ -193,7 +200,7 @@ def _mock_targets(jobs, job, job_type):
                     packages={
                         "package": CommonPackageConfig(
                             _targets=STABLE_VERSIONS,
-                        )
+                        ),
                     },
                 ),
             ],
@@ -769,6 +776,12 @@ def test_configured_build_targets(jobs, job_type, build_chroots):
 )
 def test_configured_tests_targets(jobs, job_type, test_chroots):
     job_config_trigger_type, job_trigger_model_type = job_type
+    db_trigger = flexmock(
+        job_config_trigger_type=job_config_trigger_type,
+        job_trigger_model_type=job_trigger_model_type,
+    )
+    if job_config_trigger_type == JobConfigTriggerType.commit:
+        db_trigger.name = "main"
 
     project_service = flexmock(instance_url="https://github.com")
     helper = TestingFarmJobHelper(
@@ -778,13 +791,13 @@ def test_configured_tests_targets(jobs, job_type, test_chroots):
         ),
         job_config=jobs[-1],  # test job is always the last in the list
         project=flexmock(
-            service=project_service, namespace="packit", repo="testing_package"
+            service=project_service,
+            namespace="packit",
+            repo="testing_package",
+            default_branch="main",
         ),
         metadata=flexmock(pr_id=None, identifier=None),
-        db_trigger=flexmock(
-            job_config_trigger_type=job_config_trigger_type,
-            job_trigger_model_type=job_trigger_model_type,
-        ),
+        db_trigger=db_trigger,
     )
 
     assert helper.package_config.jobs
@@ -839,12 +852,16 @@ def test_deduced_copr_targets():
         ),
         job_config=jobs[-1],  # BuildHelper looks at all jobs in the end
         project=flexmock(
-            service=flexmock(), namespace="packit", repo="testing_package"
+            service=flexmock(),
+            namespace="packit",
+            repo="testing_package",
+            default_branch="main",
         ),
         metadata=flexmock(pr_id=None, identifier=None),
         db_trigger=flexmock(
             job_config_trigger_type=job_type[0],
             job_trigger_model_type=job_type[1],
+            name="main",
         ),
     ).configured_tests_targets == {"opensuse-tumbleweed-x86_64"}
 
@@ -2125,15 +2142,21 @@ def test_build_handler_job_and_test_properties(
     result_job_build,
     result_job_tests,
 ):
+    db_trigger = flexmock(
+        job_config_trigger_type=job_config_trigger_type,
+    )
+    if job_config_trigger_type == JobConfigTriggerType.commit:
+        db_trigger.name = "main"
+
     copr_build_helper = CoprBuildJobHelper(
         service_config=ServiceConfig.get_service_config(),
         package_config=PackageConfig(
             jobs=jobs, packages={"package": CommonPackageConfig()}
         ),
         job_config=init_job,
-        project=flexmock(),
+        project=flexmock(default_branch="main"),
         metadata=flexmock(pr_id=None),
-        db_trigger=flexmock(job_config_trigger_type=job_config_trigger_type),
+        db_trigger=db_trigger,
     )
 
     assert copr_build_helper.package_config.jobs
@@ -2473,6 +2496,7 @@ def test_copr_project_and_namespace(
             namespace="the/example/namespace",
             repo="the-example-repo",
             service=flexmock(instance_url="https://git.instance.io"),
+            default_branch="main",
         ),
         metadata=flexmock(
             pr_id=None, identifier="the-event-identifier", tag_name=tag_name
@@ -2480,6 +2504,7 @@ def test_copr_project_and_namespace(
         db_trigger=flexmock(
             job_config_trigger_type=job_config_trigger_type,
             job_trigger_model_type=job_trigger_model_type,
+            name="main",
         ),
     )
     copr_build_helper._api = flexmock(
@@ -2670,7 +2695,9 @@ def test_targets_for_koji_build(
         job_config=jobs[0],
         project=flexmock(),
         metadata=flexmock(pr_id=pr_id),
-        db_trigger=flexmock(job_config_trigger_type=job_config_trigger_type),
+        db_trigger=flexmock(
+            job_config_trigger_type=job_config_trigger_type, name="build-branch"
+        ),
     )
 
     assert koji_build_helper.package_config.jobs
diff --git a/tests/unit/test_checkers.py b/tests/unit/test_checkers.py
index 97aa9d28..34cd57e6 100644
--- a/tests/unit/test_checkers.py
+++ b/tests/unit/test_checkers.py
@@ -7,7 +7,18 @@ from flexmock import flexmock
 from packit.config.job_config import JobType, JobConfigTriggerType
 from packit_service.config import ServiceConfig
 from packit_service.models import CoprBuildTargetModel
-from packit_service.worker.checker.koji import PermissionOnKoji
+from packit_service.worker.checker.koji import (
+    PermissionOnKoji,
+)
+from packit_service.worker.checker.koji import (
+    IsJobConfigTriggerMatching as IsJobConfigTriggerMatchingKoji,
+)
+from packit_service.worker.checker.copr import (
+    IsJobConfigTriggerMatching as IsJobConfigTriggerMatchingCopr,
+)
+from packit_service.worker.checker.testing_farm import (
+    IsJobConfigTriggerMatching as IsJobConfigTriggerMatchingTF,
+)
 from packit_service.worker.checker.vm_image import (
     IsCoprBuildForChrootOk,
     HasAuthorWriteAccess,
@@ -47,38 +58,6 @@ def construct_dict(event, action=None, git_ref="random-non-configured-branch"):
             JobConfigTriggerType.pull_request,
             id="closed MRs are ignored",
         ),
-        pytest.param(
-            False,
-            construct_dict(event=PushGitHubEvent.__name__),
-            True,
-            None,
-            JobConfigTriggerType.commit,
-            id="GitHub push to non-configured branch is ignored",
-        ),
-        pytest.param(
-            False,
-            construct_dict(event=PushGitlabEvent.__name__),
-            True,
-            None,
-            JobConfigTriggerType.commit,
-            id="GitLab push to non-configured branch is ignored",
-        ),
-        pytest.param(
-            False,
-            construct_dict(event=PushPagureEvent.__name__),
-            True,
-            None,
-            JobConfigTriggerType.commit,
-            id="Pagure push to non-configured branch is ignored",
-        ),
-        pytest.param(
-            True,
-            construct_dict(event=PushPagureEvent.__name__, git_ref="release"),
-            True,
-            None,
-            JobConfigTriggerType.commit,
-            id="Pagure push to configured branch is not ignored",
-        ),
         pytest.param(
             False,
             construct_dict(event=PullRequestGithubEvent.__name__),
@@ -139,7 +118,7 @@ def test_koji_permissions(success, event, is_scratch, can_merge_pr, trigger):
     git_project.should_receive("can_merge_pr").and_return(can_merge_pr)
     flexmock(ConfigFromEventMixin).should_receive("project").and_return(git_project)
 
-    db_trigger = flexmock(job_config_trigger_type=trigger)
+    db_trigger = flexmock(job_config_trigger_type=trigger, name=event["git_ref"])
     flexmock(EventData).should_receive("db_trigger").and_return(db_trigger)
 
     if not success:
@@ -150,6 +129,67 @@ def test_koji_permissions(success, event, is_scratch, can_merge_pr, trigger):
     assert checker.pre_check() == success
 
 
+@pytest.mark.parametrize(
+    "checker_kls",
+    (
+        IsJobConfigTriggerMatchingKoji,
+        IsJobConfigTriggerMatchingCopr,
+        IsJobConfigTriggerMatchingTF,
+    ),
+)
+@pytest.mark.parametrize(
+    "success, event, trigger",
+    (
+        pytest.param(
+            False,
+            construct_dict(event=PushGitHubEvent.__name__),
+            JobConfigTriggerType.commit,
+            id="GitHub push to non-configured branch is ignored",
+        ),
+        pytest.param(
+            False,
+            construct_dict(event=PushGitlabEvent.__name__),
+            JobConfigTriggerType.commit,
+            id="GitLab push to non-configured branch is ignored",
+        ),
+        pytest.param(
+            False,
+            construct_dict(event=PushPagureEvent.__name__),
+            JobConfigTriggerType.commit,
+            id="Pagure push to non-configured branch is ignored",
+        ),
+        pytest.param(
+            True,
+            construct_dict(event=PushPagureEvent.__name__, git_ref="release"),
+            JobConfigTriggerType.commit,
+            id="Pagure push to configured branch is not ignored",
+        ),
+    ),
+)
+def test_branch_push_event_checker(success, event, trigger, checker_kls):
+    package_config = flexmock(jobs=[])
+    job_config = flexmock(
+        type=JobType.upstream_koji_build,
+        trigger=trigger,
+        targets={"fedora-37"},
+        branch="release",
+    )
+
+    git_project = flexmock(
+        namespace="packit",
+        repo="ogr",
+        default_branch="main",
+    )
+    flexmock(ConfigFromEventMixin).should_receive("project").and_return(git_project)
+
+    db_trigger = flexmock(job_config_trigger_type=trigger, name=event["git_ref"])
+    flexmock(EventData).should_receive("db_trigger").and_return(db_trigger)
+
+    checker = checker_kls(package_config, job_config, event)
+
+    assert checker.pre_check() == success
+
+
 @pytest.mark.parametrize(
     "success, copr_builds, error_msg",
     (
@@ -279,7 +319,7 @@ def test_vm_image_has_author_write_access(
     assert checker.pre_check() == result
 
 
-def test_koji_permissions_merge_queue():
+def test_koji_branch_merge_queue():
     """
     Check that specifying regex for GitHub merge queue temporary branch where the
     CI must be green passes the check.
@@ -301,14 +341,16 @@ def test_koji_permissions_merge_queue():
     git_project = flexmock(
         namespace="packit",
         repo="ogr",
-        default_branch="main",
     )
     git_project.should_receive("can_merge_pr").and_return(True)
     flexmock(ConfigFromEventMixin).should_receive("project").and_return(git_project)
 
-    db_trigger = flexmock(job_config_trigger_type=JobConfigTriggerType.commit)
+    db_trigger = flexmock(
+        job_config_trigger_type=JobConfigTriggerType.commit,
+        name="gh-readonly-queue/main/pr-767-0203dd99c3d003cbfd912cec946cc5b46f695b10",
+    )
     flexmock(EventData).should_receive("db_trigger").and_return(db_trigger)
 
-    checker = PermissionOnKoji(package_config, job_config, event)
+    checker = IsJobConfigTriggerMatchingKoji(package_config, job_config, event)
 
     assert checker.pre_check()