id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,100 | projects.py | python-gitlab_python-gitlab/gitlab/v4/objects/projects.py | """
GitLab API:
https://docs.gitlab.com/ee/api/projects.html
"""
import io
from typing import (
Any,
Callable,
cast,
Dict,
Iterator,
List,
Optional,
TYPE_CHECKING,
Union,
)
import requests
from gitlab import cli, client
from gitlab import exceptions as exc
from gitlab import types, utils
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
CRUDMixin,
DeleteMixin,
GetWithoutIdMixin,
ListMixin,
ObjectDeleteMixin,
RefreshMixin,
SaveMixin,
UpdateMixin,
UploadMixin,
)
from gitlab.types import RequiredOptional
from .access_requests import ProjectAccessRequestManager # noqa: F401
from .artifacts import ProjectArtifactManager # noqa: F401
from .audit_events import ProjectAuditEventManager # noqa: F401
from .badges import ProjectBadgeManager # noqa: F401
from .boards import ProjectBoardManager # noqa: F401
from .branches import ProjectBranchManager, ProjectProtectedBranchManager # noqa: F401
from .ci_lint import ProjectCiLintManager # noqa: F401
from .cluster_agents import ProjectClusterAgentManager # noqa: F401
from .clusters import ProjectClusterManager # noqa: F401
from .commits import ProjectCommitManager # noqa: F401
from .container_registry import ProjectRegistryRepositoryManager # noqa: F401
from .custom_attributes import ProjectCustomAttributeManager # noqa: F401
from .deploy_keys import ProjectKeyManager # noqa: F401
from .deploy_tokens import ProjectDeployTokenManager # noqa: F401
from .deployments import ProjectDeploymentManager # noqa: F401
from .environments import ( # noqa: F401
ProjectEnvironmentManager,
ProjectProtectedEnvironmentManager,
)
from .events import ProjectEventManager # noqa: F401
from .export_import import ProjectExportManager, ProjectImportManager # noqa: F401
from .files import ProjectFileManager # noqa: F401
from .hooks import ProjectHookManager # noqa: F401
from .integrations import ProjectIntegrationManager, ProjectServiceManager # noqa: F401
from .invitations import ProjectInvitationManager # noqa: F401
from .issues import ProjectIssueManager # noqa: F401
from .iterations import ProjectIterationManager # noqa: F401
from .job_token_scope import ProjectJobTokenScopeManager # noqa: F401
from .jobs import ProjectJobManager # noqa: F401
from .labels import ProjectLabelManager # noqa: F401
from .members import ProjectMemberAllManager, ProjectMemberManager # noqa: F401
from .merge_request_approvals import ( # noqa: F401
ProjectApprovalManager,
ProjectApprovalRuleManager,
)
from .merge_requests import ProjectMergeRequestManager # noqa: F401
from .merge_trains import ProjectMergeTrainManager # noqa: F401
from .milestones import ProjectMilestoneManager # noqa: F401
from .notes import ProjectNoteManager # noqa: F401
from .notification_settings import ProjectNotificationSettingsManager # noqa: F401
from .package_protection_rules import ProjectPackageProtectionRuleManager
from .packages import GenericPackageManager, ProjectPackageManager # noqa: F401
from .pages import ProjectPagesDomainManager, ProjectPagesManager # noqa: F401
from .pipelines import ( # noqa: F401
ProjectPipeline,
ProjectPipelineManager,
ProjectPipelineScheduleManager,
)
from .project_access_tokens import ProjectAccessTokenManager # noqa: F401
from .push_rules import ProjectPushRulesManager # noqa: F401
from .registry_protection_rules import ( # noqa: F401
ProjectRegistryProtectionRuleManager,
)
from .releases import ProjectReleaseManager # noqa: F401
from .repositories import RepositoryMixin
from .resource_groups import ProjectResourceGroupManager
from .runners import ProjectRunnerManager # noqa: F401
from .secure_files import ProjectSecureFileManager # noqa: F401
from .snippets import ProjectSnippetManager # noqa: F401
from .statistics import ( # noqa: F401
ProjectAdditionalStatisticsManager,
ProjectIssuesStatisticsManager,
)
from .tags import ProjectProtectedTagManager, ProjectTagManager # noqa: F401
from .triggers import ProjectTriggerManager # noqa: F401
from .users import ProjectUserManager # noqa: F401
from .variables import ProjectVariableManager # noqa: F401
from .wikis import ProjectWikiManager # noqa: F401
__all__ = [
"GroupProject",
"GroupProjectManager",
"Project",
"ProjectManager",
"ProjectFork",
"ProjectForkManager",
"ProjectRemoteMirror",
"ProjectRemoteMirrorManager",
"ProjectStorage",
"ProjectStorageManager",
"SharedProject",
"SharedProjectManager",
]
class GroupProject(RESTObject):
pass
class GroupProjectManager(ListMixin, RESTManager):
_path = "/groups/{group_id}/projects"
_obj_cls = GroupProject
_from_parent_attrs = {"group_id": "id"}
_list_filters = (
"archived",
"visibility",
"order_by",
"sort",
"search",
"simple",
"owned",
"starred",
"with_custom_attributes",
"include_subgroups",
"with_issues_enabled",
"with_merge_requests_enabled",
"with_shared",
"min_access_level",
"with_security_reports",
)
class ProjectGroup(RESTObject):
pass
class ProjectGroupManager(ListMixin, RESTManager):
_path = "/projects/{project_id}/groups"
_obj_cls = ProjectGroup
_from_parent_attrs = {"project_id": "id"}
_list_filters = (
"search",
"skip_groups",
"with_shared",
"shared_min_access_level",
"shared_visible_only",
)
_types = {"skip_groups": types.ArrayAttribute}
class Project(
RefreshMixin, SaveMixin, ObjectDeleteMixin, RepositoryMixin, UploadMixin, RESTObject
):
_repr_attr = "path_with_namespace"
_upload_path = "/projects/{id}/uploads"
access_tokens: ProjectAccessTokenManager
accessrequests: ProjectAccessRequestManager
additionalstatistics: ProjectAdditionalStatisticsManager
approvalrules: ProjectApprovalRuleManager
approvals: ProjectApprovalManager
artifacts: ProjectArtifactManager
audit_events: ProjectAuditEventManager
badges: ProjectBadgeManager
boards: ProjectBoardManager
branches: ProjectBranchManager
ci_lint: ProjectCiLintManager
clusters: ProjectClusterManager
cluster_agents: ProjectClusterAgentManager
commits: ProjectCommitManager
customattributes: ProjectCustomAttributeManager
deployments: ProjectDeploymentManager
deploytokens: ProjectDeployTokenManager
environments: ProjectEnvironmentManager
events: ProjectEventManager
exports: ProjectExportManager
files: ProjectFileManager
forks: "ProjectForkManager"
generic_packages: GenericPackageManager
groups: ProjectGroupManager
hooks: ProjectHookManager
imports: ProjectImportManager
integrations: ProjectIntegrationManager
invitations: ProjectInvitationManager
issues: ProjectIssueManager
issues_statistics: ProjectIssuesStatisticsManager
iterations: ProjectIterationManager
jobs: ProjectJobManager
job_token_scope: ProjectJobTokenScopeManager
keys: ProjectKeyManager
labels: ProjectLabelManager
members: ProjectMemberManager
members_all: ProjectMemberAllManager
mergerequests: ProjectMergeRequestManager
merge_trains: ProjectMergeTrainManager
milestones: ProjectMilestoneManager
notes: ProjectNoteManager
notificationsettings: ProjectNotificationSettingsManager
packages: ProjectPackageManager
package_protection_rules: ProjectPackageProtectionRuleManager
pages: ProjectPagesManager
pagesdomains: ProjectPagesDomainManager
pipelines: ProjectPipelineManager
pipelineschedules: ProjectPipelineScheduleManager
protected_environments: ProjectProtectedEnvironmentManager
protectedbranches: ProjectProtectedBranchManager
protectedtags: ProjectProtectedTagManager
pushrules: ProjectPushRulesManager
registry_protection_rules: ProjectRegistryProtectionRuleManager
releases: ProjectReleaseManager
resource_groups: ProjectResourceGroupManager
remote_mirrors: "ProjectRemoteMirrorManager"
repositories: ProjectRegistryRepositoryManager
runners: ProjectRunnerManager
secure_files: ProjectSecureFileManager
services: ProjectServiceManager
snippets: ProjectSnippetManager
storage: "ProjectStorageManager"
tags: ProjectTagManager
triggers: ProjectTriggerManager
users: ProjectUserManager
variables: ProjectVariableManager
wikis: ProjectWikiManager
@cli.register_custom_action(cls_names="Project", required=("forked_from_id",))
@exc.on_http_error(exc.GitlabCreateError)
def create_fork_relation(self, forked_from_id: int, **kwargs: Any) -> None:
"""Create a forked from/to relation between existing projects.
Args:
forked_from_id: The ID of the project that was forked from
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the relation could not be created
"""
path = f"/projects/{self.encoded_id}/fork/{forked_from_id}"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabDeleteError)
def delete_fork_relation(self, **kwargs: Any) -> None:
"""Delete a forked relation between existing projects.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/fork"
self.manager.gitlab.http_delete(path, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabGetError)
def languages(self, **kwargs: Any) -> Union[Dict[str, Any], requests.Response]:
"""Get languages used in the project with percentage value.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/languages"
return self.manager.gitlab.http_get(path, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabCreateError)
def star(self, **kwargs: Any) -> None:
"""Star a project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/star"
server_data = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
self._update_attrs(server_data)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabDeleteError)
def unstar(self, **kwargs: Any) -> None:
"""Unstar a project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/unstar"
server_data = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
self._update_attrs(server_data)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabCreateError)
def archive(self, **kwargs: Any) -> None:
"""Archive a project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/archive"
server_data = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
self._update_attrs(server_data)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabDeleteError)
def unarchive(self, **kwargs: Any) -> None:
"""Unarchive a project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/unarchive"
server_data = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
self._update_attrs(server_data)
@cli.register_custom_action(
cls_names="Project",
required=("group_id", "group_access"),
optional=("expires_at",),
)
@exc.on_http_error(exc.GitlabCreateError)
def share(
self,
group_id: int,
group_access: int,
expires_at: Optional[str] = None,
**kwargs: Any,
) -> None:
"""Share the project with a group.
Args:
group_id: ID of the group.
group_access: Access level for the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/share"
data = {
"group_id": group_id,
"group_access": group_access,
"expires_at": expires_at,
}
self.manager.gitlab.http_post(path, post_data=data, **kwargs)
@cli.register_custom_action(cls_names="Project", required=("group_id",))
@exc.on_http_error(exc.GitlabDeleteError)
def unshare(self, group_id: int, **kwargs: Any) -> None:
"""Delete a shared project link within a group.
Args:
group_id: ID of the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/share/{group_id}"
self.manager.gitlab.http_delete(path, **kwargs)
# variables not supported in CLI
@cli.register_custom_action(cls_names="Project", required=("ref", "token"))
@exc.on_http_error(exc.GitlabCreateError)
def trigger_pipeline(
self,
ref: str,
token: str,
variables: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> ProjectPipeline:
"""Trigger a CI build.
See https://gitlab.com/help/ci/triggers/README.md#trigger-a-build
Args:
ref: Commit to build; can be a branch name or a tag
token: The trigger token
variables: Variables passed to the build script
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request
"""
variables = variables or {}
path = f"/projects/{self.encoded_id}/trigger/pipeline"
post_data = {"ref": ref, "token": token, "variables": variables}
attrs = self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)
if TYPE_CHECKING:
assert isinstance(attrs, dict)
return ProjectPipeline(self.pipelines, attrs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabHousekeepingError)
def housekeeping(self, **kwargs: Any) -> None:
"""Start the housekeeping task.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabHousekeepingError: If the server failed to perform the
request
"""
path = f"/projects/{self.encoded_id}/housekeeping"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabRestoreError)
def restore(self, **kwargs: Any) -> None:
"""Restore a project marked for deletion.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabRestoreError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/restore"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(cls_names="Project", optional=("wiki",))
@exc.on_http_error(exc.GitlabGetError)
def snapshot(
self,
wiki: bool = False,
streamed: bool = False,
action: Optional[Callable[[bytes], None]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Return a snapshot of the repository.
Args:
wiki: If True return the wiki repository
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment.
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the content could not be retrieved
Returns:
The uncompressed tar archive of the repository
"""
path = f"/projects/{self.encoded_id}/snapshot"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, wiki=wiki, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
@cli.register_custom_action(cls_names="Project", required=("scope", "search"))
@exc.on_http_error(exc.GitlabSearchError)
def search(
self, scope: str, search: str, **kwargs: Any
) -> Union[client.GitlabList, List[Dict[str, Any]]]:
"""Search the project resources matching the provided string.'
Args:
scope: Scope of the search
search: Search string
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabSearchError: If the server failed to perform the request
Returns:
A list of dicts describing the resources found.
"""
data = {"scope": scope, "search": search}
path = f"/projects/{self.encoded_id}/search"
return self.manager.gitlab.http_list(path, query_data=data, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabCreateError)
def mirror_pull(self, **kwargs: Any) -> None:
"""Start the pull mirroring process for the project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/mirror/pull"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabGetError)
def mirror_pull_details(self, **kwargs: Any) -> Dict[str, Any]:
"""Get a project's pull mirror details.
Introduced in GitLab 15.5.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
dict of the parsed json returned by the server
"""
path = f"/projects/{self.encoded_id}/mirror/pull"
result = self.manager.gitlab.http_get(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(result, dict)
return result
@cli.register_custom_action(cls_names="Project", required=("to_namespace",))
@exc.on_http_error(exc.GitlabTransferProjectError)
def transfer(self, to_namespace: Union[int, str], **kwargs: Any) -> None:
"""Transfer a project to the given namespace ID
Args:
to_namespace: ID or path of the namespace to transfer the
project to
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTransferProjectError: If the project could not be transferred
"""
path = f"/projects/{self.encoded_id}/transfer"
self.manager.gitlab.http_put(
path, post_data={"namespace": to_namespace}, **kwargs
)
class ProjectManager(CRUDMixin, RESTManager):
_path = "/projects"
_obj_cls = Project
# Please keep these _create_attrs in same order as they are at:
# https://docs.gitlab.com/ee/api/projects.html#create-project
_create_attrs = RequiredOptional(
optional=(
"name",
"path",
"allow_merge_on_skipped_pipeline",
"only_allow_merge_if_all_status_checks_passed",
"analytics_access_level",
"approvals_before_merge",
"auto_cancel_pending_pipelines",
"auto_devops_deploy_strategy",
"auto_devops_enabled",
"autoclose_referenced_issues",
"avatar",
"build_coverage_regex",
"build_git_strategy",
"build_timeout",
"builds_access_level",
"ci_config_path",
"container_expiration_policy_attributes",
"container_registry_access_level",
"container_registry_enabled",
"default_branch",
"description",
"emails_disabled",
"external_authorization_classification_label",
"forking_access_level",
"group_with_project_templates_id",
"import_url",
"initialize_with_readme",
"issues_access_level",
"issues_enabled",
"jobs_enabled",
"lfs_enabled",
"merge_method",
"merge_pipelines_enabled",
"merge_requests_access_level",
"merge_requests_enabled",
"mirror_trigger_builds",
"mirror",
"namespace_id",
"operations_access_level",
"only_allow_merge_if_all_discussions_are_resolved",
"only_allow_merge_if_pipeline_succeeds",
"packages_enabled",
"pages_access_level",
"requirements_access_level",
"printing_merge_request_link_enabled",
"public_builds",
"releases_access_level",
"environments_access_level",
"feature_flags_access_level",
"infrastructure_access_level",
"monitor_access_level",
"remove_source_branch_after_merge",
"repository_access_level",
"repository_storage",
"request_access_enabled",
"resolve_outdated_diff_discussions",
"security_and_compliance_access_level",
"shared_runners_enabled",
"show_default_award_emojis",
"snippets_access_level",
"snippets_enabled",
"squash_option",
"tag_list",
"topics",
"template_name",
"template_project_id",
"use_custom_template",
"visibility",
"wiki_access_level",
"wiki_enabled",
),
)
# Please keep these _update_attrs in same order as they are at:
# https://docs.gitlab.com/ee/api/projects.html#edit-project
_update_attrs = RequiredOptional(
optional=(
"allow_merge_on_skipped_pipeline",
"only_allow_merge_if_all_status_checks_passed",
"analytics_access_level",
"approvals_before_merge",
"auto_cancel_pending_pipelines",
"auto_devops_deploy_strategy",
"auto_devops_enabled",
"autoclose_referenced_issues",
"avatar",
"build_coverage_regex",
"build_git_strategy",
"build_timeout",
"builds_access_level",
"ci_config_path",
"ci_default_git_depth",
"ci_forward_deployment_enabled",
"ci_allow_fork_pipelines_to_run_in_parent_project",
"ci_separated_caches",
"container_expiration_policy_attributes",
"container_registry_access_level",
"container_registry_enabled",
"default_branch",
"description",
"emails_disabled",
"enforce_auth_checks_on_uploads",
"external_authorization_classification_label",
"forking_access_level",
"import_url",
"issues_access_level",
"issues_enabled",
"issues_template",
"jobs_enabled",
"keep_latest_artifact",
"lfs_enabled",
"merge_commit_template",
"merge_method",
"merge_pipelines_enabled",
"merge_requests_access_level",
"merge_requests_enabled",
"merge_requests_template",
"merge_trains_enabled",
"mirror_overwrites_diverged_branches",
"mirror_trigger_builds",
"mirror_user_id",
"mirror",
"mr_default_target_self",
"name",
"operations_access_level",
"only_allow_merge_if_all_discussions_are_resolved",
"only_allow_merge_if_pipeline_succeeds",
"only_mirror_protected_branches",
"packages_enabled",
"pages_access_level",
"requirements_access_level",
"restrict_user_defined_variables",
"path",
"public_builds",
"releases_access_level",
"environments_access_level",
"feature_flags_access_level",
"infrastructure_access_level",
"monitor_access_level",
"remove_source_branch_after_merge",
"repository_access_level",
"repository_storage",
"request_access_enabled",
"resolve_outdated_diff_discussions",
"security_and_compliance_access_level",
"service_desk_enabled",
"shared_runners_enabled",
"show_default_award_emojis",
"snippets_access_level",
"snippets_enabled",
"issue_branch_template",
"squash_commit_template",
"squash_option",
"suggestion_commit_message",
"tag_list",
"topics",
"visibility",
"wiki_access_level",
"wiki_enabled",
),
)
_list_filters = (
"archived",
"id_after",
"id_before",
"last_activity_after",
"last_activity_before",
"membership",
"min_access_level",
"order_by",
"owned",
"repository_checksum_failed",
"repository_storage",
"search_namespaces",
"search",
"simple",
"sort",
"starred",
"statistics",
"topic",
"visibility",
"wiki_checksum_failed",
"with_custom_attributes",
"with_issues_enabled",
"with_merge_requests_enabled",
"with_programming_language",
)
_types = {
"avatar": types.ImageAttribute,
"topic": types.CommaSeparatedListAttribute,
"topics": types.ArrayAttribute,
}
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> Project:
return cast(Project, super().get(id=id, lazy=lazy, **kwargs))
@exc.on_http_error(exc.GitlabImportError)
def import_project(
self,
file: io.BufferedReader,
path: str,
name: Optional[str] = None,
namespace: Optional[str] = None,
overwrite: bool = False,
override_params: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Union[Dict[str, Any], requests.Response]:
"""Import a project from an archive file.
Args:
file: Data or file object containing the project
path: Name and path for the new project
name: The name of the project to import. If not provided,
defaults to the path of the project.
namespace: The ID or path of the namespace that the project
will be imported to
overwrite: If True overwrite an existing project with the
same path
override_params: Set the specific settings for the project
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabImportError: If the server failed to perform the request
Returns:
A representation of the import status.
"""
files = {"file": ("file.tar.gz", file, "application/octet-stream")}
data = {"path": path, "overwrite": str(overwrite)}
if override_params:
for k, v in override_params.items():
data[f"override_params[{k}]"] = v
if name is not None:
data["name"] = name
if namespace:
data["namespace"] = namespace
return self.gitlab.http_post(
"/projects/import", post_data=data, files=files, **kwargs
)
@exc.on_http_error(exc.GitlabImportError)
def remote_import(
self,
url: str,
path: str,
name: Optional[str] = None,
namespace: Optional[str] = None,
overwrite: bool = False,
override_params: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Union[Dict[str, Any], requests.Response]:
"""Import a project from an archive file stored on a remote URL.
Args:
url: URL for the file containing the project data to import
path: Name and path for the new project
name: The name of the project to import. If not provided,
defaults to the path of the project.
namespace: The ID or path of the namespace that the project
will be imported to
overwrite: If True overwrite an existing project with the
same path
override_params: Set the specific settings for the project
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabImportError: If the server failed to perform the request
Returns:
A representation of the import status.
"""
data = {"path": path, "overwrite": str(overwrite), "url": url}
if override_params:
for k, v in override_params.items():
data[f"override_params[{k}]"] = v
if name is not None:
data["name"] = name
if namespace:
data["namespace"] = namespace
return self.gitlab.http_post(
"/projects/remote-import", post_data=data, **kwargs
)
@exc.on_http_error(exc.GitlabImportError)
def remote_import_s3(
self,
path: str,
region: str,
bucket_name: str,
file_key: str,
access_key_id: str,
secret_access_key: str,
name: Optional[str] = None,
namespace: Optional[str] = None,
overwrite: bool = False,
override_params: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Union[Dict[str, Any], requests.Response]:
"""Import a project from an archive file stored on AWS S3.
Args:
region: AWS S3 region name where the file is stored
bucket_name: AWS S3 bucket name where the file is stored
file_key: AWS S3 file key to identify the file.
access_key_id: AWS S3 access key ID.
secret_access_key: AWS S3 secret access key.
path: Name and path for the new project
name: The name of the project to import. If not provided,
defaults to the path of the project.
namespace: The ID or path of the namespace that the project
will be imported to
overwrite: If True overwrite an existing project with the
same path
override_params: Set the specific settings for the project
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabImportError: If the server failed to perform the request
Returns:
A representation of the import status.
"""
data = {
"region": region,
"bucket_name": bucket_name,
"file_key": file_key,
"access_key_id": access_key_id,
"secret_access_key": secret_access_key,
"path": path,
"overwrite": str(overwrite),
}
if override_params:
for k, v in override_params.items():
data[f"override_params[{k}]"] = v
if name is not None:
data["name"] = name
if namespace:
data["namespace"] = namespace
return self.gitlab.http_post(
"/projects/remote-import-s3", post_data=data, **kwargs
)
def import_bitbucket_server(
self,
bitbucket_server_url: str,
bitbucket_server_username: str,
personal_access_token: str,
bitbucket_server_project: str,
bitbucket_server_repo: str,
new_name: Optional[str] = None,
target_namespace: Optional[str] = None,
**kwargs: Any,
) -> Union[Dict[str, Any], requests.Response]:
"""Import a project from BitBucket Server to Gitlab (schedule the import)
This method will return when an import operation has been safely queued,
or an error has occurred. After triggering an import, check the
``import_status`` of the newly created project to detect when the import
operation has completed.
.. note::
This request may take longer than most other API requests.
So this method will specify a 60 second default timeout if none is
specified.
A timeout can be specified via kwargs to override this functionality.
Args:
bitbucket_server_url: Bitbucket Server URL
bitbucket_server_username: Bitbucket Server Username
personal_access_token: Bitbucket Server personal access
token/password
bitbucket_server_project: Bitbucket Project Key
bitbucket_server_repo: Bitbucket Repository Name
new_name: New repository name (Optional)
target_namespace: Namespace to import repository into.
Supports subgroups like /namespace/subgroup (Optional)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the server failed to perform the request
Returns:
A representation of the import status.
Example:
.. code-block:: python
gl = gitlab.Gitlab_from_config()
print("Triggering import")
result = gl.projects.import_bitbucket_server(
bitbucket_server_url="https://some.server.url",
bitbucket_server_username="some_bitbucket_user",
personal_access_token="my_password_or_access_token",
bitbucket_server_project="my_project",
bitbucket_server_repo="my_repo",
new_name="gl_project_name",
target_namespace="gl_project_path"
)
project = gl.projects.get(ret['id'])
print("Waiting for import to complete")
while project.import_status == u'started':
time.sleep(1.0)
project = gl.projects.get(project.id)
print("BitBucket import complete")
"""
data = {
"bitbucket_server_url": bitbucket_server_url,
"bitbucket_server_username": bitbucket_server_username,
"personal_access_token": personal_access_token,
"bitbucket_server_project": bitbucket_server_project,
"bitbucket_server_repo": bitbucket_server_repo,
}
if new_name:
data["new_name"] = new_name
if target_namespace:
data["target_namespace"] = target_namespace
if (
"timeout" not in kwargs
or self.gitlab.timeout is None
or self.gitlab.timeout < 60.0
):
# Ensure that this HTTP request has a longer-than-usual default timeout
# The base gitlab object tends to have a default that is <10 seconds,
# and this is too short for this API command, typically.
# On the order of 24 seconds has been measured on a typical gitlab instance.
kwargs["timeout"] = 60.0
result = self.gitlab.http_post(
"/import/bitbucket_server", post_data=data, **kwargs
)
return result
def import_github(
self,
personal_access_token: str,
repo_id: int,
target_namespace: str,
new_name: Optional[str] = None,
github_hostname: Optional[str] = None,
optional_stages: Optional[Dict[str, bool]] = None,
**kwargs: Any,
) -> Union[Dict[str, Any], requests.Response]:
"""Import a project from Github to Gitlab (schedule the import)
This method will return when an import operation has been safely queued,
or an error has occurred. After triggering an import, check the
``import_status`` of the newly created project to detect when the import
operation has completed.
.. note::
This request may take longer than most other API requests.
So this method will specify a 60 second default timeout if none is
specified.
A timeout can be specified via kwargs to override this functionality.
Args:
personal_access_token: GitHub personal access token
repo_id: Github repository ID
target_namespace: Namespace to import repo into
new_name: New repo name (Optional)
github_hostname: Custom GitHub Enterprise hostname.
Do not set for GitHub.com. (Optional)
optional_stages: Additional items to import. (Optional)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the server failed to perform the request
Returns:
A representation of the import status.
Example:
.. code-block:: python
gl = gitlab.Gitlab_from_config()
print("Triggering import")
result = gl.projects.import_github(ACCESS_TOKEN,
123456,
"my-group/my-subgroup")
project = gl.projects.get(ret['id'])
print("Waiting for import to complete")
while project.import_status == u'started':
time.sleep(1.0)
project = gl.projects.get(project.id)
print("Github import complete")
"""
data = {
"personal_access_token": personal_access_token,
"repo_id": repo_id,
"target_namespace": target_namespace,
"new_name": new_name,
"github_hostname": github_hostname,
"optional_stages": optional_stages,
}
data = utils.remove_none_from_dict(data)
if (
"timeout" not in kwargs
or self.gitlab.timeout is None
or self.gitlab.timeout < 60.0
):
# Ensure that this HTTP request has a longer-than-usual default timeout
# The base gitlab object tends to have a default that is <10 seconds,
# and this is too short for this API command, typically.
# On the order of 24 seconds has been measured on a typical gitlab instance.
kwargs["timeout"] = 60.0
result = self.gitlab.http_post("/import/github", post_data=data, **kwargs)
return result
class ProjectFork(RESTObject):
pass
class ProjectForkManager(CreateMixin, ListMixin, RESTManager):
_path = "/projects/{project_id}/forks"
_obj_cls = ProjectFork
_from_parent_attrs = {"project_id": "id"}
_list_filters = (
"archived",
"visibility",
"order_by",
"sort",
"search",
"simple",
"owned",
"membership",
"starred",
"statistics",
"with_custom_attributes",
"with_issues_enabled",
"with_merge_requests_enabled",
)
_create_attrs = RequiredOptional(optional=("namespace",))
def create(
self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> ProjectFork:
"""Creates a new object.
Args:
data: Parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request
Returns:
A new instance of the managed object class build with
the data sent by the server
"""
if TYPE_CHECKING:
assert self.path is not None
path = self.path[:-1] # drop the 's'
return cast(ProjectFork, CreateMixin.create(self, data, path=path, **kwargs))
class ProjectRemoteMirror(ObjectDeleteMixin, SaveMixin, RESTObject):
pass
class ProjectRemoteMirrorManager(
ListMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = "/projects/{project_id}/remote_mirrors"
_obj_cls = ProjectRemoteMirror
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("url",), optional=("enabled", "only_protected_branches")
)
_update_attrs = RequiredOptional(optional=("enabled", "only_protected_branches"))
class ProjectStorage(RefreshMixin, RESTObject):
pass
class ProjectStorageManager(GetWithoutIdMixin, RESTManager):
_path = "/projects/{project_id}/storage"
_obj_cls = ProjectStorage
_from_parent_attrs = {"project_id": "id"}
def get(self, **kwargs: Any) -> ProjectStorage:
return cast(ProjectStorage, super().get(**kwargs))
class SharedProject(RESTObject):
pass
class SharedProjectManager(ListMixin, RESTManager):
_path = "/groups/{group_id}/projects/shared"
_obj_cls = SharedProject
_from_parent_attrs = {"group_id": "id"}
_list_filters = (
"archived",
"visibility",
"order_by",
"sort",
"search",
"simple",
"starred",
"with_issues_enabled",
"with_merge_requests_enabled",
"min_access_level",
"with_custom_attributes",
)
| 44,876 | Python | .py | 1,089 | 31.935721 | 88 | 0.636309 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,101 | resource_groups.py | python-gitlab_python-gitlab/gitlab/v4/objects/resource_groups.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import ListMixin, RetrieveMixin, SaveMixin, UpdateMixin
from gitlab.types import RequiredOptional
__all__ = [
"ProjectResourceGroup",
"ProjectResourceGroupManager",
"ProjectResourceGroupUpcomingJob",
"ProjectResourceGroupUpcomingJobManager",
]
class ProjectResourceGroup(SaveMixin, RESTObject):
_id_attr = "key"
upcoming_jobs: "ProjectResourceGroupUpcomingJobManager"
class ProjectResourceGroupManager(RetrieveMixin, UpdateMixin, RESTManager):
_path = "/projects/{project_id}/resource_groups"
_obj_cls = ProjectResourceGroup
_from_parent_attrs = {"project_id": "id"}
_list_filters = (
"order_by",
"sort",
"include_html_description",
)
_update_attrs = RequiredOptional(optional=("process_mode",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectResourceGroup:
return cast(ProjectResourceGroup, super().get(id=id, lazy=lazy, **kwargs))
class ProjectResourceGroupUpcomingJob(RESTObject):
pass
class ProjectResourceGroupUpcomingJobManager(ListMixin, RESTManager):
_path = "/projects/{project_id}/resource_groups/{resource_group_key}/upcoming_jobs"
_obj_cls = ProjectResourceGroupUpcomingJob
_from_parent_attrs = {"project_id": "project_id", "resource_group_key": "key"}
| 1,427 | Python | .py | 33 | 38.484848 | 87 | 0.739508 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,102 | releases.py | python-gitlab_python-gitlab/gitlab/v4/objects/releases.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, ObjectDeleteMixin, SaveMixin
from gitlab.types import ArrayAttribute, RequiredOptional
__all__ = [
"ProjectRelease",
"ProjectReleaseManager",
"ProjectReleaseLink",
"ProjectReleaseLinkManager",
]
class ProjectRelease(SaveMixin, RESTObject):
_id_attr = "tag_name"
links: "ProjectReleaseLinkManager"
class ProjectReleaseManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/releases"
_obj_cls = ProjectRelease
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("tag_name",), optional=("name", "description", "ref", "assets")
)
_list_filters = (
"order_by",
"sort",
"include_html_description",
)
_update_attrs = RequiredOptional(
optional=("name", "description", "milestones", "released_at")
)
_types = {"milestones": ArrayAttribute}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectRelease:
return cast(ProjectRelease, super().get(id=id, lazy=lazy, **kwargs))
class ProjectReleaseLink(ObjectDeleteMixin, SaveMixin, RESTObject):
pass
class ProjectReleaseLinkManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/releases/{tag_name}/assets/links"
_obj_cls = ProjectReleaseLink
_from_parent_attrs = {"project_id": "project_id", "tag_name": "tag_name"}
_create_attrs = RequiredOptional(
required=("name", "url"),
optional=("filepath", "direct_asset_path", "link_type"),
)
_update_attrs = RequiredOptional(
optional=("name", "url", "filepath", "direct_asset_path", "link_type")
)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectReleaseLink:
return cast(ProjectReleaseLink, super().get(id=id, lazy=lazy, **kwargs))
| 1,972 | Python | .py | 50 | 34.02 | 81 | 0.674699 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,103 | applications.py | python-gitlab_python-gitlab/gitlab/v4/objects/applications.py | from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin, DeleteMixin, ListMixin, ObjectDeleteMixin
from gitlab.types import RequiredOptional
__all__ = [
"Application",
"ApplicationManager",
]
class Application(ObjectDeleteMixin, RESTObject):
_url = "/applications"
_repr_attr = "name"
class ApplicationManager(ListMixin, CreateMixin, DeleteMixin, RESTManager):
_path = "/applications"
_obj_cls = Application
_create_attrs = RequiredOptional(
required=("name", "redirect_uri", "scopes"), optional=("confidential",)
)
| 591 | Python | .py | 16 | 33.125 | 80 | 0.74386 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,104 | secure_files.py | python-gitlab_python-gitlab/gitlab/v4/objects/secure_files.py | """
GitLab API:
https://docs.gitlab.com/ee/api/secure_files.html
"""
from typing import Any, Callable, cast, Iterator, Optional, TYPE_CHECKING, Union
import requests
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import utils
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import NoUpdateMixin, ObjectDeleteMixin
from gitlab.types import FileAttribute, RequiredOptional
__all__ = ["ProjectSecureFile", "ProjectSecureFileManager"]
class ProjectSecureFile(ObjectDeleteMixin, RESTObject):
@cli.register_custom_action(cls_names="ProjectSecureFile")
@exc.on_http_error(exc.GitlabGetError)
def download(
self,
streamed: bool = False,
action: Optional[Callable[[bytes], None]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Download the secure file.
Args:
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the artifacts could not be retrieved
Returns:
The artifacts if `streamed` is False, None otherwise."""
path = f"{self.manager.path}/{self.id}/download"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
class ProjectSecureFileManager(NoUpdateMixin, RESTManager):
_path = "/projects/{project_id}/secure_files"
_obj_cls = ProjectSecureFile
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("name", "file"))
_types = {"file": FileAttribute}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectSecureFile:
return cast(ProjectSecureFile, super().get(id=id, lazy=lazy, **kwargs))
| 2,521 | Python | .py | 60 | 34.283333 | 80 | 0.665169 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,105 | appearance.py | python-gitlab_python-gitlab/gitlab/v4/objects/appearance.py | from typing import Any, cast, Dict, Optional, Union
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import GetWithoutIdMixin, SaveMixin, UpdateMixin
from gitlab.types import RequiredOptional
__all__ = [
"ApplicationAppearance",
"ApplicationAppearanceManager",
]
class ApplicationAppearance(SaveMixin, RESTObject):
_id_attr = None
class ApplicationAppearanceManager(GetWithoutIdMixin, UpdateMixin, RESTManager):
_path = "/application/appearance"
_obj_cls = ApplicationAppearance
_update_attrs = RequiredOptional(
optional=(
"title",
"description",
"logo",
"header_logo",
"favicon",
"new_project_guidelines",
"header_message",
"footer_message",
"message_background_color",
"message_font_color",
"email_header_and_footer_enabled",
),
)
@exc.on_http_error(exc.GitlabUpdateError)
def update(
self,
id: Optional[Union[str, int]] = None,
new_data: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
"""Update an object on the server.
Args:
id: ID of the object to update (can be None if not required)
new_data: the update data for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
The new object data (*not* a RESTObject)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request
"""
new_data = new_data or {}
data = new_data.copy()
return super().update(id, data, **kwargs)
def get(self, **kwargs: Any) -> ApplicationAppearance:
return cast(ApplicationAppearance, super().get(**kwargs))
| 1,932 | Python | .py | 52 | 28.865385 | 80 | 0.631889 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,106 | export_import.py | python-gitlab_python-gitlab/gitlab/v4/objects/export_import.py | from typing import Any, cast
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin, DownloadMixin, GetWithoutIdMixin, RefreshMixin
from gitlab.types import RequiredOptional
__all__ = [
"GroupExport",
"GroupExportManager",
"GroupImport",
"GroupImportManager",
"ProjectExport",
"ProjectExportManager",
"ProjectImport",
"ProjectImportManager",
]
class GroupExport(DownloadMixin, RESTObject):
_id_attr = None
class GroupExportManager(GetWithoutIdMixin, CreateMixin, RESTManager):
_path = "/groups/{group_id}/export"
_obj_cls = GroupExport
_from_parent_attrs = {"group_id": "id"}
def get(self, **kwargs: Any) -> GroupExport:
return cast(GroupExport, super().get(**kwargs))
class GroupImport(RESTObject):
_id_attr = None
class GroupImportManager(GetWithoutIdMixin, RESTManager):
_path = "/groups/{group_id}/import"
_obj_cls = GroupImport
_from_parent_attrs = {"group_id": "id"}
def get(self, **kwargs: Any) -> GroupImport:
return cast(GroupImport, super().get(**kwargs))
class ProjectExport(DownloadMixin, RefreshMixin, RESTObject):
_id_attr = None
class ProjectExportManager(GetWithoutIdMixin, CreateMixin, RESTManager):
_path = "/projects/{project_id}/export"
_obj_cls = ProjectExport
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(optional=("description",))
def get(self, **kwargs: Any) -> ProjectExport:
return cast(ProjectExport, super().get(**kwargs))
class ProjectImport(RefreshMixin, RESTObject):
_id_attr = None
class ProjectImportManager(GetWithoutIdMixin, RESTManager):
_path = "/projects/{project_id}/import"
_obj_cls = ProjectImport
_from_parent_attrs = {"project_id": "id"}
def get(self, **kwargs: Any) -> ProjectImport:
return cast(ProjectImport, super().get(**kwargs))
| 1,909 | Python | .py | 47 | 36 | 85 | 0.715761 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,107 | commits.py | python-gitlab_python-gitlab/gitlab/v4/objects/commits.py | from typing import Any, cast, Dict, List, Optional, TYPE_CHECKING, Union
import requests
import gitlab
from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin, ListMixin, RefreshMixin, RetrieveMixin
from gitlab.types import RequiredOptional
from .discussions import ProjectCommitDiscussionManager # noqa: F401
__all__ = [
"ProjectCommit",
"ProjectCommitManager",
"ProjectCommitComment",
"ProjectCommitCommentManager",
"ProjectCommitStatus",
"ProjectCommitStatusManager",
]
class ProjectCommit(RESTObject):
_repr_attr = "title"
comments: "ProjectCommitCommentManager"
discussions: ProjectCommitDiscussionManager
statuses: "ProjectCommitStatusManager"
@cli.register_custom_action(cls_names="ProjectCommit")
@exc.on_http_error(exc.GitlabGetError)
def diff(self, **kwargs: Any) -> Union[gitlab.GitlabList, List[Dict[str, Any]]]:
"""Generate the commit diff.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the diff could not be retrieved
Returns:
The changes done in this commit
"""
path = f"{self.manager.path}/{self.encoded_id}/diff"
return self.manager.gitlab.http_list(path, **kwargs)
@cli.register_custom_action(cls_names="ProjectCommit", required=("branch",))
@exc.on_http_error(exc.GitlabCherryPickError)
def cherry_pick(self, branch: str, **kwargs: Any) -> None:
"""Cherry-pick a commit into a branch.
Args:
branch: Name of target branch
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCherryPickError: If the cherry-pick could not be performed
"""
path = f"{self.manager.path}/{self.encoded_id}/cherry_pick"
post_data = {"branch": branch}
self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)
@cli.register_custom_action(cls_names="ProjectCommit", optional=("type",))
@exc.on_http_error(exc.GitlabGetError)
def refs(
self, type: str = "all", **kwargs: Any
) -> Union[gitlab.GitlabList, List[Dict[str, Any]]]:
"""List the references the commit is pushed to.
Args:
type: The scope of references ('branch', 'tag' or 'all')
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the references could not be retrieved
Returns:
The references the commit is pushed to.
"""
path = f"{self.manager.path}/{self.encoded_id}/refs"
query_data = {"type": type}
return self.manager.gitlab.http_list(path, query_data=query_data, **kwargs)
@cli.register_custom_action(cls_names="ProjectCommit")
@exc.on_http_error(exc.GitlabGetError)
def merge_requests(
self, **kwargs: Any
) -> Union[gitlab.GitlabList, List[Dict[str, Any]]]:
"""List the merge requests related to the commit.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the references could not be retrieved
Returns:
The merge requests related to the commit.
"""
path = f"{self.manager.path}/{self.encoded_id}/merge_requests"
return self.manager.gitlab.http_list(path, **kwargs)
@cli.register_custom_action(cls_names="ProjectCommit", required=("branch",))
@exc.on_http_error(exc.GitlabRevertError)
def revert(
self, branch: str, **kwargs: Any
) -> Union[Dict[str, Any], requests.Response]:
"""Revert a commit on a given branch.
Args:
branch: Name of target branch
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabRevertError: If the revert could not be performed
Returns:
The new commit data (*not* a RESTObject)
"""
path = f"{self.manager.path}/{self.encoded_id}/revert"
post_data = {"branch": branch}
return self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)
@cli.register_custom_action(cls_names="ProjectCommit")
@exc.on_http_error(exc.GitlabGetError)
def sequence(self, **kwargs: Any) -> Union[Dict[str, Any], requests.Response]:
"""Get the sequence number of the commit.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the sequence number could not be retrieved
Returns:
The commit's sequence number
"""
path = f"{self.manager.path}/{self.encoded_id}/sequence"
return self.manager.gitlab.http_get(path, **kwargs)
@cli.register_custom_action(cls_names="ProjectCommit")
@exc.on_http_error(exc.GitlabGetError)
def signature(self, **kwargs: Any) -> Union[Dict[str, Any], requests.Response]:
"""Get the signature of the commit.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the signature could not be retrieved
Returns:
The commit's signature data
"""
path = f"{self.manager.path}/{self.encoded_id}/signature"
return self.manager.gitlab.http_get(path, **kwargs)
class ProjectCommitManager(RetrieveMixin, CreateMixin, RESTManager):
_path = "/projects/{project_id}/repository/commits"
_obj_cls = ProjectCommit
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("branch", "commit_message", "actions"),
optional=("author_email", "author_name"),
)
_list_filters = (
"all",
"ref_name",
"since",
"until",
"path",
"with_stats",
"first_parent",
"order",
"trailers",
)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectCommit:
return cast(ProjectCommit, super().get(id=id, lazy=lazy, **kwargs))
class ProjectCommitComment(RESTObject):
_id_attr = None
_repr_attr = "note"
class ProjectCommitCommentManager(ListMixin, CreateMixin, RESTManager):
_path = "/projects/{project_id}/repository/commits/{commit_id}/comments"
_obj_cls = ProjectCommitComment
_from_parent_attrs = {"project_id": "project_id", "commit_id": "id"}
_create_attrs = RequiredOptional(
required=("note",), optional=("path", "line", "line_type")
)
class ProjectCommitStatus(RefreshMixin, RESTObject):
pass
class ProjectCommitStatusManager(ListMixin, CreateMixin, RESTManager):
_path = "/projects/{project_id}/repository/commits/{commit_id}/statuses"
_obj_cls = ProjectCommitStatus
_from_parent_attrs = {"project_id": "project_id", "commit_id": "id"}
_create_attrs = RequiredOptional(
required=("state",),
optional=("description", "name", "context", "ref", "target_url", "coverage"),
)
@exc.on_http_error(exc.GitlabCreateError)
def create(
self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> ProjectCommitStatus:
"""Create a new object.
Args:
data: Parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo or
'ref_name', 'stage', 'name', 'all')
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request
Returns:
A new instance of the manage object class build with
the data sent by the server
"""
# project_id and commit_id are in the data dict when using the CLI, but
# they are missing when using only the API
# See #511
base_path = "/projects/{project_id}/statuses/{commit_id}"
path: Optional[str]
if data is not None and "project_id" in data and "commit_id" in data:
path = base_path.format(**data)
else:
path = self._compute_path(base_path)
if TYPE_CHECKING:
assert path is not None
return cast(
ProjectCommitStatus, CreateMixin.create(self, data, path=path, **kwargs)
)
| 8,972 | Python | .py | 204 | 35.607843 | 85 | 0.646175 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,108 | deploy_keys.py | python-gitlab_python-gitlab/gitlab/v4/objects/deploy_keys.py | from typing import Any, cast, Dict, Union
import requests
from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, ListMixin, ObjectDeleteMixin, SaveMixin
from gitlab.types import RequiredOptional
__all__ = [
"DeployKey",
"DeployKeyManager",
"ProjectKey",
"ProjectKeyManager",
]
class DeployKey(RESTObject):
pass
class DeployKeyManager(ListMixin, RESTManager):
_path = "/deploy_keys"
_obj_cls = DeployKey
class ProjectKey(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectKeyManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/deploy_keys"
_obj_cls = ProjectKey
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("title", "key"), optional=("can_push",))
_update_attrs = RequiredOptional(optional=("title", "can_push"))
@cli.register_custom_action(
cls_names="ProjectKeyManager",
required=("key_id",),
requires_id=False,
help="Enable a deploy key for the project",
)
@exc.on_http_error(exc.GitlabProjectDeployKeyError)
def enable(
self, key_id: int, **kwargs: Any
) -> Union[Dict[str, Any], requests.Response]:
"""Enable a deploy key for a project.
Args:
key_id: The ID of the key to enable
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabProjectDeployKeyError: If the key could not be enabled
Returns:
A dict of the result.
"""
path = f"{self.path}/{key_id}/enable"
return self.gitlab.http_post(path, **kwargs)
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> ProjectKey:
return cast(ProjectKey, super().get(id=id, lazy=lazy, **kwargs))
| 1,947 | Python | .py | 50 | 32.82 | 88 | 0.676768 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,109 | keys.py | python-gitlab_python-gitlab/gitlab/v4/objects/keys.py | from typing import Any, cast, Optional, TYPE_CHECKING, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import GetMixin
__all__ = [
"Key",
"KeyManager",
]
class Key(RESTObject):
pass
class KeyManager(GetMixin, RESTManager):
_path = "/keys"
_obj_cls = Key
def get(
self, id: Optional[Union[int, str]] = None, lazy: bool = False, **kwargs: Any
) -> Key:
if id is not None:
return cast(Key, super().get(id, lazy=lazy, **kwargs))
if "fingerprint" not in kwargs:
raise AttributeError("Missing attribute: id or fingerprint")
if TYPE_CHECKING:
assert self.path is not None
server_data = self.gitlab.http_get(self.path, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
return self._obj_cls(self, server_data)
| 882 | Python | .py | 25 | 28.64 | 85 | 0.641509 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,110 | __init__.py | python-gitlab_python-gitlab/gitlab/v4/objects/__init__.py | from .access_requests import *
from .appearance import *
from .applications import *
from .artifacts import *
from .audit_events import *
from .award_emojis import *
from .badges import *
from .boards import *
from .branches import *
from .broadcast_messages import *
from .bulk_imports import *
from .ci_lint import *
from .cluster_agents import *
from .clusters import *
from .commits import *
from .container_registry import *
from .custom_attributes import *
from .deploy_keys import *
from .deploy_tokens import *
from .deployments import *
from .discussions import *
from .draft_notes import *
from .environments import *
from .epics import *
from .events import *
from .export_import import *
from .features import *
from .files import *
from .geo_nodes import *
from .group_access_tokens import *
from .groups import *
from .hooks import *
from .integrations import *
from .invitations import *
from .issues import *
from .iterations import *
from .job_token_scope import *
from .jobs import *
from .keys import *
from .labels import *
from .ldap import *
from .members import *
from .merge_request_approvals import *
from .merge_requests import *
from .merge_trains import *
from .milestones import *
from .namespaces import *
from .notes import *
from .notification_settings import *
from .package_protection_rules import *
from .packages import *
from .pages import *
from .personal_access_tokens import *
from .pipelines import *
from .project_access_tokens import *
from .projects import *
from .push_rules import *
from .registry_protection_rules import *
from .releases import *
from .repositories import *
from .resource_groups import *
from .reviewers import *
from .runners import *
from .secure_files import *
from .service_accounts import *
from .settings import *
from .sidekiq import *
from .snippets import *
from .statistics import *
from .tags import *
from .templates import *
from .todos import *
from .topics import *
from .triggers import *
from .users import *
from .variables import *
from .wikis import *
__all__ = [name for name in dir() if not name.startswith("_")]
| 2,101 | Python | .py | 78 | 25.923077 | 62 | 0.780415 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,111 | bulk_imports.py | python-gitlab_python-gitlab/gitlab/v4/objects/bulk_imports.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin, ListMixin, RefreshMixin, RetrieveMixin
from gitlab.types import RequiredOptional
__all__ = [
"BulkImport",
"BulkImportManager",
"BulkImportAllEntity",
"BulkImportAllEntityManager",
"BulkImportEntity",
"BulkImportEntityManager",
]
class BulkImport(RefreshMixin, RESTObject):
entities: "BulkImportEntityManager"
class BulkImportManager(CreateMixin, RetrieveMixin, RESTManager):
_path = "/bulk_imports"
_obj_cls = BulkImport
_create_attrs = RequiredOptional(required=("configuration", "entities"))
_list_filters = ("sort", "status")
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> BulkImport:
return cast(BulkImport, super().get(id=id, lazy=lazy, **kwargs))
class BulkImportEntity(RefreshMixin, RESTObject):
pass
class BulkImportEntityManager(RetrieveMixin, RESTManager):
_path = "/bulk_imports/{bulk_import_id}/entities"
_obj_cls = BulkImportEntity
_from_parent_attrs = {"bulk_import_id": "id"}
_list_filters = ("sort", "status")
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> BulkImportEntity:
return cast(BulkImportEntity, super().get(id=id, lazy=lazy, **kwargs))
class BulkImportAllEntity(RESTObject):
pass
class BulkImportAllEntityManager(ListMixin, RESTManager):
_path = "/bulk_imports/entities"
_obj_cls = BulkImportAllEntity
_list_filters = ("sort", "status")
| 1,573 | Python | .py | 38 | 36.921053 | 88 | 0.722844 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,112 | discussions.py | python-gitlab_python-gitlab/gitlab/v4/objects/discussions.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin, RetrieveMixin, SaveMixin, UpdateMixin
from gitlab.types import RequiredOptional
from .notes import ( # noqa: F401
ProjectCommitDiscussionNoteManager,
ProjectIssueDiscussionNoteManager,
ProjectMergeRequestDiscussionNoteManager,
ProjectSnippetDiscussionNoteManager,
)
__all__ = [
"ProjectCommitDiscussion",
"ProjectCommitDiscussionManager",
"ProjectIssueDiscussion",
"ProjectIssueDiscussionManager",
"ProjectMergeRequestDiscussion",
"ProjectMergeRequestDiscussionManager",
"ProjectSnippetDiscussion",
"ProjectSnippetDiscussionManager",
]
class ProjectCommitDiscussion(RESTObject):
notes: ProjectCommitDiscussionNoteManager
class ProjectCommitDiscussionManager(RetrieveMixin, CreateMixin, RESTManager):
_path = "/projects/{project_id}/repository/commits/{commit_id}/discussions"
_obj_cls = ProjectCommitDiscussion
_from_parent_attrs = {"project_id": "project_id", "commit_id": "id"}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectCommitDiscussion:
return cast(ProjectCommitDiscussion, super().get(id=id, lazy=lazy, **kwargs))
class ProjectIssueDiscussion(RESTObject):
notes: ProjectIssueDiscussionNoteManager
class ProjectIssueDiscussionManager(RetrieveMixin, CreateMixin, RESTManager):
_path = "/projects/{project_id}/issues/{issue_iid}/discussions"
_obj_cls = ProjectIssueDiscussion
_from_parent_attrs = {"project_id": "project_id", "issue_iid": "iid"}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueDiscussion:
return cast(ProjectIssueDiscussion, super().get(id=id, lazy=lazy, **kwargs))
class ProjectMergeRequestDiscussion(SaveMixin, RESTObject):
notes: ProjectMergeRequestDiscussionNoteManager
class ProjectMergeRequestDiscussionManager(
RetrieveMixin, CreateMixin, UpdateMixin, RESTManager
):
_path = "/projects/{project_id}/merge_requests/{mr_iid}/discussions"
_obj_cls = ProjectMergeRequestDiscussion
_from_parent_attrs = {"project_id": "project_id", "mr_iid": "iid"}
_create_attrs = RequiredOptional(
required=("body",), optional=("created_at", "position")
)
_update_attrs = RequiredOptional(required=("resolved",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMergeRequestDiscussion:
return cast(
ProjectMergeRequestDiscussion, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectSnippetDiscussion(RESTObject):
notes: ProjectSnippetDiscussionNoteManager
class ProjectSnippetDiscussionManager(RetrieveMixin, CreateMixin, RESTManager):
_path = "/projects/{project_id}/snippets/{snippet_id}/discussions"
_obj_cls = ProjectSnippetDiscussion
_from_parent_attrs = {"project_id": "project_id", "snippet_id": "id"}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectSnippetDiscussion:
return cast(ProjectSnippetDiscussion, super().get(id=id, lazy=lazy, **kwargs))
| 3,457 | Python | .py | 71 | 43.647887 | 86 | 0.737734 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,113 | events.py | python-gitlab_python-gitlab/gitlab/v4/objects/events.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import ListMixin, RetrieveMixin
__all__ = [
"Event",
"EventManager",
"GroupEpicResourceLabelEvent",
"GroupEpicResourceLabelEventManager",
"ProjectEvent",
"ProjectEventManager",
"ProjectIssueResourceLabelEvent",
"ProjectIssueResourceLabelEventManager",
"ProjectIssueResourceMilestoneEvent",
"ProjectIssueResourceMilestoneEventManager",
"ProjectIssueResourceStateEvent",
"ProjectIssueResourceIterationEventManager",
"ProjectIssueResourceWeightEventManager",
"ProjectIssueResourceIterationEvent",
"ProjectIssueResourceWeightEvent",
"ProjectIssueResourceStateEventManager",
"ProjectMergeRequestResourceLabelEvent",
"ProjectMergeRequestResourceLabelEventManager",
"ProjectMergeRequestResourceMilestoneEvent",
"ProjectMergeRequestResourceMilestoneEventManager",
"ProjectMergeRequestResourceStateEvent",
"ProjectMergeRequestResourceStateEventManager",
"UserEvent",
"UserEventManager",
]
class Event(RESTObject):
_id_attr = None
_repr_attr = "target_title"
class EventManager(ListMixin, RESTManager):
_path = "/events"
_obj_cls = Event
_list_filters = ("action", "target_type", "before", "after", "sort", "scope")
class GroupEpicResourceLabelEvent(RESTObject):
pass
class GroupEpicResourceLabelEventManager(RetrieveMixin, RESTManager):
_path = "/groups/{group_id}/epics/{epic_id}/resource_label_events"
_obj_cls = GroupEpicResourceLabelEvent
_from_parent_attrs = {"group_id": "group_id", "epic_id": "id"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupEpicResourceLabelEvent:
return cast(
GroupEpicResourceLabelEvent, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectEvent(Event):
pass
class ProjectEventManager(EventManager):
_path = "/projects/{project_id}/events"
_obj_cls = ProjectEvent
_from_parent_attrs = {"project_id": "id"}
class ProjectIssueResourceLabelEvent(RESTObject):
pass
class ProjectIssueResourceLabelEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/issues/{issue_iid}/resource_label_events"
_obj_cls = ProjectIssueResourceLabelEvent
_from_parent_attrs = {"project_id": "project_id", "issue_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueResourceLabelEvent:
return cast(
ProjectIssueResourceLabelEvent, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectIssueResourceMilestoneEvent(RESTObject):
pass
class ProjectIssueResourceMilestoneEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/issues/{issue_iid}/resource_milestone_events"
_obj_cls = ProjectIssueResourceMilestoneEvent
_from_parent_attrs = {"project_id": "project_id", "issue_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueResourceMilestoneEvent:
return cast(
ProjectIssueResourceMilestoneEvent, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectIssueResourceStateEvent(RESTObject):
pass
class ProjectIssueResourceStateEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/issues/{issue_iid}/resource_state_events"
_obj_cls = ProjectIssueResourceStateEvent
_from_parent_attrs = {"project_id": "project_id", "issue_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueResourceStateEvent:
return cast(
ProjectIssueResourceStateEvent, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectIssueResourceIterationEvent(RESTObject):
pass
class ProjectIssueResourceIterationEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/issues/{issue_iid}/resource_iteration_events"
_obj_cls = ProjectIssueResourceIterationEvent
_from_parent_attrs = {"project_id": "project_id", "issue_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueResourceIterationEvent:
return cast(
ProjectIssueResourceIterationEvent, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectIssueResourceWeightEvent(RESTObject):
pass
class ProjectIssueResourceWeightEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/issues/{issue_iid}/resource_weight_events"
_obj_cls = ProjectIssueResourceWeightEvent
_from_parent_attrs = {"project_id": "project_id", "issue_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueResourceWeightEvent:
return cast(
ProjectIssueResourceWeightEvent, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectMergeRequestResourceLabelEvent(RESTObject):
pass
class ProjectMergeRequestResourceLabelEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/merge_requests/{mr_iid}/resource_label_events"
_obj_cls = ProjectMergeRequestResourceLabelEvent
_from_parent_attrs = {"project_id": "project_id", "mr_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMergeRequestResourceLabelEvent:
return cast(
ProjectMergeRequestResourceLabelEvent,
super().get(id=id, lazy=lazy, **kwargs),
)
class ProjectMergeRequestResourceMilestoneEvent(RESTObject):
pass
class ProjectMergeRequestResourceMilestoneEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/merge_requests/{mr_iid}/resource_milestone_events"
_obj_cls = ProjectMergeRequestResourceMilestoneEvent
_from_parent_attrs = {"project_id": "project_id", "mr_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMergeRequestResourceMilestoneEvent:
return cast(
ProjectMergeRequestResourceMilestoneEvent,
super().get(id=id, lazy=lazy, **kwargs),
)
class ProjectMergeRequestResourceStateEvent(RESTObject):
pass
class ProjectMergeRequestResourceStateEventManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/merge_requests/{mr_iid}/resource_state_events"
_obj_cls = ProjectMergeRequestResourceStateEvent
_from_parent_attrs = {"project_id": "project_id", "mr_iid": "iid"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMergeRequestResourceStateEvent:
return cast(
ProjectMergeRequestResourceStateEvent,
super().get(id=id, lazy=lazy, **kwargs),
)
class UserEvent(Event):
pass
class UserEventManager(EventManager):
_path = "/users/{user_id}/events"
_obj_cls = UserEvent
_from_parent_attrs = {"user_id": "id"}
| 7,067 | Python | .py | 159 | 38.522013 | 87 | 0.718791 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,114 | container_registry.py | python-gitlab_python-gitlab/gitlab/v4/objects/container_registry.py | from typing import Any, cast, TYPE_CHECKING, Union
from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
DeleteMixin,
GetMixin,
ListMixin,
ObjectDeleteMixin,
RetrieveMixin,
)
__all__ = [
"GroupRegistryRepositoryManager",
"ProjectRegistryRepository",
"ProjectRegistryRepositoryManager",
"ProjectRegistryTag",
"ProjectRegistryTagManager",
"RegistryRepository",
"RegistryRepositoryManager",
]
class ProjectRegistryRepository(ObjectDeleteMixin, RESTObject):
tags: "ProjectRegistryTagManager"
class ProjectRegistryRepositoryManager(DeleteMixin, ListMixin, RESTManager):
_path = "/projects/{project_id}/registry/repositories"
_obj_cls = ProjectRegistryRepository
_from_parent_attrs = {"project_id": "id"}
class ProjectRegistryTag(ObjectDeleteMixin, RESTObject):
_id_attr = "name"
class ProjectRegistryTagManager(DeleteMixin, RetrieveMixin, RESTManager):
_obj_cls = ProjectRegistryTag
_from_parent_attrs = {"project_id": "project_id", "repository_id": "id"}
_path = "/projects/{project_id}/registry/repositories/{repository_id}/tags"
@cli.register_custom_action(
cls_names="ProjectRegistryTagManager",
required=("name_regex_delete",),
optional=("keep_n", "name_regex_keep", "older_than"),
)
@exc.on_http_error(exc.GitlabDeleteError)
def delete_in_bulk(self, name_regex_delete: str, **kwargs: Any) -> None:
"""Delete Tag in bulk
Args:
name_regex_delete: The regex of the name to delete. To delete all
tags specify .*.
keep_n: The amount of latest tags of given name to keep.
name_regex_keep: The regex of the name to keep. This value
overrides any matches from name_regex.
older_than: Tags to delete that are older than the given time,
written in human readable form 1h, 1d, 1month.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request
"""
valid_attrs = ["keep_n", "name_regex_keep", "older_than"]
data = {"name_regex_delete": name_regex_delete}
data.update({k: v for k, v in kwargs.items() if k in valid_attrs})
if TYPE_CHECKING:
assert self.path is not None
self.gitlab.http_delete(self.path, query_data=data, **kwargs)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectRegistryTag:
return cast(ProjectRegistryTag, super().get(id=id, lazy=lazy, **kwargs))
class GroupRegistryRepositoryManager(ListMixin, RESTManager):
_path = "/groups/{group_id}/registry/repositories"
_obj_cls = ProjectRegistryRepository
_from_parent_attrs = {"group_id": "id"}
class RegistryRepository(RESTObject):
_repr_attr = "path"
class RegistryRepositoryManager(GetMixin, RESTManager):
_path = "/registry/repositories"
_obj_cls = RegistryRepository
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> RegistryRepository:
return cast(RegistryRepository, super().get(id=id, lazy=lazy, **kwargs))
| 3,360 | Python | .py | 76 | 37.578947 | 80 | 0.689338 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,115 | topics.py | python-gitlab_python-gitlab/gitlab/v4/objects/topics.py | from typing import Any, cast, Dict, TYPE_CHECKING, Union
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import types
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, ObjectDeleteMixin, SaveMixin
from gitlab.types import RequiredOptional
__all__ = [
"Topic",
"TopicManager",
]
class Topic(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class TopicManager(CRUDMixin, RESTManager):
_path = "/topics"
_obj_cls = Topic
_create_attrs = RequiredOptional(
# NOTE: The `title` field was added and is required in GitLab 15.0 or
# newer. But not present before that.
required=("name",),
optional=("avatar", "description", "title"),
)
_update_attrs = RequiredOptional(optional=("avatar", "description", "name"))
_types = {"avatar": types.ImageAttribute}
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> Topic:
return cast(Topic, super().get(id=id, lazy=lazy, **kwargs))
@cli.register_custom_action(
cls_names="TopicManager",
required=("source_topic_id", "target_topic_id"),
)
@exc.on_http_error(exc.GitlabMRClosedError)
def merge(
self,
source_topic_id: Union[int, str],
target_topic_id: Union[int, str],
**kwargs: Any,
) -> Dict[str, Any]:
"""Merge two topics, assigning all projects to the target topic.
Args:
source_topic_id: ID of source project topic
target_topic_id: ID of target project topic
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTopicMergeError: If the merge failed
Returns:
The merged topic data (*not* a RESTObject)
"""
path = f"{self.path}/merge"
data = {
"source_topic_id": source_topic_id,
"target_topic_id": target_topic_id,
}
server_data = self.gitlab.http_post(path, post_data=data, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
return server_data
| 2,208 | Python | .py | 57 | 31.491228 | 83 | 0.644694 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,116 | branches.py | python-gitlab_python-gitlab/gitlab/v4/objects/branches.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CRUDMixin,
NoUpdateMixin,
ObjectDeleteMixin,
SaveMixin,
UpdateMethod,
)
from gitlab.types import RequiredOptional
__all__ = [
"ProjectBranch",
"ProjectBranchManager",
"ProjectProtectedBranch",
"ProjectProtectedBranchManager",
]
class ProjectBranch(ObjectDeleteMixin, RESTObject):
_id_attr = "name"
class ProjectBranchManager(NoUpdateMixin, RESTManager):
_path = "/projects/{project_id}/repository/branches"
_obj_cls = ProjectBranch
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("branch", "ref"))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectBranch:
return cast(ProjectBranch, super().get(id=id, lazy=lazy, **kwargs))
class ProjectProtectedBranch(SaveMixin, ObjectDeleteMixin, RESTObject):
_id_attr = "name"
class ProjectProtectedBranchManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/protected_branches"
_obj_cls = ProjectProtectedBranch
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("name",),
optional=(
"push_access_level",
"merge_access_level",
"unprotect_access_level",
"allow_force_push",
"allowed_to_push",
"allowed_to_merge",
"allowed_to_unprotect",
"code_owner_approval_required",
),
)
_update_method = UpdateMethod.PATCH
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectProtectedBranch:
return cast(ProjectProtectedBranch, super().get(id=id, lazy=lazy, **kwargs))
| 1,814 | Python | .py | 51 | 29.392157 | 84 | 0.667619 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,117 | snippets.py | python-gitlab_python-gitlab/gitlab/v4/objects/snippets.py | from typing import Any, Callable, cast, Iterator, List, Optional, TYPE_CHECKING, Union
import requests
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import utils
from gitlab.base import RESTManager, RESTObject, RESTObjectList
from gitlab.mixins import CRUDMixin, ObjectDeleteMixin, SaveMixin, UserAgentDetailMixin
from gitlab.types import RequiredOptional
from .award_emojis import ProjectSnippetAwardEmojiManager # noqa: F401
from .discussions import ProjectSnippetDiscussionManager # noqa: F401
from .notes import ProjectSnippetNoteManager # noqa: F401
__all__ = [
"Snippet",
"SnippetManager",
"ProjectSnippet",
"ProjectSnippetManager",
]
class Snippet(UserAgentDetailMixin, SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "title"
@cli.register_custom_action(cls_names="Snippet")
@exc.on_http_error(exc.GitlabGetError)
def content(
self,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Return the content of a snippet.
Args:
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment.
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the content could not be retrieved
Returns:
The snippet content
"""
path = f"/snippets/{self.encoded_id}/raw"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
class SnippetManager(CRUDMixin, RESTManager):
_path = "/snippets"
_obj_cls = Snippet
_create_attrs = RequiredOptional(
required=("title",),
exclusive=("files", "file_name"),
optional=(
"description",
"content",
"visibility",
),
)
_update_attrs = RequiredOptional(
optional=(
"title",
"files",
"file_name",
"content",
"visibility",
"description",
),
)
@cli.register_custom_action(cls_names="SnippetManager")
def list_public(self, **kwargs: Any) -> Union[RESTObjectList, List[RESTObject]]:
"""List all public snippets.
Args:
get_all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
iterator: If set to True and no pagination option is
defined, return a generator instead of a list
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabListError: If the list could not be retrieved
Returns:
The list of snippets, or a generator if `iterator` is True
"""
return self.list(path="/snippets/public", **kwargs)
@cli.register_custom_action(cls_names="SnippetManager")
def list_all(self, **kwargs: Any) -> Union[RESTObjectList, List[RESTObject]]:
"""List all snippets.
Args:
get_all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
iterator: If set to True and no pagination option is
defined, return a generator instead of a list
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabListError: If the list could not be retrieved
Returns:
A generator for the snippets list
"""
return self.list(path="/snippets/all", **kwargs)
def public(self, **kwargs: Any) -> Union[RESTObjectList, List[RESTObject]]:
"""List all public snippets.
Args:
get_all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
iterator: If set to True and no pagination option is
defined, return a generator instead of a list
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabListError: If the list could not be retrieved
Returns:
The list of snippets, or a generator if `iterator` is True
"""
utils.warn(
message=(
"Gitlab.snippets.public() is deprecated and will be removed in a"
"future major version. Use Gitlab.snippets.list_public() instead."
),
category=DeprecationWarning,
)
return self.list(path="/snippets/public", **kwargs)
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> Snippet:
return cast(Snippet, super().get(id=id, lazy=lazy, **kwargs))
class ProjectSnippet(UserAgentDetailMixin, SaveMixin, ObjectDeleteMixin, RESTObject):
_url = "/projects/{project_id}/snippets"
_repr_attr = "title"
awardemojis: ProjectSnippetAwardEmojiManager
discussions: ProjectSnippetDiscussionManager
notes: ProjectSnippetNoteManager
@cli.register_custom_action(cls_names="ProjectSnippet")
@exc.on_http_error(exc.GitlabGetError)
def content(
self,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Return the content of a snippet.
Args:
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment.
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the content could not be retrieved
Returns:
The snippet content
"""
path = f"{self.manager.path}/{self.encoded_id}/raw"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
class ProjectSnippetManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/snippets"
_obj_cls = ProjectSnippet
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("title", "visibility"),
exclusive=("files", "file_name"),
optional=(
"description",
"content",
),
)
_update_attrs = RequiredOptional(
optional=(
"title",
"files",
"file_name",
"content",
"visibility",
"description",
),
)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectSnippet:
return cast(ProjectSnippet, super().get(id=id, lazy=lazy, **kwargs))
| 8,176 | Python | .py | 203 | 30.788177 | 87 | 0.617536 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,118 | iterations.py | python-gitlab_python-gitlab/gitlab/v4/objects/iterations.py | from gitlab import types
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import ListMixin
__all__ = [
"ProjectIterationManager",
"GroupIteration",
"GroupIterationManager",
]
class GroupIteration(RESTObject):
_repr_attr = "title"
class GroupIterationManager(ListMixin, RESTManager):
_path = "/groups/{group_id}/iterations"
_obj_cls = GroupIteration
_from_parent_attrs = {"group_id": "id"}
# When using the API, the "in" keyword collides with python's "in" keyword
# raising a SyntaxError.
# For this reason, we have to use the query_parameters argument:
# group.iterations.list(query_parameters={"in": "title"})
_list_filters = (
"include_ancestors",
"include_descendants",
"in",
"search",
"state",
"updated_after",
"updated_before",
)
_types = {"in": types.ArrayAttribute}
class ProjectIterationManager(ListMixin, RESTManager):
_path = "/projects/{project_id}/iterations"
_obj_cls = GroupIteration
_from_parent_attrs = {"project_id": "id"}
# When using the API, the "in" keyword collides with python's "in" keyword
# raising a SyntaxError.
# For this reason, we have to use the query_parameters argument:
# project.iterations.list(query_parameters={"in": "title"})
_list_filters = (
"include_ancestors",
"include_descendants",
"in",
"search",
"state",
"updated_after",
"updated_before",
)
_types = {"in": types.ArrayAttribute}
| 1,561 | Python | .py | 46 | 28.26087 | 78 | 0.655172 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,119 | groups.py | python-gitlab_python-gitlab/gitlab/v4/objects/groups.py | from typing import Any, BinaryIO, cast, Dict, List, Optional, Type, TYPE_CHECKING, Union
import requests
import gitlab
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import types
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
CRUDMixin,
DeleteMixin,
ListMixin,
NoUpdateMixin,
ObjectDeleteMixin,
SaveMixin,
)
from gitlab.types import RequiredOptional
from .access_requests import GroupAccessRequestManager # noqa: F401
from .audit_events import GroupAuditEventManager # noqa: F401
from .badges import GroupBadgeManager # noqa: F401
from .boards import GroupBoardManager # noqa: F401
from .clusters import GroupClusterManager # noqa: F401
from .container_registry import GroupRegistryRepositoryManager # noqa: F401
from .custom_attributes import GroupCustomAttributeManager # noqa: F401
from .deploy_tokens import GroupDeployTokenManager # noqa: F401
from .epics import GroupEpicManager # noqa: F401
from .export_import import GroupExportManager, GroupImportManager # noqa: F401
from .group_access_tokens import GroupAccessTokenManager # noqa: F401
from .hooks import GroupHookManager # noqa: F401
from .invitations import GroupInvitationManager # noqa: F401
from .issues import GroupIssueManager # noqa: F401
from .iterations import GroupIterationManager # noqa: F401
from .labels import GroupLabelManager # noqa: F401
from .members import ( # noqa: F401
GroupBillableMemberManager,
GroupMemberAllManager,
GroupMemberManager,
)
from .merge_requests import GroupMergeRequestManager # noqa: F401
from .milestones import GroupMilestoneManager # noqa: F401
from .notification_settings import GroupNotificationSettingsManager # noqa: F401
from .packages import GroupPackageManager # noqa: F401
from .projects import GroupProjectManager, SharedProjectManager # noqa: F401
from .push_rules import GroupPushRulesManager
from .runners import GroupRunnerManager # noqa: F401
from .service_accounts import GroupServiceAccountManager # noqa: F401
from .statistics import GroupIssuesStatisticsManager # noqa: F401
from .variables import GroupVariableManager # noqa: F401
from .wikis import GroupWikiManager # noqa: F401
__all__ = [
"Group",
"GroupManager",
"GroupDescendantGroup",
"GroupDescendantGroupManager",
"GroupLDAPGroupLink",
"GroupLDAPGroupLinkManager",
"GroupSubgroup",
"GroupSubgroupManager",
"GroupSAMLGroupLink",
"GroupSAMLGroupLinkManager",
]
class Group(SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "name"
access_tokens: GroupAccessTokenManager
accessrequests: GroupAccessRequestManager
audit_events: GroupAuditEventManager
badges: GroupBadgeManager
billable_members: GroupBillableMemberManager
boards: GroupBoardManager
clusters: GroupClusterManager
customattributes: GroupCustomAttributeManager
deploytokens: GroupDeployTokenManager
descendant_groups: "GroupDescendantGroupManager"
epics: GroupEpicManager
exports: GroupExportManager
hooks: GroupHookManager
imports: GroupImportManager
invitations: GroupInvitationManager
issues: GroupIssueManager
issues_statistics: GroupIssuesStatisticsManager
iterations: GroupIterationManager
labels: GroupLabelManager
ldap_group_links: "GroupLDAPGroupLinkManager"
members: GroupMemberManager
members_all: GroupMemberAllManager
mergerequests: GroupMergeRequestManager
milestones: GroupMilestoneManager
notificationsettings: GroupNotificationSettingsManager
packages: GroupPackageManager
projects: GroupProjectManager
shared_projects: SharedProjectManager
pushrules: GroupPushRulesManager
registry_repositories: GroupRegistryRepositoryManager
runners: GroupRunnerManager
subgroups: "GroupSubgroupManager"
variables: GroupVariableManager
wikis: GroupWikiManager
saml_group_links: "GroupSAMLGroupLinkManager"
service_accounts: "GroupServiceAccountManager"
@cli.register_custom_action(cls_names="Group", required=("project_id",))
@exc.on_http_error(exc.GitlabTransferProjectError)
def transfer_project(self, project_id: int, **kwargs: Any) -> None:
"""Transfer a project to this group.
Args:
to_project_id: ID of the project to transfer
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTransferProjectError: If the project could not be transferred
"""
path = f"/groups/{self.encoded_id}/projects/{project_id}"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(cls_names="Group", required=(), optional=("group_id",))
@exc.on_http_error(exc.GitlabGroupTransferError)
def transfer(self, group_id: Optional[int] = None, **kwargs: Any) -> None:
"""Transfer the group to a new parent group or make it a top-level group.
Requires GitLab ≥14.6.
Args:
group_id: ID of the new parent group. When not specified,
the group to transfer is instead turned into a top-level group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGroupTransferError: If the group could not be transferred
"""
path = f"/groups/{self.encoded_id}/transfer"
post_data = {}
if group_id is not None:
post_data["group_id"] = group_id
self.manager.gitlab.http_post(path, post_data=post_data, **kwargs)
@cli.register_custom_action(cls_names="Group", required=("scope", "search"))
@exc.on_http_error(exc.GitlabSearchError)
def search(
self, scope: str, search: str, **kwargs: Any
) -> Union[gitlab.GitlabList, List[Dict[str, Any]]]:
"""Search the group resources matching the provided string.
Args:
scope: Scope of the search
search: Search string
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabSearchError: If the server failed to perform the request
Returns:
A list of dicts describing the resources found.
"""
data = {"scope": scope, "search": search}
path = f"/groups/{self.encoded_id}/search"
return self.manager.gitlab.http_list(path, query_data=data, **kwargs)
@cli.register_custom_action(cls_names="Group")
@exc.on_http_error(exc.GitlabCreateError)
def ldap_sync(self, **kwargs: Any) -> None:
"""Sync LDAP groups.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request
"""
path = f"/groups/{self.encoded_id}/ldap_sync"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(
cls_names="Group",
required=("group_id", "group_access"),
optional=("expires_at",),
)
@exc.on_http_error(exc.GitlabCreateError)
def share(
self,
group_id: int,
group_access: int,
expires_at: Optional[str] = None,
**kwargs: Any,
) -> None:
"""Share the group with a group.
Args:
group_id: ID of the group.
group_access: Access level for the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request
Returns:
Group
"""
path = f"/groups/{self.encoded_id}/share"
data = {
"group_id": group_id,
"group_access": group_access,
"expires_at": expires_at,
}
server_data = self.manager.gitlab.http_post(path, post_data=data, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
self._update_attrs(server_data)
@cli.register_custom_action(cls_names="Group", required=("group_id",))
@exc.on_http_error(exc.GitlabDeleteError)
def unshare(self, group_id: int, **kwargs: Any) -> None:
"""Delete a shared group link within a group.
Args:
group_id: ID of the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request
"""
path = f"/groups/{self.encoded_id}/share/{group_id}"
self.manager.gitlab.http_delete(path, **kwargs)
@cli.register_custom_action(cls_names="Group")
@exc.on_http_error(exc.GitlabRestoreError)
def restore(self, **kwargs: Any) -> None:
"""Restore a group marked for deletion..
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabRestoreError: If the server failed to perform the request
"""
path = f"/groups/{self.encoded_id}/restore"
self.manager.gitlab.http_post(path, **kwargs)
class GroupManager(CRUDMixin, RESTManager):
_path = "/groups"
_obj_cls = Group
_list_filters = (
"skip_groups",
"all_available",
"search",
"order_by",
"sort",
"statistics",
"owned",
"with_custom_attributes",
"min_access_level",
"top_level_only",
)
_create_attrs = RequiredOptional(
required=("name", "path"),
optional=(
"description",
"membership_lock",
"visibility",
"share_with_group_lock",
"require_two_factor_authentication",
"two_factor_grace_period",
"project_creation_level",
"auto_devops_enabled",
"subgroup_creation_level",
"emails_disabled",
"avatar",
"mentions_disabled",
"lfs_enabled",
"request_access_enabled",
"parent_id",
"default_branch_protection",
"shared_runners_minutes_limit",
"extra_shared_runners_minutes_limit",
),
)
_update_attrs = RequiredOptional(
optional=(
"name",
"path",
"description",
"membership_lock",
"share_with_group_lock",
"visibility",
"require_two_factor_authentication",
"two_factor_grace_period",
"project_creation_level",
"auto_devops_enabled",
"subgroup_creation_level",
"emails_disabled",
"avatar",
"mentions_disabled",
"lfs_enabled",
"request_access_enabled",
"default_branch_protection",
"file_template_project_id",
"shared_runners_minutes_limit",
"extra_shared_runners_minutes_limit",
"prevent_forking_outside_group",
"shared_runners_setting",
),
)
_types = {"avatar": types.ImageAttribute, "skip_groups": types.ArrayAttribute}
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> Group:
return cast(Group, super().get(id=id, lazy=lazy, **kwargs))
@exc.on_http_error(exc.GitlabImportError)
def import_group(
self,
file: BinaryIO,
path: str,
name: str,
parent_id: Optional[Union[int, str]] = None,
**kwargs: Any,
) -> Union[Dict[str, Any], requests.Response]:
"""Import a group from an archive file.
Args:
file: Data or file object containing the group
path: The path for the new group to be imported.
name: The name for the new group.
parent_id: ID of a parent group that the group will
be imported into.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabImportError: If the server failed to perform the request
Returns:
A representation of the import status.
"""
files = {"file": ("file.tar.gz", file, "application/octet-stream")}
data: Dict[str, Any] = {"path": path, "name": name}
if parent_id is not None:
data["parent_id"] = parent_id
return self.gitlab.http_post(
"/groups/import", post_data=data, files=files, **kwargs
)
class GroupSubgroup(RESTObject):
pass
class GroupSubgroupManager(ListMixin, RESTManager):
_path = "/groups/{group_id}/subgroups"
_obj_cls: Union[Type["GroupDescendantGroup"], Type[GroupSubgroup]] = GroupSubgroup
_from_parent_attrs = {"group_id": "id"}
_list_filters = (
"skip_groups",
"all_available",
"search",
"order_by",
"sort",
"statistics",
"owned",
"with_custom_attributes",
"min_access_level",
)
_types = {"skip_groups": types.ArrayAttribute}
class GroupDescendantGroup(RESTObject):
pass
class GroupDescendantGroupManager(GroupSubgroupManager):
"""
This manager inherits from GroupSubgroupManager as descendant groups
share all attributes with subgroups, except the path and object class.
"""
_path = "/groups/{group_id}/descendant_groups"
_obj_cls: Type[GroupDescendantGroup] = GroupDescendantGroup
class GroupLDAPGroupLink(RESTObject):
_repr_attr = "provider"
def _get_link_attrs(self) -> Dict[str, str]:
# https://docs.gitlab.com/ee/api/groups.html#add-ldap-group-link-with-cn-or-filter
# https://docs.gitlab.com/ee/api/groups.html#delete-ldap-group-link-with-cn-or-filter
# We can tell what attribute to use based on the data returned
data = {"provider": self.provider}
if self.cn:
data["cn"] = self.cn
else:
data["filter"] = self.filter
return data
def delete(self, **kwargs: Any) -> None:
"""Delete the LDAP group link from the server.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request
"""
if TYPE_CHECKING:
assert isinstance(self.manager, DeleteMixin)
self.manager.delete(
self.encoded_id, query_data=self._get_link_attrs(), **kwargs
)
class GroupLDAPGroupLinkManager(ListMixin, CreateMixin, DeleteMixin, RESTManager):
_path = "/groups/{group_id}/ldap_group_links"
_obj_cls: Type[GroupLDAPGroupLink] = GroupLDAPGroupLink
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(
required=("provider", "group_access"), exclusive=("cn", "filter")
)
class GroupSAMLGroupLink(ObjectDeleteMixin, RESTObject):
_id_attr = "name"
_repr_attr = "name"
class GroupSAMLGroupLinkManager(NoUpdateMixin, RESTManager):
_path = "/groups/{group_id}/saml_group_links"
_obj_cls: Type[GroupSAMLGroupLink] = GroupSAMLGroupLink
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(required=("saml_group_name", "access_level"))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupSAMLGroupLink:
return cast(GroupSAMLGroupLink, super().get(id=id, lazy=lazy, **kwargs))
| 15,958 | Python | .py | 388 | 33.309278 | 93 | 0.662819 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,120 | packages.py | python-gitlab_python-gitlab/gitlab/v4/objects/packages.py | """
GitLab API:
https://docs.gitlab.com/ee/api/packages.html
https://docs.gitlab.com/ee/user/packages/generic_packages/
"""
from pathlib import Path
from typing import (
Any,
BinaryIO,
Callable,
cast,
Iterator,
Optional,
TYPE_CHECKING,
Union,
)
import requests
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import utils
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import DeleteMixin, GetMixin, ListMixin, ObjectDeleteMixin
__all__ = [
"GenericPackage",
"GenericPackageManager",
"GroupPackage",
"GroupPackageManager",
"ProjectPackage",
"ProjectPackageManager",
"ProjectPackageFile",
"ProjectPackageFileManager",
"ProjectPackagePipeline",
"ProjectPackagePipelineManager",
]
class GenericPackage(RESTObject):
_id_attr = "package_name"
class GenericPackageManager(RESTManager):
_path = "/projects/{project_id}/packages/generic"
_obj_cls = GenericPackage
_from_parent_attrs = {"project_id": "id"}
@cli.register_custom_action(
cls_names="GenericPackageManager",
required=("package_name", "package_version", "file_name", "path"),
)
@exc.on_http_error(exc.GitlabUploadError)
def upload(
self,
package_name: str,
package_version: str,
file_name: str,
path: Optional[Union[str, Path]] = None,
select: Optional[str] = None,
data: Optional[Union[bytes, BinaryIO]] = None,
**kwargs: Any,
) -> GenericPackage:
"""Upload a file as a generic package.
Args:
package_name: The package name. Must follow generic package
name regex rules
package_version: The package version. Must follow semantic
version regex rules
file_name: The name of the file as uploaded in the registry
path: The path to a local file to upload
select: GitLab API accepts a value of 'package_file'
Raises:
GitlabConnectionError: If the server cannot be reached
GitlabUploadError: If the file upload fails
GitlabUploadError: If ``path`` cannot be read
GitlabUploadError: If both ``path`` and ``data`` are passed
Returns:
An object storing the metadata of the uploaded package.
https://docs.gitlab.com/ee/user/packages/generic_packages/
"""
if path is None and data is None:
raise exc.GitlabUploadError("No file contents or path specified")
if path is not None and data is not None:
raise exc.GitlabUploadError("File contents and file path specified")
file_data: Optional[Union[bytes, BinaryIO]] = data
if not file_data:
if TYPE_CHECKING:
assert path is not None
try:
with open(path, "rb") as f:
file_data = f.read()
except OSError as e:
raise exc.GitlabUploadError(
f"Failed to read package file {path}"
) from e
url = f"{self._computed_path}/{package_name}/{package_version}/{file_name}"
query_data = {} if select is None else {"select": select}
server_data = self.gitlab.http_put(
url, query_data=query_data, post_data=file_data, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
attrs = {
"package_name": package_name,
"package_version": package_version,
"file_name": file_name,
"path": path,
}
attrs.update(server_data)
return self._obj_cls(self, attrs=attrs)
@cli.register_custom_action(
cls_names="GenericPackageManager",
required=("package_name", "package_version", "file_name"),
)
@exc.on_http_error(exc.GitlabGetError)
def download(
self,
package_name: str,
package_version: str,
file_name: str,
streamed: bool = False,
action: Optional[Callable[[bytes], None]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Download a generic package.
Args:
package_name: The package name.
package_version: The package version.
file_name: The name of the file in the registry
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
The package content if streamed is False, None otherwise
"""
path = f"{self._computed_path}/{package_name}/{package_version}/{file_name}"
result = self.gitlab.http_get(path, streamed=streamed, raw=True, **kwargs)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
class GroupPackage(RESTObject):
pass
class GroupPackageManager(ListMixin, RESTManager):
_path = "/groups/{group_id}/packages"
_obj_cls = GroupPackage
_from_parent_attrs = {"group_id": "id"}
_list_filters = (
"exclude_subgroups",
"order_by",
"sort",
"package_type",
"package_name",
)
class ProjectPackage(ObjectDeleteMixin, RESTObject):
package_files: "ProjectPackageFileManager"
pipelines: "ProjectPackagePipelineManager"
class ProjectPackageManager(ListMixin, GetMixin, DeleteMixin, RESTManager):
_path = "/projects/{project_id}/packages"
_obj_cls = ProjectPackage
_from_parent_attrs = {"project_id": "id"}
_list_filters = (
"order_by",
"sort",
"package_type",
"package_name",
)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectPackage:
return cast(ProjectPackage, super().get(id=id, lazy=lazy, **kwargs))
class ProjectPackageFile(ObjectDeleteMixin, RESTObject):
pass
class ProjectPackageFileManager(DeleteMixin, ListMixin, RESTManager):
_path = "/projects/{project_id}/packages/{package_id}/package_files"
_obj_cls = ProjectPackageFile
_from_parent_attrs = {"project_id": "project_id", "package_id": "id"}
class ProjectPackagePipeline(RESTObject):
pass
class ProjectPackagePipelineManager(ListMixin, RESTManager):
_path = "/projects/{project_id}/packages/{package_id}/pipelines"
_obj_cls = ProjectPackagePipeline
_from_parent_attrs = {"project_id": "project_id", "package_id": "id"}
| 7,225 | Python | .py | 189 | 29.835979 | 84 | 0.63331 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,121 | hooks.py | python-gitlab_python-gitlab/gitlab/v4/objects/hooks.py | from typing import Any, cast, Union
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, NoUpdateMixin, ObjectDeleteMixin, SaveMixin
from gitlab.types import RequiredOptional
__all__ = [
"Hook",
"HookManager",
"ProjectHook",
"ProjectHookManager",
"GroupHook",
"GroupHookManager",
]
class Hook(ObjectDeleteMixin, RESTObject):
_url = "/hooks"
_repr_attr = "url"
class HookManager(NoUpdateMixin, RESTManager):
_path = "/hooks"
_obj_cls = Hook
_create_attrs = RequiredOptional(required=("url",))
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> Hook:
return cast(Hook, super().get(id=id, lazy=lazy, **kwargs))
class ProjectHook(SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "url"
@exc.on_http_error(exc.GitlabHookTestError)
def test(self, trigger: str) -> None:
"""
Test a Project Hook
Args:
trigger: Type of trigger event to test
Raises:
GitlabHookTestError: If the hook test attempt failed
"""
path = f"{self.manager.path}/{self.encoded_id}/test/{trigger}"
self.manager.gitlab.http_post(path)
class ProjectHookManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/hooks"
_obj_cls = ProjectHook
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("url",),
optional=(
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"job_events",
"pipeline_events",
"wiki_page_events",
"enable_ssl_verification",
"token",
),
)
_update_attrs = RequiredOptional(
required=("url",),
optional=(
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"job_events",
"pipeline_events",
"wiki_events",
"enable_ssl_verification",
"token",
),
)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectHook:
return cast(ProjectHook, super().get(id=id, lazy=lazy, **kwargs))
class GroupHook(SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "url"
@exc.on_http_error(exc.GitlabHookTestError)
def test(self, trigger: str) -> None:
"""
Test a Group Hook
Args:
trigger: Type of trigger event to test
Raises:
GitlabHookTestError: If the hook test attempt failed
"""
path = f"{self.manager.path}/{self.encoded_id}/test/{trigger}"
self.manager.gitlab.http_post(path)
class GroupHookManager(CRUDMixin, RESTManager):
_path = "/groups/{group_id}/hooks"
_obj_cls = GroupHook
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(
required=("url",),
optional=(
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"confidential_note_events",
"job_events",
"pipeline_events",
"wiki_page_events",
"deployment_events",
"releases_events",
"subgroup_events",
"enable_ssl_verification",
"token",
),
)
_update_attrs = RequiredOptional(
required=("url",),
optional=(
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"confidential_note_events",
"job_events",
"pipeline_events",
"wiki_page_events",
"deployment_events",
"releases_events",
"subgroup_events",
"enable_ssl_verification",
"token",
),
)
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> GroupHook:
return cast(GroupHook, super().get(id=id, lazy=lazy, **kwargs))
| 4,445 | Python | .py | 134 | 24.149254 | 87 | 0.570429 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,122 | integrations.py | python-gitlab_python-gitlab/gitlab/v4/objects/integrations.py | """
GitLab API:
https://docs.gitlab.com/ee/api/integrations.html
"""
from typing import Any, cast, List, Union
from gitlab import cli
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
DeleteMixin,
GetMixin,
ListMixin,
ObjectDeleteMixin,
SaveMixin,
UpdateMixin,
)
__all__ = [
"ProjectIntegration",
"ProjectIntegrationManager",
"ProjectService",
"ProjectServiceManager",
]
class ProjectIntegration(SaveMixin, ObjectDeleteMixin, RESTObject):
_id_attr = "slug"
class ProjectIntegrationManager(
GetMixin, UpdateMixin, DeleteMixin, ListMixin, RESTManager
):
_path = "/projects/{project_id}/integrations"
_from_parent_attrs = {"project_id": "id"}
_obj_cls = ProjectIntegration
_service_attrs = {
"asana": (("api_key",), ("restrict_to_branch", "push_events")),
"assembla": (("token",), ("subdomain", "push_events")),
"bamboo": (
("bamboo_url", "build_key", "username", "password"),
("push_events",),
),
"bugzilla": (
("new_issue_url", "issues_url", "project_url"),
("description", "title", "push_events"),
),
"buildkite": (
("token", "project_url"),
("enable_ssl_verification", "push_events"),
),
"campfire": (("token",), ("subdomain", "room", "push_events")),
"circuit": (
("webhook",),
(
"notify_only_broken_pipelines",
"branches_to_be_notified",
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"confidential_note_events",
"pipeline_events",
"wiki_page_events",
),
),
"custom-issue-tracker": (
("new_issue_url", "issues_url", "project_url"),
("description", "title", "push_events"),
),
"drone-ci": (
("token", "drone_url"),
(
"enable_ssl_verification",
"push_events",
"merge_requests_events",
"tag_push_events",
),
),
"emails-on-push": (
("recipients",),
(
"disable_diffs",
"send_from_committer_email",
"push_events",
"tag_push_events",
"branches_to_be_notified",
),
),
"pipelines-email": (
("recipients",),
(
"add_pusher",
"notify_only_broken_builds",
"branches_to_be_notified",
"notify_only_default_branch",
"pipeline_events",
),
),
"external-wiki": (("external_wiki_url",), ()),
"flowdock": (("token",), ("push_events",)),
"github": (("token", "repository_url"), ("static_context",)),
"hangouts-chat": (
("webhook",),
(
"notify_only_broken_pipelines",
"notify_only_default_branch",
"branches_to_be_notified",
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"confidential_note_events",
"pipeline_events",
"wiki_page_events",
),
),
"hipchat": (
("token",),
(
"color",
"notify",
"room",
"api_version",
"server",
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"confidential_note_events",
"pipeline_events",
),
),
"irker": (
("recipients",),
(
"default_irc_uri",
"server_port",
"server_host",
"colorize_messages",
"push_events",
),
),
"jira": (
(
"url",
"username",
"password",
),
(
"api_url",
"active",
"jira_issue_transition_id",
"commit_events",
"merge_requests_events",
"comment_on_event_enabled",
),
),
"slack-slash-commands": (("token",), ()),
"mattermost-slash-commands": (("token",), ("username",)),
"packagist": (
("username", "token"),
("server", "push_events", "merge_requests_events", "tag_push_events"),
),
"mattermost": (
("webhook",),
(
"username",
"channel",
"notify_only_broken_pipelines",
"notify_only_default_branch",
"branches_to_be_notified",
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"confidential_note_events",
"pipeline_events",
"wiki_page_events",
"push_channel",
"issue_channel",
"confidential_issue_channel",
"merge_request_channel",
"note_channel",
"confidential_note_channel",
"tag_push_channel",
"pipeline_channel",
"wiki_page_channel",
),
),
"pivotaltracker": (("token",), ("restrict_to_branch", "push_events")),
"prometheus": (("api_url",), ()),
"pushover": (
("api_key", "user_key", "priority"),
("device", "sound", "push_events"),
),
"redmine": (
("new_issue_url", "project_url", "issues_url"),
("description", "push_events"),
),
"slack": (
("webhook",),
(
"username",
"channel",
"notify_only_broken_pipelines",
"notify_only_default_branch",
"branches_to_be_notified",
"commit_events",
"confidential_issue_channel",
"confidential_issues_events",
"confidential_note_channel",
"confidential_note_events",
"deployment_channel",
"deployment_events",
"issue_channel",
"issues_events",
"job_events",
"merge_request_channel",
"merge_requests_events",
"note_channel",
"note_events",
"pipeline_channel",
"pipeline_events",
"push_channel",
"push_events",
"tag_push_channel",
"tag_push_events",
"wiki_page_channel",
"wiki_page_events",
),
),
"microsoft-teams": (
("webhook",),
(
"notify_only_broken_pipelines",
"notify_only_default_branch",
"branches_to_be_notified",
"push_events",
"issues_events",
"confidential_issues_events",
"merge_requests_events",
"tag_push_events",
"note_events",
"confidential_note_events",
"pipeline_events",
"wiki_page_events",
),
),
"teamcity": (
("teamcity_url", "build_type", "username", "password"),
("push_events",),
),
"jenkins": (("jenkins_url", "project_name"), ("username", "password")),
"mock-ci": (("mock_service_url",), ()),
"youtrack": (("issues_url", "project_url"), ("description", "push_events")),
}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIntegration:
return cast(ProjectIntegration, super().get(id=id, lazy=lazy, **kwargs))
@cli.register_custom_action(
cls_names=("ProjectIntegrationManager", "ProjectServiceManager")
)
def available(self) -> List[str]:
"""List the services known by python-gitlab.
Returns:
The list of service code names.
"""
return list(self._service_attrs.keys())
class ProjectService(ProjectIntegration):
pass
class ProjectServiceManager(ProjectIntegrationManager):
_obj_cls = ProjectService
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectService:
return cast(ProjectService, super().get(id=id, lazy=lazy, **kwargs))
| 9,229 | Python | .py | 279 | 20.508961 | 84 | 0.45769 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,123 | custom_attributes.py | python-gitlab_python-gitlab/gitlab/v4/objects/custom_attributes.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import DeleteMixin, ObjectDeleteMixin, RetrieveMixin, SetMixin
__all__ = [
"GroupCustomAttribute",
"GroupCustomAttributeManager",
"ProjectCustomAttribute",
"ProjectCustomAttributeManager",
"UserCustomAttribute",
"UserCustomAttributeManager",
]
class GroupCustomAttribute(ObjectDeleteMixin, RESTObject):
_id_attr = "key"
class GroupCustomAttributeManager(RetrieveMixin, SetMixin, DeleteMixin, RESTManager):
_path = "/groups/{group_id}/custom_attributes"
_obj_cls = GroupCustomAttribute
_from_parent_attrs = {"group_id": "id"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupCustomAttribute:
return cast(GroupCustomAttribute, super().get(id=id, lazy=lazy, **kwargs))
class ProjectCustomAttribute(ObjectDeleteMixin, RESTObject):
_id_attr = "key"
class ProjectCustomAttributeManager(RetrieveMixin, SetMixin, DeleteMixin, RESTManager):
_path = "/projects/{project_id}/custom_attributes"
_obj_cls = ProjectCustomAttribute
_from_parent_attrs = {"project_id": "id"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectCustomAttribute:
return cast(ProjectCustomAttribute, super().get(id=id, lazy=lazy, **kwargs))
class UserCustomAttribute(ObjectDeleteMixin, RESTObject):
_id_attr = "key"
class UserCustomAttributeManager(RetrieveMixin, SetMixin, DeleteMixin, RESTManager):
_path = "/users/{user_id}/custom_attributes"
_obj_cls = UserCustomAttribute
_from_parent_attrs = {"user_id": "id"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> UserCustomAttribute:
return cast(UserCustomAttribute, super().get(id=id, lazy=lazy, **kwargs))
| 1,875 | Python | .py | 41 | 40.804878 | 87 | 0.72317 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,124 | personal_access_tokens.py | python-gitlab_python-gitlab/gitlab/v4/objects/personal_access_tokens.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
DeleteMixin,
ObjectDeleteMixin,
ObjectRotateMixin,
RetrieveMixin,
RotateMixin,
)
from gitlab.types import ArrayAttribute, RequiredOptional
__all__ = [
"PersonalAccessToken",
"PersonalAccessTokenManager",
"UserPersonalAccessToken",
"UserPersonalAccessTokenManager",
]
class PersonalAccessToken(ObjectDeleteMixin, ObjectRotateMixin, RESTObject):
pass
class PersonalAccessTokenManager(DeleteMixin, RetrieveMixin, RotateMixin, RESTManager):
_path = "/personal_access_tokens"
_obj_cls = PersonalAccessToken
_list_filters = ("user_id",)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> PersonalAccessToken:
return cast(PersonalAccessToken, super().get(id=id, lazy=lazy, **kwargs))
class UserPersonalAccessToken(RESTObject):
pass
class UserPersonalAccessTokenManager(CreateMixin, RESTManager):
_path = "/users/{user_id}/personal_access_tokens"
_obj_cls = UserPersonalAccessToken
_from_parent_attrs = {"user_id": "id"}
_create_attrs = RequiredOptional(
required=("name", "scopes"), optional=("expires_at",)
)
_types = {"scopes": ArrayAttribute}
| 1,315 | Python | .py | 37 | 31.108108 | 87 | 0.734017 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,125 | clusters.py | python-gitlab_python-gitlab/gitlab/v4/objects/clusters.py | from typing import Any, cast, Dict, Optional, Union
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin, CRUDMixin, ObjectDeleteMixin, SaveMixin
from gitlab.types import RequiredOptional
__all__ = [
"GroupCluster",
"GroupClusterManager",
"ProjectCluster",
"ProjectClusterManager",
]
class GroupCluster(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class GroupClusterManager(CRUDMixin, RESTManager):
_path = "/groups/{group_id}/clusters"
_obj_cls = GroupCluster
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(
required=("name", "platform_kubernetes_attributes"),
optional=("domain", "enabled", "managed", "environment_scope"),
)
_update_attrs = RequiredOptional(
optional=(
"name",
"domain",
"management_project_id",
"platform_kubernetes_attributes",
"environment_scope",
),
)
@exc.on_http_error(exc.GitlabStopError)
def create(
self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> GroupCluster:
"""Create a new object.
Args:
data: Parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo or
'ref_name', 'stage', 'name', 'all')
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request
Returns:
A new instance of the manage object class build with
the data sent by the server
"""
path = f"{self.path}/user"
return cast(GroupCluster, CreateMixin.create(self, data, path=path, **kwargs))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupCluster:
return cast(GroupCluster, super().get(id=id, lazy=lazy, **kwargs))
class ProjectCluster(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectClusterManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/clusters"
_obj_cls = ProjectCluster
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("name", "platform_kubernetes_attributes"),
optional=("domain", "enabled", "managed", "environment_scope"),
)
_update_attrs = RequiredOptional(
optional=(
"name",
"domain",
"management_project_id",
"platform_kubernetes_attributes",
"environment_scope",
),
)
@exc.on_http_error(exc.GitlabStopError)
def create(
self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> ProjectCluster:
"""Create a new object.
Args:
data: Parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo or
'ref_name', 'stage', 'name', 'all')
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request
Returns:
A new instance of the manage object class build with
the data sent by the server
"""
path = f"{self.path}/user"
return cast(ProjectCluster, CreateMixin.create(self, data, path=path, **kwargs))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectCluster:
return cast(ProjectCluster, super().get(id=id, lazy=lazy, **kwargs))
| 3,750 | Python | .py | 95 | 30.789474 | 88 | 0.621183 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,126 | registry_protection_rules.py | python-gitlab_python-gitlab/gitlab/v4/objects/registry_protection_rules.py | from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin, ListMixin, SaveMixin, UpdateMethod, UpdateMixin
from gitlab.types import RequiredOptional
__all__ = [
"ProjectRegistryProtectionRule",
"ProjectRegistryProtectionRuleManager",
]
class ProjectRegistryProtectionRule(SaveMixin, RESTObject):
_repr_attr = "repository_path_pattern"
class ProjectRegistryProtectionRuleManager(
ListMixin, CreateMixin, UpdateMixin, RESTManager
):
_path = "/projects/{project_id}/registry/protection/rules"
_obj_cls = ProjectRegistryProtectionRule
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("repository_path_pattern",),
optional=(
"minimum_access_level_for_push",
"minimum_access_level_for_delete",
),
)
_update_attrs = RequiredOptional(
optional=(
"repository_path_pattern",
"minimum_access_level_for_push",
"minimum_access_level_for_delete",
),
)
_update_method = UpdateMethod.PATCH
| 1,092 | Python | .py | 30 | 30.3 | 86 | 0.702933 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,127 | notes.py | python-gitlab_python-gitlab/gitlab/v4/objects/notes.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
CRUDMixin,
DeleteMixin,
GetMixin,
ObjectDeleteMixin,
RetrieveMixin,
SaveMixin,
UpdateMixin,
)
from gitlab.types import RequiredOptional
from .award_emojis import ( # noqa: F401
GroupEpicNoteAwardEmojiManager,
ProjectIssueNoteAwardEmojiManager,
ProjectMergeRequestNoteAwardEmojiManager,
ProjectSnippetNoteAwardEmojiManager,
)
__all__ = [
"GroupEpicNote",
"GroupEpicNoteManager",
"GroupEpicDiscussionNote",
"GroupEpicDiscussionNoteManager",
"ProjectNote",
"ProjectNoteManager",
"ProjectCommitDiscussionNote",
"ProjectCommitDiscussionNoteManager",
"ProjectIssueNote",
"ProjectIssueNoteManager",
"ProjectIssueDiscussionNote",
"ProjectIssueDiscussionNoteManager",
"ProjectMergeRequestNote",
"ProjectMergeRequestNoteManager",
"ProjectMergeRequestDiscussionNote",
"ProjectMergeRequestDiscussionNoteManager",
"ProjectSnippetNote",
"ProjectSnippetNoteManager",
"ProjectSnippetDiscussionNote",
"ProjectSnippetDiscussionNoteManager",
]
class GroupEpicNote(SaveMixin, ObjectDeleteMixin, RESTObject):
awardemojis: GroupEpicNoteAwardEmojiManager
class GroupEpicNoteManager(CRUDMixin, RESTManager):
_path = "/groups/{group_id}/epics/{epic_id}/notes"
_obj_cls = GroupEpicNote
_from_parent_attrs = {"group_id": "group_id", "epic_id": "id"}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupEpicNote:
return cast(GroupEpicNote, super().get(id=id, lazy=lazy, **kwargs))
class GroupEpicDiscussionNote(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class GroupEpicDiscussionNoteManager(
GetMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = "/groups/{group_id}/epics/{epic_id}/discussions/{discussion_id}/notes"
_obj_cls = GroupEpicDiscussionNote
_from_parent_attrs = {
"group_id": "group_id",
"epic_id": "epic_id",
"discussion_id": "id",
}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupEpicDiscussionNote:
return cast(GroupEpicDiscussionNote, super().get(id=id, lazy=lazy, **kwargs))
class ProjectNote(RESTObject):
pass
class ProjectNoteManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/notes"
_obj_cls = ProjectNote
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectNote:
return cast(ProjectNote, super().get(id=id, lazy=lazy, **kwargs))
class ProjectCommitDiscussionNote(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectCommitDiscussionNoteManager(
GetMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = (
"/projects/{project_id}/repository/commits/{commit_id}/"
"discussions/{discussion_id}/notes"
)
_obj_cls = ProjectCommitDiscussionNote
_from_parent_attrs = {
"project_id": "project_id",
"commit_id": "commit_id",
"discussion_id": "id",
}
_create_attrs = RequiredOptional(
required=("body",), optional=("created_at", "position")
)
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectCommitDiscussionNote:
return cast(
ProjectCommitDiscussionNote, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectIssueNote(SaveMixin, ObjectDeleteMixin, RESTObject):
awardemojis: ProjectIssueNoteAwardEmojiManager
class ProjectIssueNoteManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/issues/{issue_iid}/notes"
_obj_cls = ProjectIssueNote
_from_parent_attrs = {"project_id": "project_id", "issue_iid": "iid"}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueNote:
return cast(ProjectIssueNote, super().get(id=id, lazy=lazy, **kwargs))
class ProjectIssueDiscussionNote(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectIssueDiscussionNoteManager(
GetMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = (
"/projects/{project_id}/issues/{issue_iid}/discussions/{discussion_id}/notes"
)
_obj_cls = ProjectIssueDiscussionNote
_from_parent_attrs = {
"project_id": "project_id",
"issue_iid": "issue_iid",
"discussion_id": "id",
}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectIssueDiscussionNote:
return cast(ProjectIssueDiscussionNote, super().get(id=id, lazy=lazy, **kwargs))
class ProjectMergeRequestNote(SaveMixin, ObjectDeleteMixin, RESTObject):
awardemojis: ProjectMergeRequestNoteAwardEmojiManager
class ProjectMergeRequestNoteManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/merge_requests/{mr_iid}/notes"
_obj_cls = ProjectMergeRequestNote
_from_parent_attrs = {"project_id": "project_id", "mr_iid": "iid"}
_create_attrs = RequiredOptional(required=("body",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMergeRequestNote:
return cast(ProjectMergeRequestNote, super().get(id=id, lazy=lazy, **kwargs))
class ProjectMergeRequestDiscussionNote(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectMergeRequestDiscussionNoteManager(
GetMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = (
"/projects/{project_id}/merge_requests/{mr_iid}/"
"discussions/{discussion_id}/notes"
)
_obj_cls = ProjectMergeRequestDiscussionNote
_from_parent_attrs = {
"project_id": "project_id",
"mr_iid": "mr_iid",
"discussion_id": "id",
}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMergeRequestDiscussionNote:
return cast(
ProjectMergeRequestDiscussionNote, super().get(id=id, lazy=lazy, **kwargs)
)
class ProjectSnippetNote(SaveMixin, ObjectDeleteMixin, RESTObject):
awardemojis: ProjectSnippetNoteAwardEmojiManager
class ProjectSnippetNoteManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/snippets/{snippet_id}/notes"
_obj_cls = ProjectSnippetNote
_from_parent_attrs = {"project_id": "project_id", "snippet_id": "id"}
_create_attrs = RequiredOptional(required=("body",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectSnippetNote:
return cast(ProjectSnippetNote, super().get(id=id, lazy=lazy, **kwargs))
class ProjectSnippetDiscussionNote(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectSnippetDiscussionNoteManager(
GetMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = (
"/projects/{project_id}/snippets/{snippet_id}/"
"discussions/{discussion_id}/notes"
)
_obj_cls = ProjectSnippetDiscussionNote
_from_parent_attrs = {
"project_id": "project_id",
"snippet_id": "snippet_id",
"discussion_id": "id",
}
_create_attrs = RequiredOptional(required=("body",), optional=("created_at",))
_update_attrs = RequiredOptional(required=("body",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectSnippetDiscussionNote:
return cast(
ProjectSnippetDiscussionNote, super().get(id=id, lazy=lazy, **kwargs)
)
| 8,588 | Python | .py | 209 | 35.492823 | 88 | 0.696853 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,128 | environments.py | python-gitlab_python-gitlab/gitlab/v4/objects/environments.py | from typing import Any, cast, Dict, Union
import requests
from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
DeleteMixin,
ObjectDeleteMixin,
RetrieveMixin,
SaveMixin,
UpdateMixin,
)
from gitlab.types import ArrayAttribute, RequiredOptional
__all__ = [
"ProjectEnvironment",
"ProjectEnvironmentManager",
"ProjectProtectedEnvironment",
"ProjectProtectedEnvironmentManager",
]
class ProjectEnvironment(SaveMixin, ObjectDeleteMixin, RESTObject):
@cli.register_custom_action(cls_names="ProjectEnvironment")
@exc.on_http_error(exc.GitlabStopError)
def stop(self, **kwargs: Any) -> Union[Dict[str, Any], requests.Response]:
"""Stop the environment.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabStopError: If the operation failed
Returns:
A dict of the result.
"""
path = f"{self.manager.path}/{self.encoded_id}/stop"
return self.manager.gitlab.http_post(path, **kwargs)
class ProjectEnvironmentManager(
RetrieveMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = "/projects/{project_id}/environments"
_obj_cls = ProjectEnvironment
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("name",), optional=("external_url",))
_update_attrs = RequiredOptional(optional=("name", "external_url"))
_list_filters = ("name", "search", "states")
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectEnvironment:
return cast(ProjectEnvironment, super().get(id=id, lazy=lazy, **kwargs))
class ProjectProtectedEnvironment(ObjectDeleteMixin, RESTObject):
_id_attr = "name"
_repr_attr = "name"
class ProjectProtectedEnvironmentManager(
RetrieveMixin, CreateMixin, DeleteMixin, RESTManager
):
_path = "/projects/{project_id}/protected_environments"
_obj_cls = ProjectProtectedEnvironment
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=(
"name",
"deploy_access_levels",
),
optional=("required_approval_count", "approval_rules"),
)
_types = {"deploy_access_levels": ArrayAttribute, "approval_rules": ArrayAttribute}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectProtectedEnvironment:
return cast(
ProjectProtectedEnvironment, super().get(id=id, lazy=lazy, **kwargs)
)
| 2,736 | Python | .py | 71 | 32.591549 | 87 | 0.688939 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,129 | todos.py | python-gitlab_python-gitlab/gitlab/v4/objects/todos.py | from typing import Any, Dict, TYPE_CHECKING
from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import DeleteMixin, ListMixin, ObjectDeleteMixin
__all__ = [
"Todo",
"TodoManager",
]
class Todo(ObjectDeleteMixin, RESTObject):
@cli.register_custom_action(cls_names="Todo")
@exc.on_http_error(exc.GitlabTodoError)
def mark_as_done(self, **kwargs: Any) -> Dict[str, Any]:
"""Mark the todo as done.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the server failed to perform the request
Returns:
A dict with the result
"""
path = f"{self.manager.path}/{self.encoded_id}/mark_as_done"
server_data = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
self._update_attrs(server_data)
return server_data
class TodoManager(ListMixin, DeleteMixin, RESTManager):
_path = "/todos"
_obj_cls = Todo
_list_filters = ("action", "author_id", "project_id", "state", "type")
@cli.register_custom_action(cls_names="TodoManager")
@exc.on_http_error(exc.GitlabTodoError)
def mark_all_as_done(self, **kwargs: Any) -> None:
"""Mark all the todos as done.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the server failed to perform the request
Returns:
The number of todos marked done
"""
self.gitlab.http_post("/todos/mark_as_done", **kwargs)
| 1,846 | Python | .py | 45 | 33.511111 | 74 | 0.657718 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,130 | repositories.py | python-gitlab_python-gitlab/gitlab/v4/objects/repositories.py | """
GitLab API: https://docs.gitlab.com/ee/api/repositories.html
Currently this module only contains repository-related methods for projects.
"""
from typing import Any, Callable, Dict, Iterator, List, Optional, TYPE_CHECKING, Union
import requests
import gitlab
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import types, utils
if TYPE_CHECKING:
# When running mypy we use these as the base classes
_RestObjectBase = gitlab.base.RESTObject
else:
_RestObjectBase = object
class RepositoryMixin(_RestObjectBase):
@cli.register_custom_action(
cls_names="Project", required=("submodule", "branch", "commit_sha")
)
@exc.on_http_error(exc.GitlabUpdateError)
def update_submodule(
self, submodule: str, branch: str, commit_sha: str, **kwargs: Any
) -> Union[Dict[str, Any], requests.Response]:
"""Update a project submodule
Args:
submodule: Full path to the submodule
branch: Name of the branch to commit into
commit_sha: Full commit SHA to update the submodule to
commit_message: Commit message. If no message is provided, a
default one will be set (optional)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabPutError: If the submodule could not be updated
"""
submodule = utils.EncodedId(submodule)
path = f"/projects/{self.encoded_id}/repository/submodules/{submodule}"
data = {"branch": branch, "commit_sha": commit_sha}
if "commit_message" in kwargs:
data["commit_message"] = kwargs["commit_message"]
return self.manager.gitlab.http_put(path, post_data=data)
@cli.register_custom_action(
cls_names="Project", optional=("path", "ref", "recursive")
)
@exc.on_http_error(exc.GitlabGetError)
def repository_tree(
self, path: str = "", ref: str = "", recursive: bool = False, **kwargs: Any
) -> Union[gitlab.client.GitlabList, List[Dict[str, Any]]]:
"""Return a list of files in the repository.
Args:
path: Path of the top folder (/ by default)
ref: Reference to a commit or branch
recursive: Whether to get the tree recursively
all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
iterator: If set to True and no pagination option is
defined, return a generator instead of a list
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
The representation of the tree
"""
gl_path = f"/projects/{self.encoded_id}/repository/tree"
query_data: Dict[str, Any] = {"recursive": recursive}
if path:
query_data["path"] = path
if ref:
query_data["ref"] = ref
return self.manager.gitlab.http_list(gl_path, query_data=query_data, **kwargs)
@cli.register_custom_action(cls_names="Project", required=("sha",))
@exc.on_http_error(exc.GitlabGetError)
def repository_blob(
self, sha: str, **kwargs: Any
) -> Union[Dict[str, Any], requests.Response]:
"""Return a file by blob SHA.
Args:
sha: ID of the blob
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
The blob content and metadata
"""
path = f"/projects/{self.encoded_id}/repository/blobs/{sha}"
return self.manager.gitlab.http_get(path, **kwargs)
@cli.register_custom_action(cls_names="Project", required=("sha",))
@exc.on_http_error(exc.GitlabGetError)
def repository_raw_blob(
self,
sha: str,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Return the raw file contents for a blob.
Args:
sha: ID of the blob
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
The blob content if streamed is False, None otherwise
"""
path = f"/projects/{self.encoded_id}/repository/blobs/{sha}/raw"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
@cli.register_custom_action(cls_names="Project", required=("from_", "to"))
@exc.on_http_error(exc.GitlabGetError)
def repository_compare(
self, from_: str, to: str, **kwargs: Any
) -> Union[Dict[str, Any], requests.Response]:
"""Return a diff between two branches/commits.
Args:
from_: Source branch/SHA
to: Destination branch/SHA
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
The diff
"""
path = f"/projects/{self.encoded_id}/repository/compare"
query_data = {"from": from_, "to": to}
return self.manager.gitlab.http_get(path, query_data=query_data, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabGetError)
def repository_contributors(
self, **kwargs: Any
) -> Union[gitlab.client.GitlabList, List[Dict[str, Any]]]:
"""Return a list of contributors for the project.
Args:
all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
iterator: If set to True and no pagination option is
defined, return a generator instead of a list
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
The contributors
"""
path = f"/projects/{self.encoded_id}/repository/contributors"
return self.manager.gitlab.http_list(path, **kwargs)
@cli.register_custom_action(cls_names="Project", optional=("sha", "format"))
@exc.on_http_error(exc.GitlabListError)
def repository_archive(
self,
sha: Optional[str] = None,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
format: Optional[str] = None,
path: Optional[str] = None,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Return an archive of the repository.
Args:
sha: ID of the commit (default branch by default)
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
format: file format (tar.gz by default)
path: The subpath of the repository to download (all files by default)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the server failed to perform the request
Returns:
The binary data of the archive
"""
url_path = f"/projects/{self.encoded_id}/repository/archive"
if format:
url_path += "." + format
query_data = {}
if sha:
query_data["sha"] = sha
if path is not None:
query_data["path"] = path
result = self.manager.gitlab.http_get(
url_path, query_data=query_data, raw=True, streamed=streamed, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
@cli.register_custom_action(cls_names="Project", required=("refs",))
@exc.on_http_error(exc.GitlabGetError)
def repository_merge_base(
self, refs: List[str], **kwargs: Any
) -> Union[Dict[str, Any], requests.Response]:
"""Return a diff between two branches/commits.
Args:
refs: The refs to find the common ancestor of. Multiple refs can be passed.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
The common ancestor commit (*not* a RESTObject)
"""
path = f"/projects/{self.encoded_id}/repository/merge_base"
query_data, _ = utils._transform_types(
data={"refs": refs},
custom_types={"refs": types.ArrayAttribute},
transform_data=True,
)
return self.manager.gitlab.http_get(path, query_data=query_data, **kwargs)
@cli.register_custom_action(cls_names="Project")
@exc.on_http_error(exc.GitlabDeleteError)
def delete_merged_branches(self, **kwargs: Any) -> None:
"""Delete merged branches.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request
"""
path = f"/projects/{self.encoded_id}/repository/merged_branches"
self.manager.gitlab.http_delete(path, **kwargs)
| 11,221 | Python | .py | 251 | 34.98008 | 87 | 0.625824 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,131 | pages.py | python-gitlab_python-gitlab/gitlab/v4/objects/pages.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CRUDMixin,
DeleteMixin,
GetWithoutIdMixin,
ListMixin,
ObjectDeleteMixin,
RefreshMixin,
SaveMixin,
UpdateMethod,
UpdateMixin,
)
from gitlab.types import RequiredOptional
__all__ = [
"PagesDomain",
"PagesDomainManager",
"ProjectPagesDomain",
"ProjectPagesDomainManager",
"ProjectPages",
"ProjectPagesManager",
]
class PagesDomain(RESTObject):
_id_attr = "domain"
class PagesDomainManager(ListMixin, RESTManager):
_path = "/pages/domains"
_obj_cls = PagesDomain
class ProjectPagesDomain(SaveMixin, ObjectDeleteMixin, RESTObject):
_id_attr = "domain"
class ProjectPagesDomainManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/pages/domains"
_obj_cls = ProjectPagesDomain
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("domain",), optional=("certificate", "key")
)
_update_attrs = RequiredOptional(optional=("certificate", "key"))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectPagesDomain:
return cast(ProjectPagesDomain, super().get(id=id, lazy=lazy, **kwargs))
class ProjectPages(ObjectDeleteMixin, RefreshMixin, RESTObject):
_id_attr = None
class ProjectPagesManager(DeleteMixin, UpdateMixin, GetWithoutIdMixin, RESTManager):
_path = "/projects/{project_id}/pages"
_obj_cls = ProjectPages
_from_parent_attrs = {"project_id": "id"}
_update_attrs = RequiredOptional(
optional=("pages_unique_domain_enabled", "pages_https_only")
)
_update_method: UpdateMethod = UpdateMethod.PATCH
def get(self, **kwargs: Any) -> ProjectPages:
return cast(ProjectPages, super().get(**kwargs))
| 1,868 | Python | .py | 53 | 30.54717 | 84 | 0.710951 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,132 | reviewers.py | python-gitlab_python-gitlab/gitlab/v4/objects/reviewers.py | from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import ListMixin
__all__ = [
"ProjectMergeRequestReviewerDetail",
"ProjectMergeRequestReviewerDetailManager",
]
class ProjectMergeRequestReviewerDetail(RESTObject):
pass
class ProjectMergeRequestReviewerDetailManager(ListMixin, RESTManager):
_path = "/projects/{project_id}/merge_requests/{mr_iid}/reviewers"
_obj_cls = ProjectMergeRequestReviewerDetail
_from_parent_attrs = {"project_id": "project_id", "mr_iid": "iid"}
| 517 | Python | .py | 12 | 39.666667 | 71 | 0.786 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,133 | milestones.py | python-gitlab_python-gitlab/gitlab/v4/objects/milestones.py | from typing import Any, cast, TYPE_CHECKING, Union
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import types
from gitlab.base import RESTManager, RESTObject, RESTObjectList
from gitlab.mixins import (
CRUDMixin,
ObjectDeleteMixin,
PromoteMixin,
SaveMixin,
UpdateMethod,
)
from gitlab.types import RequiredOptional
from .issues import GroupIssue, GroupIssueManager, ProjectIssue, ProjectIssueManager
from .merge_requests import (
GroupMergeRequest,
ProjectMergeRequest,
ProjectMergeRequestManager,
)
__all__ = [
"GroupMilestone",
"GroupMilestoneManager",
"ProjectMilestone",
"ProjectMilestoneManager",
]
class GroupMilestone(SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "title"
@cli.register_custom_action(cls_names="GroupMilestone")
@exc.on_http_error(exc.GitlabListError)
def issues(self, **kwargs: Any) -> RESTObjectList:
"""List issues related to this milestone.
Args:
all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
The list of issues
"""
path = f"{self.manager.path}/{self.encoded_id}/issues"
data_list = self.manager.gitlab.http_list(path, iterator=True, **kwargs)
if TYPE_CHECKING:
assert isinstance(data_list, RESTObjectList)
manager = GroupIssueManager(self.manager.gitlab, parent=self.manager._parent)
# FIXME(gpocentek): the computed manager path is not correct
return RESTObjectList(manager, GroupIssue, data_list)
@cli.register_custom_action(cls_names="GroupMilestone")
@exc.on_http_error(exc.GitlabListError)
def merge_requests(self, **kwargs: Any) -> RESTObjectList:
"""List the merge requests related to this milestone.
Args:
all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
The list of merge requests
"""
path = f"{self.manager.path}/{self.encoded_id}/merge_requests"
data_list = self.manager.gitlab.http_list(path, iterator=True, **kwargs)
if TYPE_CHECKING:
assert isinstance(data_list, RESTObjectList)
manager = GroupIssueManager(self.manager.gitlab, parent=self.manager._parent)
# FIXME(gpocentek): the computed manager path is not correct
return RESTObjectList(manager, GroupMergeRequest, data_list)
class GroupMilestoneManager(CRUDMixin, RESTManager):
_path = "/groups/{group_id}/milestones"
_obj_cls = GroupMilestone
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(
required=("title",), optional=("description", "due_date", "start_date")
)
_update_attrs = RequiredOptional(
optional=("title", "description", "due_date", "start_date", "state_event"),
)
_list_filters = ("iids", "state", "search")
_types = {"iids": types.ArrayAttribute}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupMilestone:
return cast(GroupMilestone, super().get(id=id, lazy=lazy, **kwargs))
class ProjectMilestone(PromoteMixin, SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "title"
_update_method = UpdateMethod.POST
@cli.register_custom_action(cls_names="ProjectMilestone")
@exc.on_http_error(exc.GitlabListError)
def issues(self, **kwargs: Any) -> RESTObjectList:
"""List issues related to this milestone.
Args:
all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
The list of issues
"""
path = f"{self.manager.path}/{self.encoded_id}/issues"
data_list = self.manager.gitlab.http_list(path, iterator=True, **kwargs)
if TYPE_CHECKING:
assert isinstance(data_list, RESTObjectList)
manager = ProjectIssueManager(self.manager.gitlab, parent=self.manager._parent)
# FIXME(gpocentek): the computed manager path is not correct
return RESTObjectList(manager, ProjectIssue, data_list)
@cli.register_custom_action(cls_names="ProjectMilestone")
@exc.on_http_error(exc.GitlabListError)
def merge_requests(self, **kwargs: Any) -> RESTObjectList:
"""List the merge requests related to this milestone.
Args:
all: If True, return all the items, without pagination
per_page: Number of items to retrieve per request
page: ID of the page to return (starts with page 1)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
The list of merge requests
"""
path = f"{self.manager.path}/{self.encoded_id}/merge_requests"
data_list = self.manager.gitlab.http_list(path, iterator=True, **kwargs)
if TYPE_CHECKING:
assert isinstance(data_list, RESTObjectList)
manager = ProjectMergeRequestManager(
self.manager.gitlab, parent=self.manager._parent
)
# FIXME(gpocentek): the computed manager path is not correct
return RESTObjectList(manager, ProjectMergeRequest, data_list)
class ProjectMilestoneManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/milestones"
_obj_cls = ProjectMilestone
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("title",),
optional=("description", "due_date", "start_date", "state_event"),
)
_update_attrs = RequiredOptional(
optional=("title", "description", "due_date", "start_date", "state_event"),
)
_list_filters = ("iids", "state", "search")
_types = {"iids": types.ArrayAttribute}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMilestone:
return cast(ProjectMilestone, super().get(id=id, lazy=lazy, **kwargs))
| 7,073 | Python | .py | 153 | 38.333333 | 87 | 0.672521 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,134 | files.py | python-gitlab_python-gitlab/gitlab/v4/objects/files.py | import base64
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Tuple,
TYPE_CHECKING,
Union,
)
import requests
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import utils
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
DeleteMixin,
ObjectDeleteMixin,
SaveMixin,
UpdateMixin,
)
from gitlab.types import RequiredOptional
__all__ = [
"ProjectFile",
"ProjectFileManager",
]
class ProjectFile(SaveMixin, ObjectDeleteMixin, RESTObject):
_id_attr = "file_path"
_repr_attr = "file_path"
branch: str
commit_message: str
file_path: str
manager: "ProjectFileManager"
content: str # since the `decode()` method uses `self.content`
def decode(self) -> bytes:
"""Returns the decoded content of the file.
Returns:
The decoded content.
"""
return base64.b64decode(self.content)
# NOTE(jlvillal): Signature doesn't match SaveMixin.save() so ignore
# type error
def save( # type: ignore
self, branch: str, commit_message: str, **kwargs: Any
) -> None:
"""Save the changes made to the file to the server.
The object is updated to match what the server returns.
Args:
branch: Branch in which the file will be updated
commit_message: Message to send with the commit
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request
"""
self.branch = branch
self.commit_message = commit_message
self.file_path = utils.EncodedId(self.file_path)
super().save(**kwargs)
@exc.on_http_error(exc.GitlabDeleteError)
# NOTE(jlvillal): Signature doesn't match DeleteMixin.delete() so ignore
# type error
def delete( # type: ignore
self, branch: str, commit_message: str, **kwargs: Any
) -> None:
"""Delete the file from the server.
Args:
branch: Branch from which the file will be removed
commit_message: Commit message for the deletion
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request
"""
file_path = self.encoded_id
if TYPE_CHECKING:
assert isinstance(file_path, str)
self.manager.delete(file_path, branch, commit_message, **kwargs)
class ProjectFileManager(CreateMixin, UpdateMixin, DeleteMixin, RESTManager):
_path = "/projects/{project_id}/repository/files"
_obj_cls = ProjectFile
_from_parent_attrs = {"project_id": "id"}
_optional_get_attrs: Tuple[str, ...] = ()
_create_attrs = RequiredOptional(
required=("file_path", "branch", "content", "commit_message"),
optional=("encoding", "author_email", "author_name"),
)
_update_attrs = RequiredOptional(
required=("file_path", "branch", "content", "commit_message"),
optional=("encoding", "author_email", "author_name"),
)
@cli.register_custom_action(
cls_names="ProjectFileManager", required=("file_path", "ref")
)
@exc.on_http_error(exc.GitlabGetError)
def get(self, file_path: str, ref: str, **kwargs: Any) -> ProjectFile:
"""Retrieve a single file.
Args:
file_path: Path of the file to retrieve
ref: Name of the branch, tag or commit
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the file could not be retrieved
Returns:
The generated RESTObject
"""
if TYPE_CHECKING:
assert file_path is not None
file_path = utils.EncodedId(file_path)
path = f"{self.path}/{file_path}"
server_data = self.gitlab.http_get(path, ref=ref, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
return self._obj_cls(self, server_data)
@exc.on_http_error(exc.GitlabHeadError)
def head(
self, file_path: str, ref: str, **kwargs: Any
) -> "requests.structures.CaseInsensitiveDict[Any]":
"""Retrieve just metadata for a single file.
Args:
file_path: Path of the file to retrieve
ref: Name of the branch, tag or commit
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the file could not be retrieved
Returns:
The response headers as a dictionary
"""
if TYPE_CHECKING:
assert file_path is not None
file_path = utils.EncodedId(file_path)
path = f"{self.path}/{file_path}"
return self.gitlab.http_head(path, ref=ref, **kwargs)
@cli.register_custom_action(
cls_names="ProjectFileManager",
required=("file_path", "branch", "content", "commit_message"),
optional=("encoding", "author_email", "author_name"),
)
@exc.on_http_error(exc.GitlabCreateError)
def create(
self, data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> ProjectFile:
"""Create a new object.
Args:
data: parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
a new instance of the managed object class built with
the data sent by the server
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request
"""
if TYPE_CHECKING:
assert data is not None
self._create_attrs.validate_attrs(data=data)
new_data = data.copy()
file_path = utils.EncodedId(new_data.pop("file_path"))
path = f"{self.path}/{file_path}"
server_data = self.gitlab.http_post(path, post_data=new_data, **kwargs)
if TYPE_CHECKING:
assert isinstance(server_data, dict)
return self._obj_cls(self, server_data)
@exc.on_http_error(exc.GitlabUpdateError)
# NOTE(jlvillal): Signature doesn't match UpdateMixin.update() so ignore
# type error
def update( # type: ignore
self, file_path: str, new_data: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> Dict[str, Any]:
"""Update an object on the server.
Args:
id: ID of the object to update (can be None if not required)
new_data: the update data for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
The new object data (*not* a RESTObject)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request
"""
new_data = new_data or {}
data = new_data.copy()
file_path = utils.EncodedId(file_path)
data["file_path"] = file_path
path = f"{self.path}/{file_path}"
self._update_attrs.validate_attrs(data=data)
result = self.gitlab.http_put(path, post_data=data, **kwargs)
if TYPE_CHECKING:
assert isinstance(result, dict)
return result
@cli.register_custom_action(
cls_names="ProjectFileManager",
required=("file_path", "branch", "commit_message"),
)
@exc.on_http_error(exc.GitlabDeleteError)
# NOTE(jlvillal): Signature doesn't match DeleteMixin.delete() so ignore
# type error
def delete( # type: ignore
self, file_path: str, branch: str, commit_message: str, **kwargs: Any
) -> None:
"""Delete a file on the server.
Args:
file_path: Path of the file to remove
branch: Branch from which the file will be removed
commit_message: Commit message for the deletion
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request
"""
file_path = utils.EncodedId(file_path)
path = f"{self.path}/{file_path}"
data = {"branch": branch, "commit_message": commit_message}
self.gitlab.http_delete(path, query_data=data, **kwargs)
@cli.register_custom_action(
cls_names="ProjectFileManager",
required=("file_path",),
)
@exc.on_http_error(exc.GitlabGetError)
def raw(
self,
file_path: str,
ref: Optional[str] = None,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Return the content of a file for a commit.
Args:
file_path: Path of the file to return
ref: ID of the commit
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
action: Callable responsible for dealing with each chunk of
data
chunk_size: Size of each chunk
iterator: If True directly return the underlying response
iterator
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the file could not be retrieved
Returns:
The file content
"""
file_path = utils.EncodedId(file_path)
path = f"{self.path}/{file_path}/raw"
if ref is not None:
query_data = {"ref": ref}
else:
query_data = None
result = self.gitlab.http_get(
path, query_data=query_data, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
@cli.register_custom_action(
cls_names="ProjectFileManager", required=("file_path", "ref")
)
@exc.on_http_error(exc.GitlabListError)
def blame(self, file_path: str, ref: str, **kwargs: Any) -> List[Dict[str, Any]]:
"""Return the content of a file for a commit.
Args:
file_path: Path of the file to retrieve
ref: Name of the branch, tag or commit
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the server failed to perform the request
Returns:
A list of commits/lines matching the file
"""
file_path = utils.EncodedId(file_path)
path = f"{self.path}/{file_path}/blame"
query_data = {"ref": ref}
result = self.gitlab.http_list(path, query_data, **kwargs)
if TYPE_CHECKING:
assert isinstance(result, list)
return result
| 11,674 | Python | .py | 292 | 31.113014 | 86 | 0.620656 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,135 | labels.py | python-gitlab_python-gitlab/gitlab/v4/objects/labels.py | from typing import Any, cast, Dict, Optional, Union
from gitlab import exceptions as exc
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
DeleteMixin,
ObjectDeleteMixin,
PromoteMixin,
RetrieveMixin,
SaveMixin,
SubscribableMixin,
UpdateMixin,
)
from gitlab.types import RequiredOptional
__all__ = [
"GroupLabel",
"GroupLabelManager",
"ProjectLabel",
"ProjectLabelManager",
]
class GroupLabel(SubscribableMixin, SaveMixin, ObjectDeleteMixin, RESTObject):
_id_attr = "name"
manager: "GroupLabelManager"
# Update without ID, but we need an ID to get from list.
@exc.on_http_error(exc.GitlabUpdateError)
def save(self, **kwargs: Any) -> None:
"""Saves the changes made to the object to the server.
The object is updated to match what the server returns.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct.
GitlabUpdateError: If the server cannot perform the request.
"""
updated_data = self._get_updated_data()
# call the manager
server_data = self.manager.update(None, updated_data, **kwargs)
self._update_attrs(server_data)
class GroupLabelManager(
RetrieveMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = "/groups/{group_id}/labels"
_obj_cls = GroupLabel
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(
required=("name", "color"), optional=("description", "priority")
)
_update_attrs = RequiredOptional(
required=("name",), optional=("new_name", "color", "description", "priority")
)
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> GroupLabel:
return cast(GroupLabel, super().get(id=id, lazy=lazy, **kwargs))
# Update without ID.
# NOTE(jlvillal): Signature doesn't match UpdateMixin.update() so ignore
# type error
def update( # type: ignore
self,
name: Optional[str],
new_data: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
"""Update a Label on the server.
Args:
name: The name of the label
**kwargs: Extra options to send to the server (e.g. sudo)
"""
new_data = new_data or {}
if name:
new_data["name"] = name
return super().update(id=None, new_data=new_data, **kwargs)
class ProjectLabel(
PromoteMixin, SubscribableMixin, SaveMixin, ObjectDeleteMixin, RESTObject
):
_id_attr = "name"
manager: "ProjectLabelManager"
# Update without ID, but we need an ID to get from list.
@exc.on_http_error(exc.GitlabUpdateError)
def save(self, **kwargs: Any) -> None:
"""Saves the changes made to the object to the server.
The object is updated to match what the server returns.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct.
GitlabUpdateError: If the server cannot perform the request.
"""
updated_data = self._get_updated_data()
# call the manager
server_data = self.manager.update(None, updated_data, **kwargs)
self._update_attrs(server_data)
class ProjectLabelManager(
RetrieveMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager
):
_path = "/projects/{project_id}/labels"
_obj_cls = ProjectLabel
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("name", "color"), optional=("description", "priority")
)
_update_attrs = RequiredOptional(
required=("name",), optional=("new_name", "color", "description", "priority")
)
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectLabel:
return cast(ProjectLabel, super().get(id=id, lazy=lazy, **kwargs))
# Update without ID.
# NOTE(jlvillal): Signature doesn't match UpdateMixin.update() so ignore
# type error
def update( # type: ignore
self,
name: Optional[str],
new_data: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
"""Update a Label on the server.
Args:
name: The name of the label
**kwargs: Extra options to send to the server (e.g. sudo)
"""
new_data = new_data or {}
if name:
new_data["name"] = name
return super().update(id=None, new_data=new_data, **kwargs)
| 4,736 | Python | .py | 124 | 31.241935 | 88 | 0.639991 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,136 | triggers.py | python-gitlab_python-gitlab/gitlab/v4/objects/triggers.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, ObjectDeleteMixin, SaveMixin
from gitlab.types import RequiredOptional
__all__ = [
"ProjectTrigger",
"ProjectTriggerManager",
]
class ProjectTrigger(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectTriggerManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/triggers"
_obj_cls = ProjectTrigger
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("description",))
_update_attrs = RequiredOptional(required=("description",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectTrigger:
return cast(ProjectTrigger, super().get(id=id, lazy=lazy, **kwargs))
| 824 | Python | .py | 20 | 37.05 | 76 | 0.730238 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,137 | boards.py | python-gitlab_python-gitlab/gitlab/v4/objects/boards.py | from typing import Any, cast, Union
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CRUDMixin, ObjectDeleteMixin, SaveMixin
from gitlab.types import RequiredOptional
__all__ = [
"GroupBoardList",
"GroupBoardListManager",
"GroupBoard",
"GroupBoardManager",
"ProjectBoardList",
"ProjectBoardListManager",
"ProjectBoard",
"ProjectBoardManager",
]
class GroupBoardList(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class GroupBoardListManager(CRUDMixin, RESTManager):
_path = "/groups/{group_id}/boards/{board_id}/lists"
_obj_cls = GroupBoardList
_from_parent_attrs = {"group_id": "group_id", "board_id": "id"}
_create_attrs = RequiredOptional(
exclusive=("label_id", "assignee_id", "milestone_id")
)
_update_attrs = RequiredOptional(required=("position",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupBoardList:
return cast(GroupBoardList, super().get(id=id, lazy=lazy, **kwargs))
class GroupBoard(SaveMixin, ObjectDeleteMixin, RESTObject):
lists: GroupBoardListManager
class GroupBoardManager(CRUDMixin, RESTManager):
_path = "/groups/{group_id}/boards"
_obj_cls = GroupBoard
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(required=("name",))
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> GroupBoard:
return cast(GroupBoard, super().get(id=id, lazy=lazy, **kwargs))
class ProjectBoardList(SaveMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectBoardListManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/boards/{board_id}/lists"
_obj_cls = ProjectBoardList
_from_parent_attrs = {"project_id": "project_id", "board_id": "id"}
_create_attrs = RequiredOptional(
exclusive=("label_id", "assignee_id", "milestone_id")
)
_update_attrs = RequiredOptional(required=("position",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectBoardList:
return cast(ProjectBoardList, super().get(id=id, lazy=lazy, **kwargs))
class ProjectBoard(SaveMixin, ObjectDeleteMixin, RESTObject):
lists: ProjectBoardListManager
class ProjectBoardManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/boards"
_obj_cls = ProjectBoard
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(required=("name",))
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectBoard:
return cast(ProjectBoard, super().get(id=id, lazy=lazy, **kwargs))
| 2,680 | Python | .py | 62 | 38.193548 | 88 | 0.695686 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,138 | access_requests.py | python-gitlab_python-gitlab/gitlab/v4/objects/access_requests.py | from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
AccessRequestMixin,
CreateMixin,
DeleteMixin,
ListMixin,
ObjectDeleteMixin,
)
__all__ = [
"GroupAccessRequest",
"GroupAccessRequestManager",
"ProjectAccessRequest",
"ProjectAccessRequestManager",
]
class GroupAccessRequest(AccessRequestMixin, ObjectDeleteMixin, RESTObject):
pass
class GroupAccessRequestManager(ListMixin, CreateMixin, DeleteMixin, RESTManager):
_path = "/groups/{group_id}/access_requests"
_obj_cls = GroupAccessRequest
_from_parent_attrs = {"group_id": "id"}
class ProjectAccessRequest(AccessRequestMixin, ObjectDeleteMixin, RESTObject):
pass
class ProjectAccessRequestManager(ListMixin, CreateMixin, DeleteMixin, RESTManager):
_path = "/projects/{project_id}/access_requests"
_obj_cls = ProjectAccessRequest
_from_parent_attrs = {"project_id": "id"}
| 923 | Python | .py | 26 | 31.538462 | 84 | 0.765766 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,139 | merge_trains.py | python-gitlab_python-gitlab/gitlab/v4/objects/merge_trains.py | from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import ListMixin
__all__ = [
"ProjectMergeTrain",
"ProjectMergeTrainManager",
]
class ProjectMergeTrain(RESTObject):
pass
class ProjectMergeTrainManager(ListMixin, RESTManager):
_path = "/projects/{project_id}/merge_trains"
_obj_cls = ProjectMergeTrain
_from_parent_attrs = {"project_id": "id"}
_list_filters = ("scope",)
| 422 | Python | .py | 13 | 28.923077 | 55 | 0.737624 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,140 | members.py | python-gitlab_python-gitlab/gitlab/v4/objects/members.py | from typing import Any, cast, Union
from gitlab import types
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CRUDMixin,
DeleteMixin,
ListMixin,
ObjectDeleteMixin,
RetrieveMixin,
SaveMixin,
)
from gitlab.types import RequiredOptional
__all__ = [
"GroupBillableMember",
"GroupBillableMemberManager",
"GroupBillableMemberMembership",
"GroupBillableMemberMembershipManager",
"GroupMember",
"GroupMemberAll",
"GroupMemberManager",
"GroupMemberAllManager",
"ProjectMember",
"ProjectMemberAll",
"ProjectMemberManager",
"ProjectMemberAllManager",
]
class GroupMember(SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "username"
class GroupMemberManager(CRUDMixin, RESTManager):
_path = "/groups/{group_id}/members"
_obj_cls = GroupMember
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(
required=("access_level",),
optional=("expires_at", "tasks_to_be_done"),
exclusive=("username", "user_id"),
)
_update_attrs = RequiredOptional(
required=("access_level",), optional=("expires_at",)
)
_types = {
"user_ids": types.ArrayAttribute,
"tasks_to_be_done": types.ArrayAttribute,
}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupMember:
return cast(GroupMember, super().get(id=id, lazy=lazy, **kwargs))
class GroupBillableMember(ObjectDeleteMixin, RESTObject):
_repr_attr = "username"
memberships: "GroupBillableMemberMembershipManager"
class GroupBillableMemberManager(ListMixin, DeleteMixin, RESTManager):
_path = "/groups/{group_id}/billable_members"
_obj_cls = GroupBillableMember
_from_parent_attrs = {"group_id": "id"}
_list_filters = ("search", "sort")
class GroupBillableMemberMembership(RESTObject):
_id_attr = "user_id"
class GroupBillableMemberMembershipManager(ListMixin, RESTManager):
_path = "/groups/{group_id}/billable_members/{user_id}/memberships"
_obj_cls = GroupBillableMemberMembership
_from_parent_attrs = {"group_id": "group_id", "user_id": "id"}
class GroupMemberAll(RESTObject):
_repr_attr = "username"
class GroupMemberAllManager(RetrieveMixin, RESTManager):
_path = "/groups/{group_id}/members/all"
_obj_cls = GroupMemberAll
_from_parent_attrs = {"group_id": "id"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupMemberAll:
return cast(GroupMemberAll, super().get(id=id, lazy=lazy, **kwargs))
class ProjectMember(SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = "username"
class ProjectMemberManager(CRUDMixin, RESTManager):
_path = "/projects/{project_id}/members"
_obj_cls = ProjectMember
_from_parent_attrs = {"project_id": "id"}
_create_attrs = RequiredOptional(
required=("access_level",),
optional=("expires_at", "tasks_to_be_done"),
exclusive=("username", "user_id"),
)
_update_attrs = RequiredOptional(
required=("access_level",), optional=("expires_at",)
)
_types = {
"user_ids": types.ArrayAttribute,
"tasks_to_be_dones": types.ArrayAttribute,
}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMember:
return cast(ProjectMember, super().get(id=id, lazy=lazy, **kwargs))
class ProjectMemberAll(RESTObject):
_repr_attr = "username"
class ProjectMemberAllManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/members/all"
_obj_cls = ProjectMemberAll
_from_parent_attrs = {"project_id": "id"}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectMemberAll:
return cast(ProjectMemberAll, super().get(id=id, lazy=lazy, **kwargs))
| 3,902 | Python | .py | 104 | 32.221154 | 78 | 0.683037 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,141 | deploy_tokens.py | python-gitlab_python-gitlab/gitlab/v4/objects/deploy_tokens.py | from typing import Any, cast, Union
from gitlab import types
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import (
CreateMixin,
DeleteMixin,
ListMixin,
ObjectDeleteMixin,
RetrieveMixin,
)
from gitlab.types import RequiredOptional
__all__ = [
"DeployToken",
"DeployTokenManager",
"GroupDeployToken",
"GroupDeployTokenManager",
"ProjectDeployToken",
"ProjectDeployTokenManager",
]
class DeployToken(ObjectDeleteMixin, RESTObject):
pass
class DeployTokenManager(ListMixin, RESTManager):
_path = "/deploy_tokens"
_obj_cls = DeployToken
class GroupDeployToken(ObjectDeleteMixin, RESTObject):
pass
class GroupDeployTokenManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager):
_path = "/groups/{group_id}/deploy_tokens"
_from_parent_attrs = {"group_id": "id"}
_obj_cls = GroupDeployToken
_create_attrs = RequiredOptional(
required=(
"name",
"scopes",
),
optional=(
"expires_at",
"username",
),
)
_list_filters = ("scopes",)
_types = {"scopes": types.ArrayAttribute}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> GroupDeployToken:
return cast(GroupDeployToken, super().get(id=id, lazy=lazy, **kwargs))
class ProjectDeployToken(ObjectDeleteMixin, RESTObject):
pass
class ProjectDeployTokenManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager):
_path = "/projects/{project_id}/deploy_tokens"
_from_parent_attrs = {"project_id": "id"}
_obj_cls = ProjectDeployToken
_create_attrs = RequiredOptional(
required=(
"name",
"scopes",
),
optional=(
"expires_at",
"username",
),
)
_list_filters = ("scopes",)
_types = {"scopes": types.ArrayAttribute}
def get(
self, id: Union[str, int], lazy: bool = False, **kwargs: Any
) -> ProjectDeployToken:
return cast(ProjectDeployToken, super().get(id=id, lazy=lazy, **kwargs))
| 2,110 | Python | .py | 68 | 24.970588 | 86 | 0.653998 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,142 | service_accounts.py | python-gitlab_python-gitlab/gitlab/v4/objects/service_accounts.py | from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import CreateMixin
from gitlab.types import RequiredOptional
__all__ = ["GroupServiceAccount", "GroupServiceAccountManager"]
class GroupServiceAccount(RESTObject):
pass
class GroupServiceAccountManager(CreateMixin, RESTManager):
_path = "/groups/{group_id}/service_accounts"
_obj_cls = GroupServiceAccount
_from_parent_attrs = {"group_id": "id"}
_create_attrs = RequiredOptional(
optional=("name", "username"),
)
| 517 | Python | .py | 13 | 35.923077 | 63 | 0.757515 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,143 | jobs.py | python-gitlab_python-gitlab/gitlab/v4/objects/jobs.py | from typing import Any, Callable, cast, Dict, Iterator, Optional, TYPE_CHECKING, Union
import requests
from gitlab import cli
from gitlab import exceptions as exc
from gitlab import utils
from gitlab.base import RESTManager, RESTObject
from gitlab.mixins import RefreshMixin, RetrieveMixin
from gitlab.types import ArrayAttribute
__all__ = [
"ProjectJob",
"ProjectJobManager",
]
class ProjectJob(RefreshMixin, RESTObject):
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabJobCancelError)
def cancel(self, **kwargs: Any) -> Dict[str, Any]:
"""Cancel the job.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobCancelError: If the job could not be canceled
"""
path = f"{self.manager.path}/{self.encoded_id}/cancel"
result = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(result, dict)
return result
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabJobRetryError)
def retry(self, **kwargs: Any) -> Dict[str, Any]:
"""Retry the job.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobRetryError: If the job could not be retried
"""
path = f"{self.manager.path}/{self.encoded_id}/retry"
result = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(result, dict)
return result
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabJobPlayError)
def play(self, **kwargs: Any) -> None:
"""Trigger a job explicitly.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobPlayError: If the job could not be triggered
"""
path = f"{self.manager.path}/{self.encoded_id}/play"
result = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert isinstance(result, dict)
self._update_attrs(result)
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabJobEraseError)
def erase(self, **kwargs: Any) -> None:
"""Erase the job (remove job artifacts and trace).
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobEraseError: If the job could not be erased
"""
path = f"{self.manager.path}/{self.encoded_id}/erase"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabCreateError)
def keep_artifacts(self, **kwargs: Any) -> None:
"""Prevent artifacts from being deleted when expiration is set.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the request could not be performed
"""
path = f"{self.manager.path}/{self.encoded_id}/artifacts/keep"
self.manager.gitlab.http_post(path, **kwargs)
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabCreateError)
def delete_artifacts(self, **kwargs: Any) -> None:
"""Delete artifacts of a job.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the request could not be performed
"""
path = f"{self.manager.path}/{self.encoded_id}/artifacts"
self.manager.gitlab.http_delete(path, **kwargs)
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabGetError)
def artifacts(
self,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Get the job artifacts.
Args:
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the artifacts could not be retrieved
Returns:
The artifacts if `streamed` is False, None otherwise.
"""
path = f"{self.manager.path}/{self.encoded_id}/artifacts"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabGetError)
def artifact(
self,
path: str,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Get a single artifact file from within the job's artifacts archive.
Args:
path: Path of the artifact
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the artifacts could not be retrieved
Returns:
The artifacts if `streamed` is False, None otherwise.
"""
path = f"{self.manager.path}/{self.encoded_id}/artifacts/{path}"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
@cli.register_custom_action(cls_names="ProjectJob")
@exc.on_http_error(exc.GitlabGetError)
def trace(
self,
streamed: bool = False,
action: Optional[Callable[..., Any]] = None,
chunk_size: int = 1024,
*,
iterator: bool = False,
**kwargs: Any,
) -> Optional[Union[bytes, Iterator[Any]]]:
"""Get the job trace.
Args:
streamed: If True the data will be processed by chunks of
`chunk_size` and each chunk is passed to `action` for
treatment
iterator: If True directly return the underlying response
iterator
action: Callable responsible of dealing with chunk of
data
chunk_size: Size of each chunk
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the artifacts could not be retrieved
Returns:
The trace
"""
path = f"{self.manager.path}/{self.encoded_id}/trace"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
if TYPE_CHECKING:
assert isinstance(result, requests.Response)
return utils.response_content(
result, streamed, action, chunk_size, iterator=iterator
)
class ProjectJobManager(RetrieveMixin, RESTManager):
_path = "/projects/{project_id}/jobs"
_obj_cls = ProjectJob
_from_parent_attrs = {"project_id": "id"}
_list_filters = ("scope",)
_types = {"scope": ArrayAttribute}
def get(self, id: Union[str, int], lazy: bool = False, **kwargs: Any) -> ProjectJob:
return cast(ProjectJob, super().get(id=id, lazy=lazy, **kwargs))
| 9,140 | Python | .py | 215 | 33.023256 | 88 | 0.6268 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,144 | conf.py | python-gitlab_python-gitlab/docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# python-gitlab documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 8 15:17:39 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from __future__ import unicode_literals
import os
import sys
from datetime import datetime
from sphinx.domains.python import PythonDomain
sys.path.append("../")
sys.path.append(os.path.dirname(__file__))
import gitlab # noqa: E402. Needed purely for readthedocs' build
# Sphinx will warn when attributes are exported in multiple places. See workaround:
# https://github.com/sphinx-doc/sphinx/issues/3866#issuecomment-768167824
# This patch can be removed when this issue is resolved:
# https://github.com/sphinx-doc/sphinx/issues/4961
class PatchedPythonDomain(PythonDomain):
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
if "refspecific" in node:
del node["refspecific"]
return super(PatchedPythonDomain, self).resolve_xref(
env, fromdocname, builder, typ, target, node, contnode
)
def setup(sphinx):
sphinx.add_domain(PatchedPythonDomain, override=True)
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
year = datetime.now().year
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(".."))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"myst_parser",
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"ext.docstrings",
"sphinxcontrib.autoprogram",
]
autodoc_typehints = "both"
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = {".rst": "restructuredtext", ".md": "markdown"}
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
root_doc = "index"
# General information about the project.
project = "python-gitlab"
copyright = gitlab.__copyright__
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = gitlab.__version__
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "furo"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = f"{project} <small>v{release}</small>"
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
html_js_files = [
"js/gitter.js",
(
"https://sidecar.gitter.im/dist/sidecar.v1.js",
{"async": "async", "defer": "defer"},
),
]
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "python-gitlabdoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
"index",
"python-gitlab.tex",
"python-gitlab Documentation",
"Gauvain Pocentek, Mika Mäenpää",
"manual",
)
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(
"index",
"python-gitlab",
"python-gitlab Documentation",
["Gauvain Pocentek, Mika Mäenpää"],
1,
)
]
# If true, show URL addresses after external links.
# man_show_urls = False
nitpick_ignore_regex = [(r"py:.*", r".*")]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
"index",
"python-gitlab",
"python-gitlab Documentation",
"Gauvain Pocentek, Mika Mäenpää",
"python-gitlab",
"One line description of project.",
"Miscellaneous",
)
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
| 9,858 | Python | .py | 241 | 38.356846 | 83 | 0.712232 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,145 | docstrings.py | python-gitlab_python-gitlab/docs/ext/docstrings.py | import inspect
import os
import jinja2
import sphinx
import sphinx.ext.napoleon as napoleon
from sphinx.ext.napoleon.docstring import GoogleDocstring
def classref(value, short=True):
return value
if not inspect.isclass(value):
return f":class:{value}"
tilde = "~" if short else ""
return f":class:`{tilde}gitlab.objects.{value.__name__}`"
def setup(app):
app.connect("autodoc-process-docstring", _process_docstring)
app.connect("autodoc-skip-member", napoleon._skip_member)
conf = napoleon.Config._config_values
for name, (default, rebuild) in conf.items():
app.add_config_value(name, default, rebuild)
return {"version": sphinx.__display_version__, "parallel_read_safe": True}
def _process_docstring(app, what, name, obj, options, lines):
result_lines = lines
docstring = GitlabDocstring(result_lines, app.config, app, what, name, obj, options)
result_lines = docstring.lines()
lines[:] = result_lines[:]
class GitlabDocstring(GoogleDocstring):
def _build_doc(self, tmpl, **kwargs):
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), trim_blocks=False
)
env.filters["classref"] = classref
template = env.get_template(tmpl)
output = template.render(**kwargs)
return output.split("\n")
def __init__(
self, docstring, config=None, app=None, what="", name="", obj=None, options=None
):
super().__init__(docstring, config, app, what, name, obj, options)
if name.startswith("gitlab.v4.objects") and name.endswith("Manager"):
self._parsed_lines.extend(self._build_doc("manager_tmpl.j2", cls=self._obj))
| 1,722 | Python | .py | 39 | 38.25641 | 88 | 0.681055 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,146 | conftest.py | python-gitlab_python-gitlab/tests/conftest.py | import pathlib
import _pytest.config
import pytest
import gitlab
@pytest.fixture(scope="session")
def test_dir(pytestconfig: _pytest.config.Config) -> pathlib.Path:
return pytestconfig.rootdir / "tests" # type: ignore
@pytest.fixture(autouse=True)
def mock_clean_config(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ensures user-defined environment variables do not interfere with tests."""
monkeypatch.delenv("PYTHON_GITLAB_CFG", raising=False)
monkeypatch.delenv("GITLAB_PRIVATE_TOKEN", raising=False)
monkeypatch.delenv("GITLAB_URL", raising=False)
monkeypatch.delenv("CI_JOB_TOKEN", raising=False)
monkeypatch.delenv("CI_SERVER_URL", raising=False)
@pytest.fixture(autouse=True)
def default_files(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ensures user configuration files do not interfere with tests."""
monkeypatch.setattr(gitlab.config, "_DEFAULT_FILES", [])
@pytest.fixture
def valid_gitlab_ci_yml() -> str:
return """---
:test_job:
:script: echo 1
"""
@pytest.fixture
def invalid_gitlab_ci_yml() -> str:
return "invalid"
| 1,090 | Python | .py | 28 | 35.857143 | 81 | 0.750476 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,147 | conftest.py | python-gitlab_python-gitlab/tests/unit/conftest.py | import pytest
import responses
import gitlab
from tests.unit import helpers
@pytest.fixture
def fake_manager(gl):
return helpers.FakeManager(gl)
@pytest.fixture
def fake_manager_with_parent(gl, fake_manager):
return helpers.FakeManagerWithParent(
gl, parent=helpers.FakeParent(manager=fake_manager, attrs={})
)
@pytest.fixture
def fake_object(fake_manager):
return helpers.FakeObject(fake_manager, {"attr1": "foo", "alist": [1, 2, 3]})
@pytest.fixture
def fake_object_no_id(fake_manager):
return helpers.FakeObjectWithoutId(fake_manager, {})
@pytest.fixture
def fake_object_long_repr(fake_manager):
return helpers.FakeObjectWithLongRepr(fake_manager, {"test": "a" * 100})
@pytest.fixture
def fake_object_with_parent(fake_manager_with_parent):
return helpers.FakeObject(
fake_manager_with_parent, {"attr1": "foo", "alist": [1, 2, 3]}
)
@pytest.fixture
def gl():
return gitlab.Gitlab(
"http://localhost",
private_token="private_token",
ssl_verify=True,
api_version="4",
)
@pytest.fixture
def gl_retry():
return gitlab.Gitlab(
"http://localhost",
private_token="private_token",
ssl_verify=True,
api_version="4",
retry_transient_errors=True,
)
@pytest.fixture
def resp_get_current_user():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/user",
json={
"id": 1,
"username": "username",
"web_url": "http://localhost/username",
},
content_type="application/json",
status=200,
)
yield rsps
# Todo: parametrize, but check what tests it's really useful for
@pytest.fixture
def gl_trailing():
return gitlab.Gitlab(
"http://localhost/", private_token="private_token", api_version="4"
)
@pytest.fixture
def default_config(tmpdir):
valid_config = """[global]
default = one
ssl_verify = true
timeout = 2
[one]
url = http://one.url
private_token = ABCDEF
"""
config_path = tmpdir.join("python-gitlab.cfg")
config_path.write(valid_config)
return str(config_path)
@pytest.fixture
def tag_name():
return "v1.0.0"
@pytest.fixture
def group(gl):
return gl.groups.get(1, lazy=True)
@pytest.fixture
def project(gl):
return gl.projects.get(1, lazy=True)
@pytest.fixture
def another_project(gl):
return gl.projects.get(2, lazy=True)
@pytest.fixture
def project_issue(project):
return project.issues.get(1, lazy=True)
@pytest.fixture
def project_merge_request(project):
return project.mergerequests.get(1, lazy=True)
@pytest.fixture
def release(project, tag_name):
return project.releases.get(tag_name, lazy=True)
@pytest.fixture
def schedule(project):
return project.pipelineschedules.get(1, lazy=True)
@pytest.fixture
def user(gl):
return gl.users.get(1, lazy=True)
@pytest.fixture
def current_user(gl, resp_get_current_user):
gl.auth()
return gl.user
@pytest.fixture
def migration(gl):
return gl.bulk_imports.get(1, lazy=True)
| 3,194 | Python | .py | 111 | 23.81982 | 81 | 0.681818 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,148 | test_types.py | python-gitlab_python-gitlab/tests/unit/test_types.py | import pytest
from gitlab import types
class TestRequiredOptional:
def test_requiredoptional_empty(self):
b = types.RequiredOptional()
assert not b.required
assert not b.optional
assert not b.exclusive
def test_requiredoptional_values_no_keywords(self):
b = types.RequiredOptional(
("required1", "required2"),
("optional1", "optional2"),
("exclusive1", "exclusive2"),
)
assert b.required == ("required1", "required2")
assert b.optional == ("optional1", "optional2")
assert b.exclusive == ("exclusive1", "exclusive2")
def test_requiredoptional_values_keywords(self):
b = types.RequiredOptional(
exclusive=("exclusive1", "exclusive2"),
optional=("optional1", "optional2"),
required=("required1", "required2"),
)
assert b.required == ("required1", "required2")
assert b.optional == ("optional1", "optional2")
assert b.exclusive == ("exclusive1", "exclusive2")
def test_validate_attrs_required(self):
data = {"required1": 1, "optional2": 2}
rq = types.RequiredOptional(required=("required1",))
rq.validate_attrs(data=data)
data = {"optional1": 1, "optional2": 2}
with pytest.raises(AttributeError, match="Missing attributes: required1"):
rq.validate_attrs(data=data)
def test_validate_attrs_exclusive(self):
data = {"exclusive1": 1, "optional1": 1}
rq = types.RequiredOptional(exclusive=("exclusive1", "exclusive2"))
rq.validate_attrs(data=data)
data = {"exclusive1": 1, "exclusive2": 2, "optional1": 1}
with pytest.raises(
AttributeError,
match="Provide only one of these attributes: exclusive1, exclusive2",
):
rq.validate_attrs(data=data)
def test_gitlab_attribute_get():
o = types.GitlabAttribute("whatever")
assert o.get() == "whatever"
o.set_from_cli("whatever2")
assert o.get() == "whatever2"
assert o.get_for_api(key="spam") == ("spam", "whatever2")
o = types.GitlabAttribute()
assert o._value is None
def test_array_attribute_input():
o = types.ArrayAttribute()
o.set_from_cli("foo,bar,baz")
assert o.get() == ["foo", "bar", "baz"]
o.set_from_cli("foo")
assert o.get() == ["foo"]
def test_array_attribute_empty_input():
o = types.ArrayAttribute()
o.set_from_cli("")
assert o.get() == []
o.set_from_cli(" ")
assert o.get() == []
def test_array_attribute_get_for_api_from_cli():
o = types.ArrayAttribute()
o.set_from_cli("foo,bar,baz")
assert o.get_for_api(key="spam") == ("spam[]", ["foo", "bar", "baz"])
def test_array_attribute_get_for_api_from_list():
o = types.ArrayAttribute(["foo", "bar", "baz"])
assert o.get_for_api(key="spam") == ("spam[]", ["foo", "bar", "baz"])
def test_array_attribute_get_for_api_from_int_list():
o = types.ArrayAttribute([1, 9, 7])
assert o.get_for_api(key="spam") == ("spam[]", [1, 9, 7])
def test_array_attribute_does_not_split_string():
o = types.ArrayAttribute("foo")
assert o.get_for_api(key="spam") == ("spam[]", "foo")
# CommaSeparatedListAttribute tests
def test_csv_string_attribute_get_for_api_from_cli():
o = types.CommaSeparatedListAttribute()
o.set_from_cli("foo,bar,baz")
assert o.get_for_api(key="spam") == ("spam", "foo,bar,baz")
def test_csv_string_attribute_get_for_api_from_list():
o = types.CommaSeparatedListAttribute(["foo", "bar", "baz"])
assert o.get_for_api(key="spam") == ("spam", "foo,bar,baz")
def test_csv_string_attribute_get_for_api_from_int_list():
o = types.CommaSeparatedListAttribute([1, 9, 7])
assert o.get_for_api(key="spam") == ("spam", "1,9,7")
# LowercaseStringAttribute tests
def test_lowercase_string_attribute_get_for_api():
o = types.LowercaseStringAttribute("FOO")
assert o.get_for_api(key="spam") == ("spam", "foo")
| 4,011 | Python | .py | 91 | 37.43956 | 82 | 0.632622 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,149 | test_cli.py | python-gitlab_python-gitlab/tests/unit/test_cli.py | import argparse
import contextlib
import io
import os
import sys
import tempfile
from unittest import mock
import pytest
import gitlab.base
from gitlab import cli
from gitlab.exceptions import GitlabError
from gitlab.mixins import CreateMixin, UpdateMixin
from gitlab.types import RequiredOptional
from gitlab.v4 import cli as v4_cli
@pytest.mark.parametrize(
"gitlab_resource,expected_class",
[
("class", "Class"),
("test-class", "TestClass"),
("test-longer-class", "TestLongerClass"),
("current-user-gpg-key", "CurrentUserGPGKey"),
("user-gpg-key", "UserGPGKey"),
("ldap-group", "LDAPGroup"),
],
)
def test_gitlab_resource_to_cls(gitlab_resource, expected_class):
def _namespace():
pass
ExpectedClass = type(expected_class, (gitlab.base.RESTObject,), {})
_namespace.__dict__[expected_class] = ExpectedClass
assert cli.gitlab_resource_to_cls(gitlab_resource, _namespace) == ExpectedClass
@pytest.mark.parametrize(
"class_name,expected_gitlab_resource",
[
("Class", "class"),
("TestClass", "test-class"),
("TestUPPERCASEClass", "test-uppercase-class"),
("UPPERCASETestClass", "uppercase-test-class"),
("CurrentUserGPGKey", "current-user-gpg-key"),
("UserGPGKey", "user-gpg-key"),
("LDAPGroup", "ldap-group"),
],
)
def test_cls_to_gitlab_resource(class_name, expected_gitlab_resource):
TestClass = type(class_name, (), {})
assert cli.cls_to_gitlab_resource(TestClass) == expected_gitlab_resource
@pytest.mark.parametrize(
"message,error,expected",
[
("foobar", None, "foobar\n"),
("foo", GitlabError("bar"), "foo (bar)\n"),
],
)
def test_die(message, error, expected):
fl = io.StringIO()
with contextlib.redirect_stderr(fl):
with pytest.raises(SystemExit) as test:
cli.die(message, error)
assert fl.getvalue() == expected
assert test.value.code == 1
def test_parse_value():
ret = cli._parse_value("foobar")
assert ret == "foobar"
ret = cli._parse_value(True)
assert ret is True
ret = cli._parse_value(1)
assert ret == 1
ret = cli._parse_value(None)
assert ret is None
fd, temp_path = tempfile.mkstemp()
os.write(fd, b"content")
os.close(fd)
ret = cli._parse_value(f"@{temp_path}")
assert ret == "content"
os.unlink(temp_path)
fl = io.StringIO()
with contextlib.redirect_stderr(fl):
with pytest.raises(SystemExit) as exc:
cli._parse_value("@/thisfileprobablydoesntexist")
assert fl.getvalue().startswith(
"FileNotFoundError: [Errno 2] No such file or directory:"
)
assert exc.value.code == 1
def test_base_parser():
parser = cli._get_base_parser()
args = parser.parse_args(["-v", "-g", "gl_id", "-c", "foo.cfg", "-c", "bar.cfg"])
assert args.verbose
assert args.gitlab == "gl_id"
assert args.config_file == ["foo.cfg", "bar.cfg"]
assert args.ssl_verify is None
def test_no_ssl_verify():
parser = cli._get_base_parser()
args = parser.parse_args(["--no-ssl-verify"])
assert args.ssl_verify is False
def test_v4_parse_args():
parser = cli._get_parser()
args = parser.parse_args(["project", "list"])
assert args.gitlab_resource == "project"
assert args.resource_action == "list"
def test_v4_parser():
parser = cli._get_parser()
subparsers = next(
action
for action in parser._actions
if isinstance(action, argparse._SubParsersAction)
)
assert subparsers is not None
assert "project" in subparsers.choices
user_subparsers = next(
action
for action in subparsers.choices["project"]._actions
if isinstance(action, argparse._SubParsersAction)
)
assert user_subparsers is not None
assert "list" in user_subparsers.choices
assert "get" in user_subparsers.choices
assert "delete" in user_subparsers.choices
assert "update" in user_subparsers.choices
assert "create" in user_subparsers.choices
assert "archive" in user_subparsers.choices
assert "unarchive" in user_subparsers.choices
actions = user_subparsers.choices["create"]._option_string_actions
assert not actions["--description"].required
user_subparsers = next(
action
for action in subparsers.choices["group"]._actions
if isinstance(action, argparse._SubParsersAction)
)
actions = user_subparsers.choices["create"]._option_string_actions
assert actions["--name"].required
def test_extend_parser():
class ExceptionArgParser(argparse.ArgumentParser):
def error(self, message):
"Raise error instead of exiting on invalid arguments, to make testing easier"
raise ValueError(message)
class Fake:
_id_attr = None
class FakeManager(gitlab.base.RESTManager, CreateMixin, UpdateMixin):
_obj_cls = Fake
_create_attrs = RequiredOptional(
required=("create",),
optional=("opt_create",),
exclusive=("create_a", "create_b"),
)
_update_attrs = RequiredOptional(
required=("update",),
optional=("opt_update",),
exclusive=("update_a", "update_b"),
)
parser = ExceptionArgParser()
with mock.patch.dict(
"gitlab.v4.objects.__dict__", {"FakeManager": FakeManager}, clear=True
):
v4_cli.extend_parser(parser)
assert parser.parse_args(["fake", "create", "--create", "1"])
assert parser.parse_args(["fake", "create", "--create", "1", "--opt-create", "1"])
assert parser.parse_args(["fake", "create", "--create", "1", "--create-a", "1"])
assert parser.parse_args(["fake", "create", "--create", "1", "--create-b", "1"])
with pytest.raises(ValueError):
# missing required "create"
parser.parse_args(["fake", "create", "--opt_create", "1"])
with pytest.raises(ValueError):
# both exclusive options
parser.parse_args(
["fake", "create", "--create", "1", "--create-a", "1", "--create-b", "1"]
)
assert parser.parse_args(["fake", "update", "--update", "1"])
assert parser.parse_args(["fake", "update", "--update", "1", "--opt-update", "1"])
assert parser.parse_args(["fake", "update", "--update", "1", "--update-a", "1"])
assert parser.parse_args(["fake", "update", "--update", "1", "--update-b", "1"])
with pytest.raises(ValueError):
# missing required "update"
parser.parse_args(["fake", "update", "--opt_update", "1"])
with pytest.raises(ValueError):
# both exclusive options
parser.parse_args(
["fake", "update", "--update", "1", "--update-a", "1", "--update-b", "1"]
)
@pytest.mark.skipif(sys.version_info < (3, 8), reason="added in 3.8")
def test_legacy_display_without_fields_warns(fake_object_no_id):
printer = v4_cli.LegacyPrinter()
with mock.patch("builtins.print") as mocked:
printer.display(fake_object_no_id, obj=fake_object_no_id)
assert "No default fields to show" in mocked.call_args.args[0]
@pytest.mark.skipif(sys.version_info < (3, 8), reason="added in 3.8")
def test_legacy_display_with_long_repr_truncates(fake_object_long_repr):
printer = v4_cli.LegacyPrinter()
with mock.patch("builtins.print") as mocked:
printer.display(fake_object_long_repr, obj=fake_object_long_repr)
assert len(mocked.call_args.args[0]) < 80
| 7,536 | Python | .py | 190 | 33.484211 | 89 | 0.646204 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,150 | test_graphql.py | python-gitlab_python-gitlab/tests/unit/test_graphql.py | import httpx
import pytest
import respx
import gitlab
@pytest.fixture
def gl_gql() -> gitlab.GraphQL:
return gitlab.GraphQL("https://gitlab.example.com")
def test_import_error_includes_message(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(gitlab.client, "_GQL_INSTALLED", False)
with pytest.raises(ImportError, match="GraphQL client could not be initialized"):
gitlab.GraphQL()
def test_graphql_as_context_manager_exits():
with gitlab.GraphQL() as gl:
assert isinstance(gl, gitlab.GraphQL)
def test_graphql_retries_on_429_response(
gl_gql: gitlab.GraphQL, respx_mock: respx.MockRouter
):
url = "https://gitlab.example.com/api/graphql"
responses = [
httpx.Response(429, headers={"retry-after": "1"}),
httpx.Response(
200, json={"data": {"currentUser": {"id": "gid://gitlab/User/1"}}}
),
]
respx_mock.post(url).mock(side_effect=responses)
gl_gql.execute("query {currentUser {id}}")
def test_graphql_raises_when_max_retries_exceeded(respx_mock: respx.MockRouter):
url = "https://gitlab.example.com/api/graphql"
responses = [
httpx.Response(502),
httpx.Response(502),
httpx.Response(502),
]
respx_mock.post(url).mock(side_effect=responses)
gl_gql = gitlab.GraphQL(
"https://gitlab.example.com", max_retries=1, retry_transient_errors=True
)
with pytest.raises(gitlab.GitlabHttpError):
gl_gql.execute("query {currentUser {id}}")
def test_graphql_raises_on_401_response(
gl_gql: gitlab.GraphQL, respx_mock: respx.MockRouter
):
url = "https://gitlab.example.com/api/graphql"
respx_mock.post(url).mock(return_value=httpx.Response(401))
with pytest.raises(gitlab.GitlabAuthenticationError):
gl_gql.execute("query {currentUser {id}}")
| 1,830 | Python | .py | 46 | 34.478261 | 85 | 0.69887 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,151 | test_gitlab_auth.py | python-gitlab_python-gitlab/tests/unit/test_gitlab_auth.py | import pathlib
import pytest
import requests
import responses
from requests import PreparedRequest
from gitlab import Gitlab
from gitlab._backends import JobTokenAuth, OAuthTokenAuth, PrivateTokenAuth
from gitlab.config import GitlabConfigParser
@pytest.fixture
def netrc(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path):
netrc_file = tmp_path / ".netrc"
netrc_file.write_text("machine localhost login test password test")
monkeypatch.setenv("NETRC", str(netrc_file))
def test_invalid_auth_args():
with pytest.raises(ValueError):
Gitlab(
"http://localhost",
api_version="4",
private_token="private_token",
oauth_token="bearer",
)
with pytest.raises(ValueError):
Gitlab(
"http://localhost",
api_version="4",
oauth_token="bearer",
http_username="foo",
http_password="bar",
)
with pytest.raises(ValueError):
Gitlab(
"http://localhost",
api_version="4",
private_token="private_token",
http_password="bar",
)
with pytest.raises(ValueError):
Gitlab(
"http://localhost",
api_version="4",
private_token="private_token",
http_username="foo",
)
def test_private_token_auth():
gl = Gitlab("http://localhost", private_token="private_token", api_version="4")
p = PreparedRequest()
p.prepare(url=gl.url, auth=gl._auth)
assert gl.private_token == "private_token"
assert gl.oauth_token is None
assert gl.job_token is None
assert isinstance(gl._auth, PrivateTokenAuth)
assert gl._auth.token == "private_token"
assert p.headers["PRIVATE-TOKEN"] == "private_token"
assert "JOB-TOKEN" not in p.headers
assert "Authorization" not in p.headers
def test_oauth_token_auth():
gl = Gitlab("http://localhost", oauth_token="oauth_token", api_version="4")
p = PreparedRequest()
p.prepare(url=gl.url, auth=gl._auth)
assert gl.private_token is None
assert gl.oauth_token == "oauth_token"
assert gl.job_token is None
assert isinstance(gl._auth, OAuthTokenAuth)
assert gl._auth.token == "oauth_token"
assert p.headers["Authorization"] == "Bearer oauth_token"
assert "PRIVATE-TOKEN" not in p.headers
assert "JOB-TOKEN" not in p.headers
def test_job_token_auth():
gl = Gitlab("http://localhost", job_token="CI_JOB_TOKEN", api_version="4")
p = PreparedRequest()
p.prepare(url=gl.url, auth=gl._auth)
assert gl.private_token is None
assert gl.oauth_token is None
assert gl.job_token == "CI_JOB_TOKEN"
assert isinstance(gl._auth, JobTokenAuth)
assert gl._auth.token == "CI_JOB_TOKEN"
assert p.headers["JOB-TOKEN"] == "CI_JOB_TOKEN"
assert "PRIVATE-TOKEN" not in p.headers
assert "Authorization" not in p.headers
def test_http_auth():
gl = Gitlab(
"http://localhost",
http_username="foo",
http_password="bar",
api_version="4",
)
p = PreparedRequest()
p.prepare(url=gl.url, auth=gl._auth)
assert gl.private_token is None
assert gl.oauth_token is None
assert gl.job_token is None
assert isinstance(gl._auth, requests.auth.HTTPBasicAuth)
assert gl._auth.username == "foo"
assert gl._auth.password == "bar"
assert p.headers["Authorization"] == "Basic Zm9vOmJhcg=="
assert "PRIVATE-TOKEN" not in p.headers
assert "JOB-TOKEN" not in p.headers
@responses.activate
def test_with_no_auth_uses_netrc_file(netrc):
responses.get(
url="http://localhost/api/v4/test",
match=[
responses.matchers.header_matcher({"Authorization": "Basic dGVzdDp0ZXN0"})
],
)
gl = Gitlab("http://localhost")
gl.http_get("/test")
@responses.activate
def test_with_auth_ignores_netrc_file(netrc):
responses.get(
url="http://localhost/api/v4/test",
match=[responses.matchers.header_matcher({"Authorization": "Bearer test"})],
)
gl = Gitlab("http://localhost", oauth_token="test")
gl.http_get("/test")
@pytest.mark.parametrize(
"options,config,expected_private_token,expected_oauth_token,expected_job_token",
[
(
{
"private_token": "options-private-token",
"oauth_token": "options-oauth-token",
"job_token": "options-job-token",
},
{
"private_token": "config-private-token",
"oauth_token": "config-oauth-token",
"job_token": "config-job-token",
},
"options-private-token",
None,
None,
),
(
{
"private_token": None,
"oauth_token": "options-oauth-token",
"job_token": "options-job-token",
},
{
"private_token": "config-private-token",
"oauth_token": "config-oauth-token",
"job_token": "config-job-token",
},
"config-private-token",
None,
None,
),
(
{
"private_token": None,
"oauth_token": None,
"job_token": "options-job-token",
},
{
"private_token": "config-private-token",
"oauth_token": "config-oauth-token",
"job_token": "config-job-token",
},
"config-private-token",
None,
None,
),
(
{
"private_token": None,
"oauth_token": None,
"job_token": None,
},
{
"private_token": "config-private-token",
"oauth_token": "config-oauth-token",
"job_token": "config-job-token",
},
"config-private-token",
None,
None,
),
(
{
"private_token": None,
"oauth_token": None,
"job_token": None,
},
{
"private_token": None,
"oauth_token": "config-oauth-token",
"job_token": "config-job-token",
},
None,
"config-oauth-token",
None,
),
(
{
"private_token": None,
"oauth_token": None,
"job_token": None,
},
{
"private_token": None,
"oauth_token": None,
"job_token": "config-job-token",
},
None,
None,
"config-job-token",
),
],
)
def test_merge_auth(
options,
config,
expected_private_token,
expected_oauth_token,
expected_job_token,
):
cp = GitlabConfigParser()
cp.private_token = config["private_token"]
cp.oauth_token = config["oauth_token"]
cp.job_token = config["job_token"]
private_token, oauth_token, job_token = Gitlab._merge_auth(options, cp)
assert private_token == expected_private_token
assert oauth_token == expected_oauth_token
assert job_token == expected_job_token
| 7,347 | Python | .py | 225 | 23.391111 | 86 | 0.558811 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,152 | test_utils.py | python-gitlab_python-gitlab/tests/unit/test_utils.py | import json
import logging
import warnings
import pytest
import requests
import responses
from gitlab import types, utils
@pytest.mark.parametrize(
"content_type,expected_type",
[
("application/json", "application/json"),
("application/json; charset=utf-8", "application/json"),
("", "text/plain"),
(None, "text/plain"),
],
)
def test_get_content_type(content_type, expected_type):
parsed_type = utils.get_content_type(content_type)
assert parsed_type == expected_type
@responses.activate
def test_response_content(capsys):
responses.add(
method="GET",
url="https://example.com",
status=200,
body="test",
content_type="application/octet-stream",
)
resp = requests.get("https://example.com", stream=True)
utils.response_content(
resp, streamed=True, action=None, chunk_size=1024, iterator=False
)
captured = capsys.readouterr()
assert "test" in captured.out
class TestEncodedId:
def test_init_str(self):
obj = utils.EncodedId("Hello")
assert "Hello" == obj
assert "Hello" == str(obj)
assert "Hello" == f"{obj}"
assert isinstance(obj, utils.EncodedId)
obj = utils.EncodedId("this/is a/path")
assert "this%2Fis%20a%2Fpath" == str(obj)
assert "this%2Fis%20a%2Fpath" == f"{obj}"
assert isinstance(obj, utils.EncodedId)
def test_init_int(self):
obj = utils.EncodedId(23)
assert "23" == obj
assert "23" == f"{obj}"
assert isinstance(obj, utils.EncodedId)
def test_init_invalid_type_raises(self):
with pytest.raises(TypeError):
utils.EncodedId(None)
def test_init_encodeid_str(self):
value = "Goodbye"
obj_init = utils.EncodedId(value)
obj = utils.EncodedId(obj_init)
assert value == str(obj)
assert value == f"{obj}"
value = "we got/a/path"
expected = "we%20got%2Fa%2Fpath"
obj_init = utils.EncodedId(value)
assert expected == str(obj_init)
assert expected == f"{obj_init}"
# Show that no matter how many times we recursively call it we still only
# URL-encode it once.
obj = utils.EncodedId(
utils.EncodedId(utils.EncodedId(utils.EncodedId(utils.EncodedId(obj_init))))
)
assert expected == str(obj)
assert expected == f"{obj}"
# Show assignments still only encode once
obj2 = obj
assert expected == str(obj2)
assert expected == f"{obj2}"
def test_init_encodeid_int(self):
value = 23
expected = f"{value}"
obj_init = utils.EncodedId(value)
obj = utils.EncodedId(obj_init)
assert expected == str(obj)
assert expected == f"{obj}"
def test_json_serializable(self):
obj = utils.EncodedId("someone")
assert '"someone"' == json.dumps(obj)
obj = utils.EncodedId("we got/a/path")
assert '"we%20got%2Fa%2Fpath"' == json.dumps(obj)
class TestWarningsWrapper:
def test_warn(self):
warn_message = "short and stout"
warn_source = "teapot"
with warnings.catch_warnings(record=True) as caught_warnings:
utils.warn(message=warn_message, category=UserWarning, source=warn_source)
assert len(caught_warnings) == 1
warning = caught_warnings[0]
# File name is this file as it is the first file outside of the `gitlab/` path.
assert __file__ == warning.filename
assert warning.category == UserWarning
assert isinstance(warning.message, UserWarning)
assert warn_message in str(warning.message)
assert __file__ in str(warning.message)
assert warn_source == warning.source
def test_warn_no_show_caller(self):
warn_message = "short and stout"
warn_source = "teapot"
with warnings.catch_warnings(record=True) as caught_warnings:
utils.warn(
message=warn_message,
category=UserWarning,
source=warn_source,
show_caller=False,
)
assert len(caught_warnings) == 1
warning = caught_warnings[0]
# File name is this file as it is the first file outside of the `gitlab/` path.
assert __file__ == warning.filename
assert warning.category == UserWarning
assert isinstance(warning.message, UserWarning)
assert warn_message in str(warning.message)
assert __file__ not in str(warning.message)
assert warn_source == warning.source
@pytest.mark.parametrize(
"source,expected",
[
({"a": "", "b": "spam", "c": None}, {"a": "", "b": "spam", "c": None}),
({"a": "", "b": {"c": "spam"}}, {"a": "", "b[c]": "spam"}),
],
)
def test_copy_dict(source, expected):
dest = {}
utils.copy_dict(src=source, dest=dest)
assert dest == expected
@pytest.mark.parametrize(
"dictionary,expected",
[
({"a": None, "b": "spam"}, {"b": "spam"}),
({"a": "", "b": "spam"}, {"a": "", "b": "spam"}),
({"a": None, "b": None}, {}),
],
)
def test_remove_none_from_dict(dictionary, expected):
result = utils.remove_none_from_dict(dictionary)
assert result == expected
def test_transform_types_copies_data_with_empty_files():
data = {"attr": "spam"}
new_data, files = utils._transform_types(data, {}, transform_data=True)
assert new_data is not data
assert new_data == data
assert files == {}
def test_transform_types_with_transform_files_populates_files():
custom_types = {"attr": types.FileAttribute}
data = {"attr": "spam"}
new_data, files = utils._transform_types(data, custom_types, transform_data=True)
assert new_data == {}
assert files["attr"] == ("attr", "spam")
def test_transform_types_without_transform_files_populates_data_with_empty_files():
custom_types = {"attr": types.FileAttribute}
data = {"attr": "spam"}
new_data, files = utils._transform_types(
data, custom_types, transform_files=False, transform_data=True
)
assert new_data == {"attr": "spam"}
assert files == {}
def test_transform_types_params_array():
data = {"attr": [1, 2, 3]}
custom_types = {"attr": types.ArrayAttribute}
new_data, files = utils._transform_types(data, custom_types, transform_data=True)
assert new_data is not data
assert new_data == {"attr[]": [1, 2, 3]}
assert files == {}
def test_transform_types_not_params_array():
data = {"attr": [1, 2, 3]}
custom_types = {"attr": types.ArrayAttribute}
new_data, files = utils._transform_types(data, custom_types, transform_data=False)
assert new_data is not data
assert new_data == data
assert files == {}
def test_masking_formatter_masks_token(capsys: pytest.CaptureFixture):
token = "glpat-private-token"
logger = logging.getLogger()
handler = logging.StreamHandler()
handler.setFormatter(utils.MaskingFormatter(masked=token))
logger.handlers.clear()
logger.addHandler(handler)
logger.info(token)
captured = capsys.readouterr()
assert "[MASKED]" in captured.err
assert token not in captured.err
| 7,272 | Python | .py | 188 | 31.718085 | 88 | 0.63113 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,153 | test_exceptions.py | python-gitlab_python-gitlab/tests/unit/test_exceptions.py | import pytest
from gitlab import exceptions
@pytest.mark.parametrize(
"kwargs,expected",
[
({"error_message": "foo"}, "foo"),
({"error_message": "foo", "response_code": "400"}, "400: foo"),
],
)
def test_gitlab_error(kwargs, expected):
error = exceptions.GitlabError(**kwargs)
assert str(error) == expected
def test_error_raises_from_http_error():
"""Methods decorated with @on_http_error should raise from GitlabHttpError."""
class TestError(Exception):
pass
@exceptions.on_http_error(TestError)
def raise_error_from_http_error():
raise exceptions.GitlabHttpError
with pytest.raises(TestError) as context:
raise_error_from_http_error()
assert isinstance(context.value.__cause__, exceptions.GitlabHttpError)
| 800 | Python | .py | 22 | 31.181818 | 82 | 0.692208 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,154 | test_retry.py | python-gitlab_python-gitlab/tests/unit/test_retry.py | import time
from unittest import mock
import pytest
from gitlab import utils
def test_handle_retry_on_status_ignores_unknown_status_code():
retry = utils.Retry(max_retries=1, retry_transient_errors=True)
assert retry.handle_retry_on_status(418) is False
def test_handle_retry_on_status_accepts_retry_after_header(
monkeypatch: pytest.MonkeyPatch,
):
mock_sleep = mock.Mock()
monkeypatch.setattr(time, "sleep", mock_sleep)
retry = utils.Retry(max_retries=1)
headers = {"Retry-After": "1"}
assert retry.handle_retry_on_status(429, headers=headers) is True
assert isinstance(mock_sleep.call_args[0][0], int)
def test_handle_retry_on_status_accepts_ratelimit_reset_header(
monkeypatch: pytest.MonkeyPatch,
):
mock_sleep = mock.Mock()
monkeypatch.setattr(time, "sleep", mock_sleep)
retry = utils.Retry(max_retries=1)
headers = {"RateLimit-Reset": str(int(time.time() + 1))}
assert retry.handle_retry_on_status(429, headers=headers) is True
assert isinstance(mock_sleep.call_args[0][0], float)
def test_handle_retry_on_status_returns_false_when_max_retries_reached():
retry = utils.Retry(max_retries=0)
assert retry.handle_retry_on_status(429) is False
| 1,232 | Python | .py | 28 | 39.964286 | 73 | 0.742233 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,155 | test_gitlab_http_methods.py | python-gitlab_python-gitlab/tests/unit/test_gitlab_http_methods.py | import copy
import warnings
import pytest
import requests
import responses
from gitlab import GitlabHttpError, GitlabList, GitlabParsingError, RedirectError
from gitlab.const import RETRYABLE_TRANSIENT_ERROR_CODES
from tests.unit import helpers
def test_build_url(gl):
r = gl._build_url("http://localhost/api/v4")
assert r == "http://localhost/api/v4"
r = gl._build_url("https://localhost/api/v4")
assert r == "https://localhost/api/v4"
r = gl._build_url("/projects")
assert r == "http://localhost/api/v4/projects"
@responses.activate
def test_http_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.GET,
url=url,
json=[{"name": "project1"}],
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
http_r = gl.http_request("get", "/projects")
http_r.json()
assert http_r.status_code == 200
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_http_request_with_url_encoded_kwargs_does_not_duplicate_params(gl):
url = "http://localhost/api/v4/projects?topics%5B%5D=python"
responses.add(
method=responses.GET,
url=url,
json=[{"name": "project1"}],
status=200,
match=[responses.matchers.query_param_matcher({"topics[]": "python"})],
)
kwargs = {"topics[]": "python"}
http_r = gl.http_request("get", "/projects?topics%5B%5D=python", **kwargs)
http_r.json()
assert http_r.status_code == 200
assert responses.assert_call_count(url, 1)
@responses.activate
def test_http_request_404(gl):
url = "http://localhost/api/v4/not_there"
responses.add(
method=responses.GET,
url=url,
json={},
status=400,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_request("get", "/not_there")
assert responses.assert_call_count(url, 1) is True
@responses.activate
@pytest.mark.parametrize("status_code", RETRYABLE_TRANSIENT_ERROR_CODES)
def test_http_request_with_only_failures(gl, status_code):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.GET,
url=url,
json={},
status=status_code,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_request("get", "/projects")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_http_request_with_retry_on_method_for_transient_failures(gl):
call_count = 0
calls_before_success = 3
url = "http://localhost/api/v4/projects"
def request_callback(request):
nonlocal call_count
call_count += 1
status_code = 200 if call_count >= calls_before_success else 500
headers = {}
body = "[]"
return (status_code, headers, body)
responses.add_callback(
method=responses.GET,
url=url,
callback=request_callback,
content_type="application/json",
)
http_r = gl.http_request("get", "/projects", retry_transient_errors=True)
assert http_r.status_code == 200
assert len(responses.calls) == calls_before_success
@responses.activate
@pytest.mark.parametrize(
"exception",
[
requests.ConnectionError("Connection aborted."),
requests.exceptions.ChunkedEncodingError("Connection broken."),
],
)
def test_http_request_with_retry_on_method_for_transient_network_failures(
gl, exception
):
call_count = 0
calls_before_success = 3
url = "http://localhost/api/v4/projects"
def request_callback(request):
nonlocal call_count
call_count += 1
status_code = 200
headers = {}
body = "[]"
if call_count >= calls_before_success:
return (status_code, headers, body)
raise exception
responses.add_callback(
method=responses.GET,
url=url,
callback=request_callback,
content_type="application/json",
)
http_r = gl.http_request("get", "/projects", retry_transient_errors=True)
assert http_r.status_code == 200
assert len(responses.calls) == calls_before_success
@responses.activate
def test_http_request_with_retry_on_class_for_transient_failures(gl_retry):
call_count = 0
calls_before_success = 3
url = "http://localhost/api/v4/projects"
def request_callback(request: requests.models.PreparedRequest):
nonlocal call_count
call_count += 1
status_code = 200 if call_count >= calls_before_success else 500
headers = {}
body = "[]"
return (status_code, headers, body)
responses.add_callback(
method=responses.GET,
url=url,
callback=request_callback,
content_type="application/json",
)
http_r = gl_retry.http_request("get", "/projects", retry_transient_errors=True)
assert http_r.status_code == 200
assert len(responses.calls) == calls_before_success
@responses.activate
def test_http_request_with_retry_on_class_for_transient_network_failures(gl_retry):
call_count = 0
calls_before_success = 3
url = "http://localhost/api/v4/projects"
def request_callback(request: requests.models.PreparedRequest):
nonlocal call_count
call_count += 1
status_code = 200
headers = {}
body = "[]"
if call_count >= calls_before_success:
return (status_code, headers, body)
raise requests.ConnectionError("Connection aborted.")
responses.add_callback(
method=responses.GET,
url=url,
callback=request_callback,
content_type="application/json",
)
http_r = gl_retry.http_request("get", "/projects", retry_transient_errors=True)
assert http_r.status_code == 200
assert len(responses.calls) == calls_before_success
@responses.activate
def test_http_request_with_retry_on_class_and_method_for_transient_failures(gl_retry):
call_count = 0
calls_before_success = 3
url = "http://localhost/api/v4/projects"
def request_callback(request):
nonlocal call_count
call_count += 1
status_code = 200 if call_count >= calls_before_success else 500
headers = {}
body = "[]"
return (status_code, headers, body)
responses.add_callback(
method=responses.GET,
url=url,
callback=request_callback,
content_type="application/json",
)
with pytest.raises(GitlabHttpError):
gl_retry.http_request("get", "/projects", retry_transient_errors=False)
assert len(responses.calls) == 1
@responses.activate
def test_http_request_with_retry_on_class_and_method_for_transient_network_failures(
gl_retry,
):
call_count = 0
calls_before_success = 3
url = "http://localhost/api/v4/projects"
def request_callback(request):
nonlocal call_count
call_count += 1
status_code = 200
headers = {}
body = "[]"
if call_count >= calls_before_success:
return (status_code, headers, body)
raise requests.ConnectionError("Connection aborted.")
responses.add_callback(
method=responses.GET,
url=url,
callback=request_callback,
content_type="application/json",
)
with pytest.raises(requests.ConnectionError):
gl_retry.http_request("get", "/projects", retry_transient_errors=False)
assert len(responses.calls) == 1
def create_redirect_response(
*, response: requests.models.Response, http_method: str, api_path: str
) -> requests.models.Response:
"""Create a Requests response object that has a redirect in it"""
assert api_path.startswith("/")
http_method = http_method.upper()
# Create a history which contains our original request which is redirected
history = [
helpers.httmock_response(
status_code=302,
content="",
headers={"Location": f"http://example.com/api/v4{api_path}"},
reason="Moved Temporarily",
request=response.request,
)
]
# Create a "prepped" Request object to be the final redirect. The redirect
# will be a "GET" method as Requests changes the method to "GET" when there
# is a 301/302 redirect code.
req = requests.Request(
method="GET",
url=f"http://example.com/api/v4{api_path}",
)
prepped = req.prepare()
resp_obj = helpers.httmock_response(
status_code=200,
content="",
headers={},
reason="OK",
elapsed=5,
request=prepped,
)
resp_obj.history = history
return resp_obj
def test_http_request_302_get_does_not_raise(gl):
"""Test to show that a redirect of a GET will not cause an error"""
method = "get"
api_path = "/user/status"
url = f"http://localhost/api/v4{api_path}"
def response_callback(
response: requests.models.Response,
) -> requests.models.Response:
return create_redirect_response(
response=response, http_method=method, api_path=api_path
)
with responses.RequestsMock(response_callback=response_callback) as req_mock:
req_mock.add(
method=responses.GET,
url=url,
status=302,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
gl.http_request(verb=method, path=api_path)
def test_http_request_302_put_raises_redirect_error(gl):
"""Test to show that a redirect of a PUT will cause an error"""
method = "put"
api_path = "/user/status"
url = f"http://localhost/api/v4{api_path}"
def response_callback(
response: requests.models.Response,
) -> requests.models.Response:
return create_redirect_response(
response=response, http_method=method, api_path=api_path
)
with responses.RequestsMock(response_callback=response_callback) as req_mock:
req_mock.add(
method=responses.PUT,
url=url,
status=302,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(RedirectError) as exc:
gl.http_request(verb=method, path=api_path)
error_message = exc.value.error_message
assert "Moved Temporarily" in error_message
assert "http://localhost/api/v4/user/status" in error_message
assert "http://example.com/api/v4/user/status" in error_message
def test_http_request_on_409_resource_lock_retries(gl_retry):
url = "http://localhost/api/v4/user"
retried = False
def response_callback(
response: requests.models.Response,
) -> requests.models.Response:
"""We need a callback that adds a resource lock reason only on first call"""
nonlocal retried
if not retried:
response.reason = "Resource lock"
retried = True
return response
with responses.RequestsMock(response_callback=response_callback) as rsps:
rsps.add(
method=responses.GET,
url=url,
status=409,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
rsps.add(
method=responses.GET,
url=url,
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
response = gl_retry.http_request("get", "/user")
assert response.status_code == 200
def test_http_request_on_409_resource_lock_without_retry_raises(gl):
url = "http://localhost/api/v4/user"
def response_callback(
response: requests.models.Response,
) -> requests.models.Response:
"""Without retry, this will fail on the first call"""
response.reason = "Resource lock"
return response
with responses.RequestsMock(response_callback=response_callback) as req_mock:
req_mock.add(
method=responses.GET,
url=url,
status=409,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError) as excinfo:
gl.http_request("get", "/user")
assert excinfo.value.response_code == 409
@responses.activate
def test_get_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.GET,
url=url,
json={"name": "project1"},
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_get("/projects")
assert isinstance(result, dict)
assert result["name"] == "project1"
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_get_request_raw(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.GET,
url=url,
content_type="application/octet-stream",
body="content",
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_get("/projects")
assert result.content.decode("utf-8") == "content"
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_get_request_404(gl):
url = "http://localhost/api/v4/not_there"
responses.add(
method=responses.GET,
url=url,
json=[],
status=404,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_get("/not_there")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_get_request_invalid_data(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.GET,
url=url,
body='["name": "project1"]',
content_type="application/json",
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabParsingError):
result = gl.http_get("/projects")
print(type(result))
print(result.content)
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_head_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.HEAD,
url=url,
headers={"X-Total": "1"},
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_head("/projects")
assert isinstance(result, requests.structures.CaseInsensitiveDict)
assert result["X-Total"] == "1"
@responses.activate
def test_list_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.GET,
url=url,
json=[{"name": "project1"}],
headers={"X-Total": "1"},
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with warnings.catch_warnings(record=True) as caught_warnings:
result = gl.http_list("/projects", iterator=False)
assert len(caught_warnings) == 0
assert isinstance(result, list)
assert len(result) == 1
result = gl.http_list("/projects", iterator=True)
assert isinstance(result, GitlabList)
assert len(list(result)) == 1
result = gl.http_list("/projects", get_all=True)
assert isinstance(result, list)
assert len(result) == 1
assert responses.assert_call_count(url, 3) is True
@responses.activate
def test_list_request_page_and_iterator(gl):
response_dict = copy.deepcopy(large_list_response)
response_dict["match"] = [responses.matchers.query_param_matcher({"page": "1"})]
responses.add(**response_dict)
with pytest.warns(
UserWarning, match="`iterator=True` and `page=1` were both specified"
):
result = gl.http_list("/projects", iterator=True, page=1)
assert isinstance(result, list)
assert len(result) == 20
assert len(responses.calls) == 1
large_list_response = {
"method": responses.GET,
"url": "http://localhost/api/v4/projects",
"json": [
{"name": "project01"},
{"name": "project02"},
{"name": "project03"},
{"name": "project04"},
{"name": "project05"},
{"name": "project06"},
{"name": "project07"},
{"name": "project08"},
{"name": "project09"},
{"name": "project10"},
{"name": "project11"},
{"name": "project12"},
{"name": "project13"},
{"name": "project14"},
{"name": "project15"},
{"name": "project16"},
{"name": "project17"},
{"name": "project18"},
{"name": "project19"},
{"name": "project20"},
],
"headers": {"X-Total": "30", "x-per-page": "20"},
"status": 200,
"match": helpers.MATCH_EMPTY_QUERY_PARAMS,
}
@responses.activate
def test_list_request_pagination_warning(gl):
responses.add(**large_list_response)
with warnings.catch_warnings(record=True) as caught_warnings:
result = gl.http_list("/projects", iterator=False)
assert len(caught_warnings) == 1
warning = caught_warnings[0]
assert isinstance(warning.message, UserWarning)
message = str(warning.message)
assert "Calling a `list()` method" in message
assert "python-gitlab.readthedocs.io" in message
assert __file__ in message
assert __file__ == warning.filename
assert isinstance(result, list)
assert len(result) == 20
assert len(responses.calls) == 1
@responses.activate
def test_list_request_iterator_true_nowarning(gl):
responses.add(**large_list_response)
with warnings.catch_warnings(record=True) as caught_warnings:
result = gl.http_list("/projects", iterator=True)
assert len(caught_warnings) == 0
assert isinstance(result, GitlabList)
assert len(list(result)) == 20
assert len(responses.calls) == 1
@responses.activate
def test_list_request_all_true_nowarning(gl):
responses.add(**large_list_response)
with warnings.catch_warnings(record=True) as caught_warnings:
result = gl.http_list("/projects", get_all=True)
assert len(caught_warnings) == 0
assert isinstance(result, list)
assert len(result) == 20
assert len(responses.calls) == 1
@responses.activate
def test_list_request_all_false_nowarning(gl):
responses.add(**large_list_response)
with warnings.catch_warnings(record=True) as caught_warnings:
result = gl.http_list("/projects", all=False)
assert len(caught_warnings) == 0
assert isinstance(result, list)
assert len(result) == 20
assert len(responses.calls) == 1
@responses.activate
def test_list_request_page_nowarning(gl):
response_dict = copy.deepcopy(large_list_response)
response_dict["match"] = [responses.matchers.query_param_matcher({"page": "1"})]
responses.add(**response_dict)
with warnings.catch_warnings(record=True) as caught_warnings:
gl.http_list("/projects", page=1)
assert len(caught_warnings) == 0
assert len(responses.calls) == 1
@responses.activate
def test_list_request_404(gl):
url = "http://localhost/api/v4/not_there"
responses.add(
method=responses.GET,
url=url,
json=[],
status=404,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_list("/not_there")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_list_request_invalid_data(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.GET,
url=url,
body='["name": "project1"]',
content_type="application/json",
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabParsingError):
gl.http_list("/projects")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_post_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.POST,
url=url,
json={"name": "project1"},
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_post("/projects")
assert isinstance(result, dict)
assert result["name"] == "project1"
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_post_request_404(gl):
url = "http://localhost/api/v4/not_there"
responses.add(
method=responses.POST,
url=url,
json=[],
status=404,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_post("/not_there")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_post_request_invalid_data(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.POST,
url=url,
content_type="application/json",
body='["name": "project1"]',
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabParsingError):
gl.http_post("/projects")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_put_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.PUT,
url=url,
json={"name": "project1"},
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_put("/projects")
assert isinstance(result, dict)
assert result["name"] == "project1"
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_put_request_404(gl):
url = "http://localhost/api/v4/not_there"
responses.add(
method=responses.PUT,
url=url,
json=[],
status=404,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_put("/not_there")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_put_request_204(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.PUT,
url=url,
status=204,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_put("/projects")
assert isinstance(result, requests.Response)
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_put_request_invalid_data(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.PUT,
url=url,
body='["name": "project1"]',
content_type="application/json",
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabParsingError):
gl.http_put("/projects")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_patch_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.PATCH,
url=url,
json={"name": "project1"},
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_patch("/projects")
assert isinstance(result, dict)
assert result["name"] == "project1"
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_patch_request_204(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.PATCH,
url=url,
status=204,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_patch("/projects")
assert isinstance(result, requests.Response)
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_patch_request_404(gl):
url = "http://localhost/api/v4/not_there"
responses.add(
method=responses.PATCH,
url=url,
json=[],
status=404,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_patch("/not_there")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_patch_request_invalid_data(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.PATCH,
url=url,
body='["name": "project1"]',
content_type="application/json",
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabParsingError):
gl.http_patch("/projects")
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_delete_request(gl):
url = "http://localhost/api/v4/projects"
responses.add(
method=responses.DELETE,
url=url,
json=True,
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
result = gl.http_delete("/projects")
assert isinstance(result, requests.Response)
assert result.json() is True
assert responses.assert_call_count(url, 1) is True
@responses.activate
def test_delete_request_404(gl):
url = "http://localhost/api/v4/not_there"
responses.add(
method=responses.DELETE,
url=url,
json=[],
status=404,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
with pytest.raises(GitlabHttpError):
gl.http_delete("/not_there")
assert responses.assert_call_count(url, 1) is True
| 25,196 | Python | .py | 723 | 28.22545 | 86 | 0.653936 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,156 | test_config.py | python-gitlab_python-gitlab/tests/unit/test_config.py | import io
import sys
from pathlib import Path
from textwrap import dedent
from unittest import mock
import pytest
import gitlab
from gitlab import config, const
custom_user_agent = "my-package/1.0.0"
valid_config = """[global]
default = one
ssl_verify = true
timeout = 2
[one]
url = http://one.url
private_token = ABCDEF
[two]
url = https://two.url
private_token = GHIJKL
ssl_verify = false
timeout = 10
[three]
url = https://three.url
private_token = MNOPQR
ssl_verify = /path/to/CA/bundle.crt
per_page = 50
[four]
url = https://four.url
oauth_token = STUV
"""
ssl_verify_str_config = """[global]
default = one
ssl_verify = /etc/ssl/certs/ca-certificates.crt
[one]
url = http://one.url
private_token = ABCDEF
"""
custom_user_agent_config = f"""[global]
default = one
user_agent = {custom_user_agent}
[one]
url = http://one.url
private_token = ABCDEF
"""
no_default_config = """[global]
[there]
url = http://there.url
private_token = ABCDEF
"""
invalid_data_config = """[global]
[one]
url = http://one.url
[two]
private_token = ABCDEF
[three]
meh = hem
[four]
url = http://four.url
private_token = ABCDEF
per_page = 200
[invalid-api-version]
url = http://invalid-api-version.url
private_token = ABCDEF
api_version = 1
"""
@pytest.fixture(autouse=True)
def default_files(monkeypatch):
"""Overrides mocked default files from conftest.py as we have our own mocks here."""
monkeypatch.setattr(gitlab.config, "_DEFAULT_FILES", config._DEFAULT_FILES)
def global_retry_transient_errors(value: bool) -> str:
return f"""[global]
default = one
retry_transient_errors={value}
[one]
url = http://one.url
private_token = ABCDEF"""
def global_and_gitlab_retry_transient_errors(
global_value: bool, gitlab_value: bool
) -> str:
return f"""[global]
default = one
retry_transient_errors={global_value}
[one]
url = http://one.url
private_token = ABCDEF
retry_transient_errors={gitlab_value}"""
def _mock_nonexistent_file(*args, **kwargs):
raise OSError
def _mock_existent_file(path, *args, **kwargs):
return path
def test_env_config_missing_file_raises(monkeypatch):
monkeypatch.setenv("PYTHON_GITLAB_CFG", "/some/path")
with pytest.raises(config.GitlabConfigMissingError):
config._get_config_files()
def test_env_config_not_defined_does_not_raise(monkeypatch):
with monkeypatch.context() as m:
m.setattr(config, "_DEFAULT_FILES", [])
assert config._get_config_files() == []
def test_default_config(monkeypatch):
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_nonexistent_file)
cp = config.GitlabConfigParser()
assert cp.gitlab_id is None
assert cp.http_username is None
assert cp.http_password is None
assert cp.job_token is None
assert cp.oauth_token is None
assert cp.private_token is None
assert cp.api_version == "4"
assert cp.order_by is None
assert cp.pagination is None
assert cp.per_page is None
assert cp.retry_transient_errors is False
assert cp.ssl_verify is True
assert cp.timeout == 60
assert cp.url is None
assert cp.user_agent == const.USER_AGENT
@mock.patch("builtins.open")
def test_invalid_id(m_open, monkeypatch):
fd = io.StringIO(no_default_config)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
config.GitlabConfigParser("there")
with pytest.raises(config.GitlabIDError):
config.GitlabConfigParser()
fd = io.StringIO(valid_config)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with pytest.raises(config.GitlabDataError):
config.GitlabConfigParser(gitlab_id="not_there")
@mock.patch("builtins.open")
def test_invalid_data(m_open, monkeypatch):
fd = io.StringIO(invalid_data_config)
fd.close = mock.Mock(return_value=None, side_effect=lambda: fd.seek(0))
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
config.GitlabConfigParser("one")
config.GitlabConfigParser("one")
with pytest.raises(config.GitlabDataError):
config.GitlabConfigParser(gitlab_id="two")
with pytest.raises(config.GitlabDataError):
config.GitlabConfigParser(gitlab_id="three")
with pytest.raises(config.GitlabDataError) as e:
config.GitlabConfigParser("four")
assert str(e.value) == "Unsupported per_page number: 200"
with pytest.raises(config.GitlabDataError) as e:
config.GitlabConfigParser("invalid-api-version")
assert str(e.value) == "Unsupported API version: 1"
@mock.patch("builtins.open")
def test_valid_data(m_open, monkeypatch):
fd = io.StringIO(valid_config)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser()
assert "one" == cp.gitlab_id
assert "http://one.url" == cp.url
assert "ABCDEF" == cp.private_token
assert cp.oauth_token is None
assert 2 == cp.timeout
assert cp.ssl_verify is True
assert cp.per_page is None
fd = io.StringIO(valid_config)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser(gitlab_id="two")
assert "two" == cp.gitlab_id
assert "https://two.url" == cp.url
assert "GHIJKL" == cp.private_token
assert cp.oauth_token is None
assert 10 == cp.timeout
assert cp.ssl_verify is False
fd = io.StringIO(valid_config)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser(gitlab_id="three")
assert "three" == cp.gitlab_id
assert "https://three.url" == cp.url
assert "MNOPQR" == cp.private_token
assert cp.oauth_token is None
assert 2 == cp.timeout
assert "/path/to/CA/bundle.crt" == cp.ssl_verify
assert 50 == cp.per_page
fd = io.StringIO(valid_config)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser(gitlab_id="four")
assert "four" == cp.gitlab_id
assert "https://four.url" == cp.url
assert cp.private_token is None
assert "STUV" == cp.oauth_token
assert 2 == cp.timeout
assert cp.ssl_verify is True
@mock.patch("builtins.open")
def test_ssl_verify_as_str(m_open, monkeypatch):
fd = io.StringIO(ssl_verify_str_config)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser()
assert cp.ssl_verify == "/etc/ssl/certs/ca-certificates.crt"
@mock.patch("builtins.open")
@pytest.mark.skipif(sys.platform.startswith("win"), reason="Not supported on Windows")
def test_data_from_helper(m_open, monkeypatch, tmp_path):
helper = tmp_path / "helper.sh"
helper.write_text(
dedent(
"""\
#!/bin/sh
echo "secret"
"""
),
encoding="utf-8",
)
helper.chmod(0o755)
fd = io.StringIO(
dedent(
f"""\
[global]
default = helper
[helper]
url = https://helper.url
oauth_token = helper: {helper}
"""
)
)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser(gitlab_id="helper")
assert "helper" == cp.gitlab_id
assert "https://helper.url" == cp.url
assert cp.private_token is None
assert "secret" == cp.oauth_token
@mock.patch("builtins.open")
@pytest.mark.skipif(sys.platform.startswith("win"), reason="Not supported on Windows")
def test_from_helper_subprocess_error_raises_error(m_open, monkeypatch):
# using false here to force a non-zero return code
fd = io.StringIO(
dedent(
"""\
[global]
default = helper
[helper]
url = https://helper.url
oauth_token = helper: false
"""
)
)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
with pytest.raises(config.GitlabConfigHelperError) as e:
config.GitlabConfigParser(gitlab_id="helper")
assert "Failed to read oauth_token value from helper" in str(e.value)
@mock.patch("builtins.open")
@pytest.mark.parametrize(
"config_string,expected_agent",
[
(valid_config, gitlab.const.USER_AGENT),
(custom_user_agent_config, custom_user_agent),
],
)
def test_config_user_agent(m_open, monkeypatch, config_string, expected_agent):
fd = io.StringIO(config_string)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser()
assert cp.user_agent == expected_agent
@mock.patch("builtins.open")
@pytest.mark.parametrize(
"config_string,expected",
[
pytest.param(valid_config, False, id="default_value"),
pytest.param(
global_retry_transient_errors(True), True, id="global_config_true"
),
pytest.param(
global_retry_transient_errors(False), False, id="global_config_false"
),
pytest.param(
global_and_gitlab_retry_transient_errors(False, True),
True,
id="gitlab_overrides_global_true",
),
pytest.param(
global_and_gitlab_retry_transient_errors(True, False),
False,
id="gitlab_overrides_global_false",
),
pytest.param(
global_and_gitlab_retry_transient_errors(True, True),
True,
id="gitlab_equals_global_true",
),
pytest.param(
global_and_gitlab_retry_transient_errors(False, False),
False,
id="gitlab_equals_global_false",
),
],
)
def test_config_retry_transient_errors_when_global_config_is_set(
m_open, monkeypatch, config_string, expected
):
fd = io.StringIO(config_string)
fd.close = mock.Mock(return_value=None)
m_open.return_value = fd
with monkeypatch.context() as m:
m.setattr(Path, "resolve", _mock_existent_file)
cp = config.GitlabConfigParser()
assert cp.retry_transient_errors == expected
| 11,083 | Python | .py | 327 | 28.235474 | 88 | 0.665263 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,157 | helpers.py | python-gitlab_python-gitlab/tests/unit/helpers.py | import datetime
import io
import json
from typing import Optional
import requests
import responses
from gitlab import base
MATCH_EMPTY_QUERY_PARAMS = [responses.matchers.query_param_matcher({})]
class FakeObject(base.RESTObject):
pass
class FakeObjectWithoutId(base.RESTObject):
_id_attr = None
class FakeObjectWithLongRepr(base.RESTObject):
_id_attr = None
_repr_attr = "test"
class OtherFakeObject(FakeObject):
_id_attr = "foo"
class FakeManager(base.RESTManager):
_path = "/tests"
_obj_cls = FakeObject
class FakeParent(FakeObject):
id = 42
class FakeManagerWithParent(base.RESTManager):
_path = "/tests/{test_id}/cases"
_obj_cls = FakeObject
_from_parent_attrs = {"test_id": "id"}
# NOTE: The function `httmock_response` and the class `Headers` is taken from
# https://github.com/patrys/httmock/ which is licensed under the Apache License, Version
# 2.0. Thus it is allowed to be used in this project.
# https://www.apache.org/licenses/GPL-compatibility.html
class Headers(object):
def __init__(self, res):
self.headers = res.headers
def get_all(self, name, failobj=None):
return self.getheaders(name)
def getheaders(self, name):
return [self.headers.get(name)]
def httmock_response(
status_code: int = 200,
content: str = "",
headers=None,
reason=None,
elapsed=0,
request: Optional[requests.models.PreparedRequest] = None,
stream: bool = False,
http_vsn=11,
) -> requests.models.Response:
res = requests.Response()
res.status_code = status_code
if isinstance(content, (dict, list)):
content = json.dumps(content).encode("utf-8")
if isinstance(content, str):
content = content.encode("utf-8")
res._content = content
res._content_consumed = content
res.headers = requests.structures.CaseInsensitiveDict(headers or {})
res.encoding = requests.utils.get_encoding_from_headers(res.headers)
res.reason = reason
res.elapsed = datetime.timedelta(elapsed)
res.request = request
if hasattr(request, "url"):
res.url = request.url
if isinstance(request.url, bytes):
res.url = request.url.decode("utf-8")
if "set-cookie" in res.headers:
res.cookies.extract_cookies(
requests.cookies.MockResponse(Headers(res)),
requests.cookies.MockRequest(request),
)
if stream:
res.raw = io.BytesIO(content)
else:
res.raw = io.BytesIO(b"")
res.raw.version = http_vsn
# normally this closes the underlying connection,
# but we have nothing to free.
res.close = lambda *args, **kwargs: None
return res
| 2,695 | Python | .py | 78 | 29.487179 | 88 | 0.694444 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,158 | test_gitlab.py | python-gitlab_python-gitlab/tests/unit/test_gitlab.py | import copy
import logging
import pickle
from http.client import HTTPConnection
import pytest
import requests
import responses
import gitlab
from gitlab.config import GitlabConfigMissingError, GitlabDataError
from tests.unit import helpers
localhost = "http://localhost"
token = "abc123"
@pytest.fixture
def resp_get_user():
return {
"method": responses.GET,
"url": "http://localhost/api/v4/user",
"json": {
"id": 1,
"username": "username",
"web_url": "http://localhost/username",
},
"content_type": "application/json",
"status": 200,
}
@pytest.fixture
def resp_page_1():
headers = {
"X-Page": "1",
"X-Next-Page": "2",
"X-Per-Page": "1",
"X-Total-Pages": "2",
"X-Total": "2",
"Link": ("<http://localhost/api/v4/tests?per_page=1&page=2>;" ' rel="next"'),
}
return {
"method": responses.GET,
"url": "http://localhost/api/v4/tests",
"json": [{"a": "b"}],
"headers": headers,
"content_type": "application/json",
"status": 200,
"match": helpers.MATCH_EMPTY_QUERY_PARAMS,
}
@pytest.fixture
def resp_page_2():
headers = {
"X-Page": "2",
"X-Next-Page": "2",
"X-Per-Page": "1",
"X-Total-Pages": "2",
"X-Total": "2",
}
params = {"per_page": "1", "page": "2"}
return {
"method": responses.GET,
"url": "http://localhost/api/v4/tests",
"json": [{"c": "d"}],
"headers": headers,
"content_type": "application/json",
"status": 200,
"match": [responses.matchers.query_param_matcher(params)],
}
def test_gitlab_init_with_valid_api_version():
gl = gitlab.Gitlab(api_version="4")
assert gl.api_version == "4"
def test_gitlab_init_with_invalid_api_version():
with pytest.raises(ModuleNotFoundError, match="gitlab.v1.objects"):
gitlab.Gitlab(api_version="1")
def test_gitlab_as_context_manager():
with gitlab.Gitlab() as gl:
assert isinstance(gl, gitlab.Gitlab)
def test_gitlab_enable_debug(gl):
gl.enable_debug()
logger = logging.getLogger("requests.packages.urllib3")
assert logger.level == logging.DEBUG
assert HTTPConnection.debuglevel == 1
@responses.activate
@pytest.mark.parametrize(
"status_code,response_json,expected",
[
(200, {"version": "0.0.0-pre", "revision": "abcdef"}, ("0.0.0-pre", "abcdef")),
(200, None, ("unknown", "unknown")),
(401, None, ("unknown", "unknown")),
],
)
def test_gitlab_get_version(gl, status_code, response_json, expected):
responses.add(
method=responses.GET,
url="http://localhost/api/v4/version",
json=response_json,
status=status_code,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
version = gl.version()
assert version == expected
@responses.activate
@pytest.mark.parametrize(
"response_json,expected",
[
({"id": "1", "plan": "premium"}, {"id": "1", "plan": "premium"}),
(None, {}),
],
)
def test_gitlab_get_license(gl, response_json, expected):
responses.add(
method=responses.GET,
url="http://localhost/api/v4/license",
json=response_json,
status=200,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
gitlab_license = gl.get_license()
assert gitlab_license == expected
@responses.activate
def test_gitlab_set_license(gl):
responses.add(
method=responses.POST,
url="http://localhost/api/v4/license",
json={"id": 1, "plan": "premium"},
status=201,
match=helpers.MATCH_EMPTY_QUERY_PARAMS,
)
gitlab_license = gl.set_license("yJkYXRhIjoiMHM5Q")
assert gitlab_license["plan"] == "premium"
@responses.activate
def test_gitlab_build_list(gl, resp_page_1, resp_page_2):
responses.add(**resp_page_1)
obj = gl.http_list("/tests", iterator=True)
assert len(obj) == 2
assert obj._next_url == "http://localhost/api/v4/tests?per_page=1&page=2"
assert obj.current_page == 1
assert obj.prev_page is None
assert obj.next_page == 2
assert obj.per_page == 1
assert obj.total_pages == 2
assert obj.total == 2
responses.add(**resp_page_2)
test_list = list(obj)
assert len(test_list) == 2
assert test_list[0]["a"] == "b"
assert test_list[1]["c"] == "d"
def _strip_pagination_headers(response):
"""
https://docs.gitlab.com/ee/user/gitlab_com/index.html#pagination-response-headers
"""
stripped = copy.deepcopy(response)
del stripped["headers"]["X-Total-Pages"]
del stripped["headers"]["X-Total"]
return stripped
@responses.activate
def test_gitlab_build_list_missing_headers(gl, resp_page_1, resp_page_2):
stripped_page_1 = _strip_pagination_headers(resp_page_1)
stripped_page_2 = _strip_pagination_headers(resp_page_2)
responses.add(**stripped_page_1)
obj = gl.http_list("/tests", iterator=True)
assert len(obj) == 0 # Lazy generator has no knowledge of total items
assert obj.total_pages is None
assert obj.total is None
responses.add(**stripped_page_2)
test_list = list(obj)
assert len(test_list) == 2 # List has total items after making the API calls
@responses.activate
def test_gitlab_get_all_omitted_when_iterator(gl, resp_page_1, resp_page_2):
responses.add(**resp_page_1)
responses.add(**resp_page_2)
result = gl.http_list("/tests", iterator=True, get_all=True)
assert isinstance(result, gitlab.GitlabList)
def test_gitlab_strip_base_url(gl_trailing):
assert gl_trailing.url == "http://localhost"
def test_gitlab_strip_api_url(gl_trailing):
assert gl_trailing.api_url == "http://localhost/api/v4"
def test_gitlab_build_url(gl_trailing):
r = gl_trailing._build_url("/projects")
assert r == "http://localhost/api/v4/projects"
def test_gitlab_pickability(gl):
original_gl_objects = gl._objects
pickled = pickle.dumps(gl)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, gitlab.Gitlab)
assert hasattr(unpickled, "_objects")
assert unpickled._objects == original_gl_objects
@responses.activate
def test_gitlab_token_auth(gl, resp_get_user):
responses.add(**resp_get_user)
gl.auth()
assert gl.user.username == "username"
assert gl.user.id == 1
assert isinstance(gl.user, gitlab.v4.objects.CurrentUser)
@responses.activate
def test_gitlab_auth_with_mismatching_url_warns():
responses.add(
method=responses.GET,
url="http://first.example.com/api/v4/user",
json={
"username": "test-user",
"web_url": "http://second.example.com/test-user",
},
content_type="application/json",
status=200,
)
gl = gitlab.Gitlab("http://first.example.com")
with pytest.warns(UserWarning):
gl.auth()
def test_gitlab_default_url():
gl = gitlab.Gitlab()
assert gl.url == gitlab.const.DEFAULT_URL
@pytest.mark.parametrize(
"args, kwargs, expected_url, expected_private_token, expected_oauth_token",
[
([], {}, gitlab.const.DEFAULT_URL, None, None),
([None, token], {}, gitlab.const.DEFAULT_URL, token, None),
([localhost], {}, localhost, None, None),
([localhost, token], {}, localhost, token, None),
([localhost, None, token], {}, localhost, None, token),
([], {"private_token": token}, gitlab.const.DEFAULT_URL, token, None),
([], {"oauth_token": token}, gitlab.const.DEFAULT_URL, None, token),
([], {"url": localhost}, localhost, None, None),
([], {"url": localhost, "private_token": token}, localhost, token, None),
([], {"url": localhost, "oauth_token": token}, localhost, None, token),
],
ids=[
"no_args",
"args_private_token",
"args_url",
"args_url_private_token",
"args_url_oauth_token",
"kwargs_private_token",
"kwargs_oauth_token",
"kwargs_url",
"kwargs_url_private_token",
"kwargs_url_oauth_token",
],
)
def test_gitlab_args_kwargs(
args, kwargs, expected_url, expected_private_token, expected_oauth_token
):
gl = gitlab.Gitlab(*args, **kwargs)
assert gl.url == expected_url
assert gl.private_token == expected_private_token
assert gl.oauth_token == expected_oauth_token
def test_gitlab_from_config(default_config):
config_path = default_config
gitlab.Gitlab.from_config("one", [config_path])
def test_gitlab_from_config_without_files_raises():
with pytest.raises(GitlabConfigMissingError, match="non-existing"):
gitlab.Gitlab.from_config("non-existing")
def test_gitlab_from_config_with_wrong_gitlab_id_raises(default_config):
with pytest.raises(GitlabDataError, match="non-existing"):
gitlab.Gitlab.from_config("non-existing", [default_config])
def test_gitlab_subclass_from_config(default_config):
class MyGitlab(gitlab.Gitlab):
pass
config_path = default_config
gl = MyGitlab.from_config("one", [config_path])
assert isinstance(gl, MyGitlab)
@pytest.mark.parametrize(
"kwargs,expected_agent",
[
({}, gitlab.const.USER_AGENT),
({"user_agent": "my-package/1.0.0"}, "my-package/1.0.0"),
],
)
def test_gitlab_user_agent(kwargs, expected_agent):
gl = gitlab.Gitlab("http://localhost", **kwargs)
assert gl.headers["User-Agent"] == expected_agent
def test_gitlab_enum_const_does_not_warn(recwarn):
no_access = gitlab.const.AccessLevel.NO_ACCESS
assert not recwarn
assert no_access == 0
def test_gitlab_plain_const_does_not_warn(recwarn):
no_access = gitlab.const.NO_ACCESS
assert not recwarn
assert no_access == 0
@responses.activate
@pytest.mark.parametrize(
"kwargs,link_header,expected_next_url,show_warning",
[
(
{},
"<http://localhost/api/v4/tests?per_page=1&page=2>;" ' rel="next"',
"http://localhost/api/v4/tests?per_page=1&page=2",
False,
),
(
{},
"<http://orig_host/api/v4/tests?per_page=1&page=2>;" ' rel="next"',
"http://orig_host/api/v4/tests?per_page=1&page=2",
True,
),
(
{"keep_base_url": True},
"<http://orig_host/api/v4/tests?per_page=1&page=2>;" ' rel="next"',
"http://localhost/api/v4/tests?per_page=1&page=2",
False,
),
],
ids=["url-match-does-not-warn", "url-mismatch-warns", "url-mismatch-keeps-url"],
)
def test_gitlab_keep_base_url(kwargs, link_header, expected_next_url, show_warning):
responses.add(
**{
"method": responses.GET,
"url": "http://localhost/api/v4/tests",
"json": [{"a": "b"}],
"headers": {
"X-Page": "1",
"X-Next-Page": "2",
"X-Per-Page": "1",
"X-Total-Pages": "2",
"X-Total": "2",
"Link": (link_header),
},
"content_type": "application/json",
"status": 200,
"match": helpers.MATCH_EMPTY_QUERY_PARAMS,
}
)
gl = gitlab.Gitlab(url="http://localhost", **kwargs)
if show_warning:
with pytest.warns(UserWarning) as warn_record:
obj = gl.http_list("/tests", iterator=True)
assert len(warn_record) == 1
else:
obj = gl.http_list("/tests", iterator=True)
assert obj._next_url == expected_next_url
def test_no_custom_session(default_config):
"""Test no custom session"""
config_path = default_config
custom_session = requests.Session()
test_gitlab = gitlab.Gitlab.from_config("one", [config_path])
assert test_gitlab.session != custom_session
def test_custom_session(default_config):
"""Test custom session"""
config_path = default_config
custom_session = requests.Session()
test_gitlab = gitlab.Gitlab.from_config(
"one", [config_path], session=custom_session
)
assert test_gitlab.session == custom_session
| 12,171 | Python | .py | 340 | 29.364706 | 87 | 0.626958 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,159 | conftest.py | python-gitlab_python-gitlab/tests/unit/objects/conftest.py | """Common mocks for resources in gitlab.v4.objects"""
import re
import pytest
import responses
@pytest.fixture
def binary_content():
return b"binary content"
@pytest.fixture
def accepted_content():
return {"message": "202 Accepted"}
@pytest.fixture
def created_content():
return {"message": "201 Created"}
@pytest.fixture
def token_content():
return {
"user_id": 141,
"scopes": ["api"],
"name": "token",
"expires_at": "2021-01-31",
"id": 42,
"active": True,
"created_at": "2021-01-20T22:11:48.151Z",
"revoked": False,
"token": "s3cr3t",
}
@pytest.fixture
def resp_export(accepted_content, binary_content):
"""Common fixture for group and project exports."""
export_status_content = {
"id": 1,
"description": "Itaque perspiciatis minima aspernatur",
"name": "Gitlab Test",
"name_with_namespace": "Gitlab Org / Gitlab Test",
"path": "gitlab-test",
"path_with_namespace": "gitlab-org/gitlab-test",
"created_at": "2017-08-29T04:36:44.383Z",
"export_status": "finished",
"_links": {
"api_url": "https://gitlab.test/api/v4/projects/1/export/download",
"web_url": "https://gitlab.test/gitlab-test/download_export",
},
}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.POST,
url=re.compile(r".*/api/v4/(groups|projects)/1/export"),
json=accepted_content,
content_type="application/json",
status=202,
)
rsps.add(
method=responses.GET,
url=re.compile(r".*/api/v4/(groups|projects)/1/export/download"),
body=binary_content,
content_type="application/octet-stream",
status=200,
)
# Currently only project export supports status checks
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/export",
json=export_status_content,
content_type="application/json",
status=200,
)
yield rsps
| 2,212 | Python | .py | 67 | 25.014925 | 79 | 0.593809 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,160 | test_releases.py | python-gitlab_python-gitlab/tests/unit/objects/test_releases.py | """
GitLab API:
https://docs.gitlab.com/ee/api/releases/index.html
https://docs.gitlab.com/ee/api/releases/links.html
"""
import re
import pytest
import responses
from gitlab.v4.objects import ProjectReleaseLink
tag_name = "v1.0.0"
release_name = "demo-release"
release_description = "my-rel-desc"
released_at = "2019-03-15T08:00:00Z"
link_name = "hello-world"
link_url = "https://gitlab.example.com/group/hello/-/jobs/688/artifacts/raw/bin/hello-darwin-amd64"
direct_url = f"https://gitlab.example.com/group/hello/-/releases/{tag_name}/downloads/hello-world"
new_link_type = "package"
link_content = {
"id": 2,
"name": link_name,
"url": link_url,
"direct_asset_url": direct_url,
"external": False,
"link_type": "other",
}
release_content = {
"id": 3,
"tag_name": tag_name,
"name": release_name,
"description": release_description,
"milestones": [],
"released_at": released_at,
}
release_url = re.compile(rf"http://localhost/api/v4/projects/1/releases/{tag_name}")
links_url = re.compile(
rf"http://localhost/api/v4/projects/1/releases/{tag_name}/assets/links"
)
link_id_url = re.compile(
rf"http://localhost/api/v4/projects/1/releases/{tag_name}/assets/links/1"
)
@pytest.fixture
def resp_list_links():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=links_url,
json=[link_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_link():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=link_id_url,
json=link_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_link():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url=links_url,
json=link_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_update_link():
updated_content = dict(link_content)
updated_content["link_type"] = new_link_type
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url=link_id_url,
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_delete_link():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url=link_id_url,
status=204,
)
yield rsps
@pytest.fixture
def resp_update_release():
updated_content = dict(release_content)
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url=release_url,
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_release_links(release, resp_list_links):
links = release.links.list()
assert isinstance(links, list)
assert isinstance(links[0], ProjectReleaseLink)
assert links[0].url == link_url
def test_get_release_link(release, resp_get_link):
link = release.links.get(1)
assert isinstance(link, ProjectReleaseLink)
assert link.url == link_url
def test_create_release_link(release, resp_create_link):
link = release.links.create({"url": link_url, "name": link_name})
assert isinstance(link, ProjectReleaseLink)
assert link.url == link_url
def test_update_release_link(release, resp_update_link):
link = release.links.get(1, lazy=True)
link.link_type = new_link_type
link.save()
assert link.link_type == new_link_type
def test_delete_release_link(release, resp_delete_link):
link = release.links.get(1, lazy=True)
link.delete()
def test_update_release(release, resp_update_release):
release.name = release_name
release.description = release_description
release.save()
assert release.name == release_name
assert release.description == release_description
| 4,215 | Python | .py | 134 | 25.320896 | 99 | 0.655964 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,161 | test_applications.py | python-gitlab_python-gitlab/tests/unit/objects/test_applications.py | """
GitLab API: https://docs.gitlab.com/ce/api/applications.html
"""
import pytest
import responses
title = "GitLab Test Instance"
description = "gitlab-test.example.com"
new_title = "new-title"
new_description = "new-description"
@pytest.fixture
def resp_application_create():
content = {
"name": "test_app",
"redirect_uri": "http://localhost:8080",
"scopes": ["api", "email"],
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/applications",
json=content,
content_type="application/json",
status=200,
)
yield rsps
def test_create_application(gl, resp_application_create):
application = gl.applications.create(
{
"name": "test_app",
"redirect_uri": "http://localhost:8080",
"scopes": ["api", "email"],
"confidential": False,
}
)
assert application.name == "test_app"
assert application.redirect_uri == "http://localhost:8080"
assert application.scopes == ["api", "email"]
| 1,137 | Python | .py | 37 | 24.027027 | 62 | 0.610247 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,162 | test_pipelines.py | python-gitlab_python-gitlab/tests/unit/objects/test_pipelines.py | """
GitLab API: https://docs.gitlab.com/ee/api/pipelines.html
"""
import pytest
import responses
from gitlab.v4.objects import (
ProjectPipeline,
ProjectPipelineTestReport,
ProjectPipelineTestReportSummary,
)
pipeline_content = {
"id": 46,
"project_id": 1,
"status": "pending",
"ref": "main",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"before_sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"tag": False,
"yaml_errors": None,
"user": {
"name": "Administrator",
"username": "root",
"id": 1,
"state": "active",
"avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
"web_url": "http://localhost:3000/root",
},
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"started_at": None,
"finished_at": "2016-08-11T11:32:35.145Z",
"committed_at": None,
"duration": None,
"queued_duration": 0.010,
"coverage": None,
"web_url": "https://example.com/foo/bar/pipelines/46",
}
pipeline_latest = {
"id": 47,
"project_id": 1,
"status": "pending",
"ref": "main",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"before_sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"tag": False,
"yaml_errors": None,
"user": {
"name": "Administrator",
"username": "root",
"id": 1,
"state": "active",
"avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
"web_url": "http://localhost:3000/root",
},
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"started_at": None,
"finished_at": "2016-08-11T11:32:35.145Z",
"committed_at": None,
"duration": None,
"queued_duration": 0.010,
"coverage": None,
"web_url": "https://example.com/foo/bar/pipelines/46",
}
pipeline_latest_other_ref = {
"id": 48,
"project_id": 1,
"status": "pending",
"ref": "feature-ref",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"before_sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"tag": False,
"yaml_errors": None,
"user": {
"name": "Administrator",
"username": "root",
"id": 1,
"state": "active",
"avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
"web_url": "http://localhost:3000/root",
},
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"started_at": None,
"finished_at": "2016-08-11T11:32:35.145Z",
"committed_at": None,
"duration": None,
"queued_duration": 0.010,
"coverage": None,
"web_url": "https://example.com/foo/bar/pipelines/46",
}
test_report_content = {
"total_time": 5,
"total_count": 1,
"success_count": 1,
"failed_count": 0,
"skipped_count": 0,
"error_count": 0,
"test_suites": [
{
"name": "Secure",
"total_time": 5,
"total_count": 1,
"success_count": 1,
"failed_count": 0,
"skipped_count": 0,
"error_count": 0,
"test_cases": [
{
"status": "success",
"name": "Security Reports can create an auto-remediation MR",
"classname": "vulnerability_management_spec",
"execution_time": 5,
"system_output": None,
"stack_trace": None,
}
],
}
],
}
test_report_summary_content = {
"total": {
"time": 1904,
"count": 3363,
"success": 3351,
"failed": 0,
"skipped": 12,
"error": 0,
"suite_error": None,
},
"test_suites": [
{
"name": "test",
"total_time": 1904,
"total_count": 3363,
"success_count": 3351,
"failed_count": 0,
"skipped_count": 12,
"error_count": 0,
"build_ids": [66004],
"suite_error": None,
}
],
}
@pytest.fixture
def resp_get_pipeline():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipelines/1",
json=pipeline_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_cancel_pipeline():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/pipelines/1/cancel",
json=pipeline_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_retry_pipeline():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/pipelines/1/retry",
json=pipeline_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_get_pipeline_test_report():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipelines/1/test_report",
json=test_report_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_pipeline_test_report_summary():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipelines/1/test_report_summary",
json=test_report_summary_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_latest():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipelines/latest",
json=pipeline_latest,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_latest_other_ref():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipelines/latest",
json=pipeline_latest_other_ref,
content_type="application/json",
status=200,
)
yield rsps
def test_get_project_pipeline(project, resp_get_pipeline):
pipeline = project.pipelines.get(1)
assert isinstance(pipeline, ProjectPipeline)
assert pipeline.ref == "main"
assert pipeline.id == 46
def test_cancel_project_pipeline(project, resp_cancel_pipeline):
pipeline = project.pipelines.get(1, lazy=True)
output = pipeline.cancel()
assert output["ref"] == "main"
def test_retry_project_pipeline(project, resp_retry_pipeline):
pipeline = project.pipelines.get(1, lazy=True)
output = pipeline.retry()
assert output["ref"] == "main"
def test_get_project_pipeline_test_report(project, resp_get_pipeline_test_report):
pipeline = project.pipelines.get(1, lazy=True)
test_report = pipeline.test_report.get()
assert isinstance(test_report, ProjectPipelineTestReport)
assert test_report.total_time == 5
assert test_report.test_suites[0]["name"] == "Secure"
def test_get_project_pipeline_test_report_summary(
project, resp_get_pipeline_test_report_summary
):
pipeline = project.pipelines.get(1, lazy=True)
test_report_summary = pipeline.test_report_summary.get()
assert isinstance(test_report_summary, ProjectPipelineTestReportSummary)
assert test_report_summary.total["count"] == 3363
assert test_report_summary.test_suites[0]["name"] == "test"
def test_latest_pipeline(project, resp_get_latest):
pipeline = project.pipelines.latest()
assert isinstance(pipeline, ProjectPipeline)
assert pipeline.ref == "main"
assert pipeline.id == 47
def test_latest_pipeline_other_ref(project, resp_get_latest_other_ref):
pipeline = project.pipelines.latest(ref="feature-ref")
assert isinstance(pipeline, ProjectPipeline)
assert pipeline.ref == "feature-ref"
assert pipeline.id == 48
| 8,488 | Python | .py | 258 | 25.468992 | 105 | 0.607374 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,163 | test_resource_groups.py | python-gitlab_python-gitlab/tests/unit/objects/test_resource_groups.py | """
GitLab API:
https://docs.gitlab.com/ee/api/resource_groups.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectResourceGroup, ProjectResourceGroupUpcomingJob
from .test_jobs import failed_job_content
resource_group_content = {
"id": 3,
"key": "production",
"process_mode": "unordered",
"created_at": "2021-09-01T08:04:59.650Z",
"updated_at": "2021-09-01T08:04:59.650Z",
}
@pytest.fixture
def resp_list_resource_groups():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/resource_groups",
json=[resource_group_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_resource_group():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/resource_groups/production",
json=resource_group_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_upcoming_jobs():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/resource_groups/production/upcoming_jobs",
json=[failed_job_content],
content_type="application/json",
status=200,
)
yield rsps
def test_list_project_resource_groups(project, resp_list_resource_groups):
resource_groups = project.resource_groups.list()
assert isinstance(resource_groups, list)
assert isinstance(resource_groups[0], ProjectResourceGroup)
assert resource_groups[0].process_mode == "unordered"
def test_get_project_resource_group(project, resp_get_resource_group):
resource_group = project.resource_groups.get("production")
assert isinstance(resource_group, ProjectResourceGroup)
assert resource_group.process_mode == "unordered"
def test_list_resource_group_upcoming_jobs(project, resp_list_upcoming_jobs):
resource_group = project.resource_groups.get("production", lazy=True)
upcoming_jobs = resource_group.upcoming_jobs.list()
assert isinstance(upcoming_jobs, list)
assert isinstance(upcoming_jobs[0], ProjectResourceGroupUpcomingJob)
assert upcoming_jobs[0].ref == "main"
| 2,438 | Python | .py | 63 | 32.15873 | 94 | 0.693808 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,164 | test_issues.py | python-gitlab_python-gitlab/tests/unit/objects/test_issues.py | """
GitLab API: https://docs.gitlab.com/ce/api/issues.html
"""
import re
import pytest
import responses
from gitlab.v4.objects import (
GroupIssuesStatistics,
IssuesStatistics,
ProjectIssuesStatistics,
)
@pytest.fixture
def resp_list_issues():
content = [{"name": "name", "id": 1}, {"name": "other_name", "id": 2}]
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/issues",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_issue():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/issues/1",
json={"name": "name", "id": 1},
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_reorder_issue():
match_params = {"move_after_id": 2, "move_before_id": 3}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/issues/1/reorder",
json={"name": "name", "id": 1},
content_type="application/json",
status=200,
match=[responses.matchers.json_params_matcher(match_params)],
)
yield rsps
@pytest.fixture
def resp_issue_statistics():
content = {"statistics": {"counts": {"all": 20, "closed": 5, "opened": 15}}}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(
r"http://localhost/api/v4/((groups|projects)/1/)?issues_statistics"
),
json=content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_issues(gl, resp_list_issues):
data = gl.issues.list()
assert data[1].id == 2
assert data[1].name == "other_name"
def test_get_issue(gl, resp_get_issue):
issue = gl.issues.get(1)
assert issue.id == 1
assert issue.name == "name"
def test_reorder_issue(project, resp_reorder_issue):
issue = project.issues.get(1, lazy=True)
issue.reorder(move_after_id=2, move_before_id=3)
def test_get_issues_statistics(gl, resp_issue_statistics):
statistics = gl.issues_statistics.get()
assert isinstance(statistics, IssuesStatistics)
assert statistics.statistics["counts"]["all"] == 20
def test_get_group_issues_statistics(group, resp_issue_statistics):
statistics = group.issues_statistics.get()
assert isinstance(statistics, GroupIssuesStatistics)
assert statistics.statistics["counts"]["all"] == 20
def test_get_project_issues_statistics(project, resp_issue_statistics):
statistics = project.issues_statistics.get()
assert isinstance(statistics, ProjectIssuesStatistics)
assert statistics.statistics["counts"]["all"] == 20
| 3,000 | Python | .py | 84 | 28.654762 | 83 | 0.639571 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,165 | test_badges.py | python-gitlab_python-gitlab/tests/unit/objects/test_badges.py | """
GitLab API: https://docs.gitlab.com/ee/api/project_badges.html
GitLab API: https://docs.gitlab.com/ee/api/group_badges.html
"""
import re
import pytest
import responses
from gitlab.v4.objects import GroupBadge, ProjectBadge
link_url = (
"http://example.com/ci_status.svg?project=example-org/example-project&ref=main"
)
image_url = "https://example.io/my/badge"
rendered_link_url = (
"http://example.com/ci_status.svg?project=example-org/example-project&ref=main"
)
rendered_image_url = "https://example.io/my/badge"
new_badge = {
"link_url": link_url,
"image_url": image_url,
}
badge_content = {
"name": "Coverage",
"id": 1,
"link_url": link_url,
"image_url": image_url,
"rendered_link_url": rendered_image_url,
"rendered_image_url": rendered_image_url,
}
preview_badge_content = {
"link_url": link_url,
"image_url": image_url,
"rendered_link_url": rendered_link_url,
"rendered_image_url": rendered_image_url,
}
@pytest.fixture()
def resp_get_badge():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(r"http://localhost/api/v4/(projects|groups)/1/badges/1"),
json=badge_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_list_badges():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(r"http://localhost/api/v4/(projects|groups)/1/badges"),
json=[badge_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_create_badge():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url=re.compile(r"http://localhost/api/v4/(projects|groups)/1/badges"),
json=badge_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_update_badge():
updated_content = dict(badge_content)
updated_content["link_url"] = "http://link_url"
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url=re.compile(r"http://localhost/api/v4/(projects|groups)/1/badges/1"),
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_delete_badge():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url=re.compile(r"http://localhost/api/v4/(projects|groups)/1/badges/1"),
status=204,
)
yield rsps
@pytest.fixture()
def resp_preview_badge():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(
r"http://localhost/api/v4/(projects|groups)/1/badges/render"
),
json=preview_badge_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_project_badges(project, resp_list_badges):
badges = project.badges.list()
assert isinstance(badges, list)
assert isinstance(badges[0], ProjectBadge)
def test_list_group_badges(group, resp_list_badges):
badges = group.badges.list()
assert isinstance(badges, list)
assert isinstance(badges[0], GroupBadge)
def test_get_project_badge(project, resp_get_badge):
badge = project.badges.get(1)
assert isinstance(badge, ProjectBadge)
assert badge.name == "Coverage"
assert badge.id == 1
def test_get_group_badge(group, resp_get_badge):
badge = group.badges.get(1)
assert isinstance(badge, GroupBadge)
assert badge.name == "Coverage"
assert badge.id == 1
def test_delete_project_badge(project, resp_delete_badge):
badge = project.badges.get(1, lazy=True)
badge.delete()
def test_delete_group_badge(group, resp_delete_badge):
badge = group.badges.get(1, lazy=True)
badge.delete()
def test_create_project_badge(project, resp_create_badge):
badge = project.badges.create(new_badge)
assert isinstance(badge, ProjectBadge)
assert badge.image_url == image_url
def test_create_group_badge(group, resp_create_badge):
badge = group.badges.create(new_badge)
assert isinstance(badge, GroupBadge)
assert badge.image_url == image_url
def test_preview_project_badge(project, resp_preview_badge):
output = project.badges.render(
link_url=link_url,
image_url=image_url,
)
assert isinstance(output, dict)
assert "rendered_link_url" in output
assert "rendered_image_url" in output
assert output["link_url"] == output["rendered_link_url"]
assert output["image_url"] == output["rendered_image_url"]
def test_preview_group_badge(group, resp_preview_badge):
output = group.badges.render(
link_url=link_url,
image_url=image_url,
)
assert isinstance(output, dict)
assert "rendered_link_url" in output
assert "rendered_image_url" in output
assert output["link_url"] == output["rendered_link_url"]
assert output["image_url"] == output["rendered_image_url"]
def test_update_project_badge(project, resp_update_badge):
badge = project.badges.get(1, lazy=True)
badge.link_url = "http://link_url"
badge.save()
assert badge.link_url == "http://link_url"
def test_update_group_badge(group, resp_update_badge):
badge = group.badges.get(1, lazy=True)
badge.link_url = "http://link_url"
badge.save()
assert badge.link_url == "http://link_url"
| 5,724 | Python | .py | 164 | 28.676829 | 84 | 0.661469 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,166 | test_runners.py | python-gitlab_python-gitlab/tests/unit/objects/test_runners.py | import re
import pytest
import responses
import gitlab
from gitlab.v4.objects.runners import Runner, RunnerAll
runner_detail = {
"active": True,
"architecture": "amd64",
"description": "test-1-20150125",
"id": 6,
"ip_address": "127.0.0.1",
"is_shared": False,
"contacted_at": "2016-01-25T16:39:48.066Z",
"name": "test-runner",
"online": True,
"status": "online",
"platform": "linux",
"projects": [
{
"id": 1,
"name": "GitLab Community Edition",
"name_with_namespace": "GitLab.org / GitLab Community Edition",
"path": "gitlab-foss",
"path_with_namespace": "gitlab-org/gitlab-foss",
}
],
"revision": "5nj35",
"tag_list": ["ruby", "mysql"],
"version": "v13.0.0",
"access_level": "ref_protected",
"maximum_timeout": 3600,
}
runner_shortinfo = {
"active": True,
"description": "test-1-20150125",
"id": 6,
"is_shared": False,
"ip_address": "127.0.0.1",
"name": "test-name",
"online": True,
"status": "online",
}
runner_jobs = [
{
"id": 6,
"ip_address": "127.0.0.1",
"status": "running",
"stage": "test",
"name": "test",
"ref": "main",
"tag": False,
"coverage": "99%",
"created_at": "2017-11-16T08:50:29.000Z",
"started_at": "2017-11-16T08:51:29.000Z",
"finished_at": "2017-11-16T08:53:29.000Z",
"duration": 120,
"user": {
"id": 1,
"name": "John Doe2",
"username": "user2",
"state": "active",
"avatar_url": "http://www.gravatar.com/avatar/c922747a93b40d1ea88262bf1aebee62?s=80&d=identicon",
"web_url": "http://localhost/user2",
"created_at": "2017-11-16T18:38:46.000Z",
"bio": None,
"location": None,
"public_email": "",
"skype": "",
"linkedin": "",
"twitter": "",
"website_url": "",
"organization": None,
},
}
]
@pytest.fixture
def resp_get_runners_jobs():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/runners/6/jobs",
json=runner_jobs,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_runners_list():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(r".*?(/runners(/all)?|/(groups|projects)/1/runners)"),
json=[runner_shortinfo],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_runner_detail():
with responses.RequestsMock() as rsps:
pattern = re.compile(r".*?/runners/6")
rsps.add(
method=responses.GET,
url=pattern,
json=runner_detail,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.PUT,
url=pattern,
json=runner_detail,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_runner_register():
with responses.RequestsMock() as rsps:
pattern = re.compile(r".*?/runners")
rsps.add(
method=responses.POST,
url=pattern,
json={"id": "6", "token": "6337ff461c94fd3fa32ba3b1ff4125"},
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_runner_enable():
with responses.RequestsMock() as rsps:
pattern = re.compile(r".*?projects/1/runners")
rsps.add(
method=responses.POST,
url=pattern,
json=runner_shortinfo,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_runner_delete():
with responses.RequestsMock() as rsps:
pattern = re.compile(r".*?/runners/6")
rsps.add(
method=responses.GET,
url=pattern,
json=runner_detail,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.DELETE,
url=pattern,
status=204,
)
yield rsps
@pytest.fixture
def resp_runner_delete_by_token():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/runners",
status=204,
match=[responses.matchers.query_param_matcher({"token": "auth-token"})],
)
yield rsps
@pytest.fixture
def resp_runner_disable():
with responses.RequestsMock() as rsps:
pattern = re.compile(r".*?/projects/1/runners/6")
rsps.add(
method=responses.DELETE,
url=pattern,
status=204,
)
yield rsps
@pytest.fixture
def resp_runner_verify():
with responses.RequestsMock() as rsps:
pattern = re.compile(r".*?/runners/verify")
rsps.add(
method=responses.POST,
url=pattern,
status=200,
)
yield rsps
def test_owned_runners_list(gl: gitlab.Gitlab, resp_get_runners_list):
runners = gl.runners.list()
assert runners[0].active is True
assert runners[0].id == 6
assert runners[0].name == "test-name"
assert len(runners) == 1
def test_project_runners_list(gl: gitlab.Gitlab, resp_get_runners_list):
runners = gl.projects.get(1, lazy=True).runners.list()
assert runners[0].active is True
assert runners[0].id == 6
assert runners[0].name == "test-name"
assert len(runners) == 1
def test_group_runners_list(gl: gitlab.Gitlab, resp_get_runners_list):
runners = gl.groups.get(1, lazy=True).runners.list()
assert runners[0].active is True
assert runners[0].id == 6
assert runners[0].name == "test-name"
assert len(runners) == 1
def test_runners_all(gl: gitlab.Gitlab, resp_get_runners_list):
runners = gl.runners.all()
assert isinstance(runners[0], Runner)
assert runners[0].active is True
assert runners[0].id == 6
assert runners[0].name == "test-name"
assert len(runners) == 1
def test_runners_all_list(gl: gitlab.Gitlab, resp_get_runners_list):
runners = gl.runners_all.list()
assert isinstance(runners[0], RunnerAll)
assert runners[0].active is True
assert runners[0].id == 6
assert runners[0].name == "test-name"
assert len(runners) == 1
def test_create_runner(gl: gitlab.Gitlab, resp_runner_register):
runner = gl.runners.create({"token": "token"})
assert runner.id == "6"
assert runner.token == "6337ff461c94fd3fa32ba3b1ff4125"
def test_get_update_runner(gl: gitlab.Gitlab, resp_runner_detail):
runner = gl.runners.get(6)
assert runner.active is True
runner.tag_list.append("new")
runner.save()
def test_delete_runner_by_id(gl: gitlab.Gitlab, resp_runner_delete):
runner = gl.runners.get(6)
runner.delete()
gl.runners.delete(6)
def test_delete_runner_by_token(gl: gitlab.Gitlab, resp_runner_delete_by_token):
gl.runners.delete(token="auth-token")
def test_disable_project_runner(gl: gitlab.Gitlab, resp_runner_disable):
gl.projects.get(1, lazy=True).runners.delete(6)
def test_enable_project_runner(gl: gitlab.Gitlab, resp_runner_enable):
runner = gl.projects.get(1, lazy=True).runners.create({"runner_id": 6})
assert runner.active is True
assert runner.id == 6
assert runner.name == "test-name"
def test_verify_runner(gl: gitlab.Gitlab, resp_runner_verify):
gl.runners.verify("token")
def test_runner_jobs(gl: gitlab.Gitlab, resp_get_runners_jobs):
jobs = gl.runners.get(6, lazy=True).jobs.list()
assert jobs[0].duration == 120
assert jobs[0].name == "test"
assert jobs[0].user.get("name") == "John Doe2"
assert len(jobs) == 1
| 8,133 | Python | .py | 249 | 25.104418 | 109 | 0.596299 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,167 | test_job_token_scope.py | python-gitlab_python-gitlab/tests/unit/objects/test_job_token_scope.py | """
GitLab API: https://docs.gitlab.com/ee/api/project_job_token_scopes.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectJobTokenScope
from gitlab.v4.objects.job_token_scope import (
AllowlistGroupManager,
AllowlistProjectManager,
)
job_token_scope_content = {
"inbound_enabled": True,
"outbound_enabled": False,
}
project_allowlist_content = [
{
"id": 4,
"description": "",
"name": "Diaspora Client",
"name_with_namespace": "Diaspora / Diaspora Client",
"path": "diaspora-client",
"path_with_namespace": "diaspora/diaspora-client",
"created_at": "2013-09-30T13:46:02Z",
"default_branch": "main",
"tag_list": ["example", "disapora client"],
"topics": ["example", "disapora client"],
"ssh_url_to_repo": "git@gitlab.example.com:diaspora/diaspora-client.git",
"http_url_to_repo": "https://gitlab.example.com/diaspora/diaspora-client.git",
"web_url": "https://gitlab.example.com/diaspora/diaspora-client",
"avatar_url": "https://gitlab.example.com/uploads/project/avatar/4/uploads/avatar.png",
"star_count": 0,
"last_activity_at": "2013-09-30T13:46:02Z",
"namespace": {
"id": 2,
"name": "Diaspora",
"path": "diaspora",
"kind": "group",
"full_path": "diaspora",
"parent_id": "",
"avatar_url": "",
"web_url": "https://gitlab.example.com/diaspora",
},
}
]
project_allowlist_created_content = {
"target_project_id": 2,
"project_id": 1,
}
groups_allowlist_content = [
{
"id": 4,
"web_url": "https://gitlab.example.com/groups/diaspora/diaspora-group",
"name": "namegroup",
}
]
group_allowlist_created_content = {
"target_group_id": 4,
"project_id": 1,
}
@pytest.fixture
def resp_get_job_token_scope():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/job_token_scope",
json=job_token_scope_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_allowlist():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/job_token_scope/allowlist",
json=project_allowlist_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_add_to_allowlist():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/job_token_scope/allowlist",
json=project_allowlist_created_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_groups_allowlist():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/job_token_scope/groups_allowlist",
json=groups_allowlist_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_add_to_groups_allowlist():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/job_token_scope/groups_allowlist",
json=group_allowlist_created_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_patch_job_token_scope():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.PATCH,
url="http://localhost/api/v4/projects/1/job_token_scope",
status=204,
match=[responses.matchers.json_params_matcher({"enabled": False})],
)
yield rsps
@pytest.fixture
def job_token_scope(project, resp_get_job_token_scope):
return project.job_token_scope.get()
def test_get_job_token_scope(project, resp_get_job_token_scope):
scope = project.job_token_scope.get()
assert isinstance(scope, ProjectJobTokenScope)
assert scope.inbound_enabled is True
def test_refresh_job_token_scope(job_token_scope, resp_get_job_token_scope):
job_token_scope.refresh()
assert job_token_scope.inbound_enabled is True
def test_save_job_token_scope(job_token_scope, resp_patch_job_token_scope):
job_token_scope.enabled = False
job_token_scope.save()
def test_update_job_token_scope(project, resp_patch_job_token_scope):
project.job_token_scope.update(new_data={"enabled": False})
def test_get_projects_allowlist(job_token_scope, resp_get_allowlist):
allowlist = job_token_scope.allowlist
assert isinstance(allowlist, AllowlistProjectManager)
allowlist_content = allowlist.list()
assert isinstance(allowlist_content, list)
assert allowlist_content[0].get_id() == 4
def test_add_project_to_allowlist(job_token_scope, resp_add_to_allowlist):
allowlist = job_token_scope.allowlist
assert isinstance(allowlist, AllowlistProjectManager)
resp = allowlist.create({"target_project_id": 2})
assert resp.get_id() == 2
def test_get_groups_allowlist(job_token_scope, resp_get_groups_allowlist):
allowlist = job_token_scope.groups_allowlist
assert isinstance(allowlist, AllowlistGroupManager)
allowlist_content = allowlist.list()
assert isinstance(allowlist_content, list)
assert allowlist_content[0].get_id() == 4
def test_add_group_to_allowlist(job_token_scope, resp_add_to_groups_allowlist):
allowlist = job_token_scope.groups_allowlist
assert isinstance(allowlist, AllowlistGroupManager)
resp = allowlist.create({"target_group_id": 4})
assert resp.get_id() == 4
| 6,210 | Python | .py | 161 | 31.503106 | 95 | 0.662783 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,168 | test_invitations.py | python-gitlab_python-gitlab/tests/unit/objects/test_invitations.py | """
GitLab API: https://docs.gitlab.com/ce/api/invitations.html
"""
import re
import pytest
import responses
from gitlab.exceptions import GitlabInvitationError
create_content = {"email": "email@example.com", "access_level": 30}
success_content = {"status": "success"}
error_content = {
"status": "error",
"message": {
"test@example.com": "Invite email has already been taken",
"test2@example.com": "User already exists in source",
"test_username": "Access level is not included in the list",
},
}
invitations_content = [
{
"id": 1,
"invite_email": "member@example.org",
"created_at": "2020-10-22T14:13:35Z",
"access_level": 30,
"expires_at": "2020-11-22T14:13:35Z",
"user_name": "Raymond Smith",
"created_by_name": "Administrator",
},
]
invitation_content = {
"expires_at": "2012-10-22T14:13:35Z",
"access_level": 40,
}
@pytest.fixture
def resp_invitations_list():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(r"http://localhost/api/v4/(groups|projects)/1/invitations"),
json=invitations_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_invitation_create():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url=re.compile(r"http://localhost/api/v4/(groups|projects)/1/invitations"),
json=success_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_invitation_create_error():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url=re.compile(r"http://localhost/api/v4/(groups|projects)/1/invitations"),
json=error_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_invitation_update():
with responses.RequestsMock() as rsps:
pattern = re.compile(
r"http://localhost/api/v4/(groups|projects)/1/invitations/email%40example.com"
)
rsps.add(
method=responses.PUT,
url=pattern,
json=invitation_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_invitation_delete():
with responses.RequestsMock() as rsps:
pattern = re.compile(
r"http://localhost/api/v4/(groups|projects)/1/invitations/email%40example.com"
)
rsps.add(
method=responses.DELETE,
url=pattern,
status=204,
)
yield rsps
def test_list_group_invitations(group, resp_invitations_list):
invitations = group.invitations.list()
assert invitations[0].invite_email == "member@example.org"
def test_create_group_invitation(group, resp_invitation_create):
invitation = group.invitations.create(create_content)
assert invitation.status == "success"
def test_update_group_invitation(group, resp_invitation_update):
invitation = group.invitations.get("email@example.com", lazy=True)
invitation.access_level = 30
invitation.save()
def test_delete_group_invitation(group, resp_invitation_delete):
invitation = group.invitations.get("email@example.com", lazy=True)
invitation.delete()
group.invitations.delete("email@example.com")
def test_list_project_invitations(project, resp_invitations_list):
invitations = project.invitations.list()
assert invitations[0].invite_email == "member@example.org"
def test_create_project_invitation(project, resp_invitation_create):
invitation = project.invitations.create(create_content)
assert invitation.status == "success"
def test_update_project_invitation(project, resp_invitation_update):
invitation = project.invitations.get("email@example.com", lazy=True)
invitation.access_level = 30
invitation.save()
def test_delete_project_invitation(project, resp_invitation_delete):
invitation = project.invitations.get("email@example.com", lazy=True)
invitation.delete()
project.invitations.delete("email@example.com")
def test_create_group_invitation_raises(group, resp_invitation_create_error):
with pytest.raises(GitlabInvitationError, match="User already exists"):
group.invitations.create(create_content)
def test_create_project_invitation_raises(project, resp_invitation_create_error):
with pytest.raises(GitlabInvitationError, match="User already exists"):
project.invitations.create(create_content)
| 4,748 | Python | .py | 125 | 31.24 | 90 | 0.679015 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,169 | test_project_statistics.py | python-gitlab_python-gitlab/tests/unit/objects/test_project_statistics.py | """
GitLab API: https://docs.gitlab.com/ce/api/project_statistics.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectAdditionalStatistics
@pytest.fixture
def resp_project_statistics():
content = {"fetches": {"total": 50, "days": [{"count": 10, "date": "2018-01-10"}]}}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/statistics",
json=content,
content_type="application/json",
status=200,
)
yield rsps
def test_project_additional_statistics(project, resp_project_statistics):
statistics = project.additionalstatistics.get()
assert isinstance(statistics, ProjectAdditionalStatistics)
assert statistics.fetches["total"] == 50
| 824 | Python | .py | 22 | 31.409091 | 87 | 0.690566 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,170 | test_resource_iteration_events.py | python-gitlab_python-gitlab/tests/unit/objects/test_resource_iteration_events.py | """
GitLab API: https://docs.gitlab.com/ee/api/resource_iteration_events.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectIssueResourceIterationEvent
issue_event_content = {"id": 1, "resource_type": "Issue"}
@pytest.fixture()
def resp_list_project_issue_iteration_events():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/issues/1/resource_iteration_events",
json=[issue_event_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_get_project_issue_iteration_event():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/issues/1/resource_iteration_events/1",
json=issue_event_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_project_issue_iteration_events(
project_issue, resp_list_project_issue_iteration_events
):
iteration_events = project_issue.resource_iteration_events.list()
assert isinstance(iteration_events, list)
iteration_event = iteration_events[0]
assert isinstance(iteration_event, ProjectIssueResourceIterationEvent)
assert iteration_event.resource_type == "Issue"
def test_get_project_issue_iteration_event(
project_issue, resp_get_project_issue_iteration_event
):
iteration_event = project_issue.resource_iteration_events.get(1)
assert isinstance(iteration_event, ProjectIssueResourceIterationEvent)
assert iteration_event.resource_type == "Issue"
| 1,717 | Python | .py | 43 | 33.627907 | 90 | 0.712996 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,171 | test_draft_notes.py | python-gitlab_python-gitlab/tests/unit/objects/test_draft_notes.py | """
GitLab API: https://docs.gitlab.com/ee/api/draft_notes.html
"""
from copy import deepcopy
import pytest
import responses
from gitlab.v4.objects import ProjectMergeRequestDraftNote
draft_note_content = {
"id": 1,
"author_id": 23,
"merge_request_id": 1,
"resolve_discussion": False,
"discussion_id": None,
"note": "Example title",
"commit_id": None,
"line_code": None,
"position": {
"base_sha": None,
"start_sha": None,
"head_sha": None,
"old_path": None,
"new_path": None,
"position_type": "text",
"old_line": None,
"new_line": None,
"line_range": None,
},
}
@pytest.fixture()
def resp_list_merge_request_draft_notes():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/1/draft_notes",
json=[draft_note_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_get_merge_request_draft_note():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/1/draft_notes/1",
json=draft_note_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_create_merge_request_draft_note():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/merge_requests/1/draft_notes",
json=draft_note_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture()
def resp_update_merge_request_draft_note():
updated_content = deepcopy(draft_note_content)
updated_content["note"] = "New title"
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/merge_requests/1/draft_notes/1",
json=updated_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture()
def resp_delete_merge_request_draft_note():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/merge_requests/1/draft_notes/1",
json=draft_note_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture()
def resp_publish_merge_request_draft_note():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/merge_requests/1/draft_notes/1/publish",
status=204,
)
yield rsps
@pytest.fixture()
def resp_bulk_publish_merge_request_draft_notes():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/merge_requests/1/draft_notes/bulk_publish",
status=204,
)
yield rsps
def test_list_merge_requests_draft_notes(
project_merge_request, resp_list_merge_request_draft_notes
):
draft_notes = project_merge_request.draft_notes.list()
assert len(draft_notes) == 1
assert isinstance(draft_notes[0], ProjectMergeRequestDraftNote)
assert draft_notes[0].note == draft_note_content["note"]
def test_get_merge_requests_draft_note(
project_merge_request, resp_get_merge_request_draft_note
):
draft_note = project_merge_request.draft_notes.get(1)
assert isinstance(draft_note, ProjectMergeRequestDraftNote)
assert draft_note.note == draft_note_content["note"]
def test_create_merge_requests_draft_note(
project_merge_request, resp_create_merge_request_draft_note
):
draft_note = project_merge_request.draft_notes.create({"note": "Example title"})
assert isinstance(draft_note, ProjectMergeRequestDraftNote)
assert draft_note.note == draft_note_content["note"]
def test_update_merge_requests_draft_note(
project_merge_request, resp_update_merge_request_draft_note
):
draft_note = project_merge_request.draft_notes.get(1, lazy=True)
draft_note.note = "New title"
draft_note.save()
assert draft_note.note == "New title"
def test_delete_merge_requests_draft_note(
project_merge_request, resp_delete_merge_request_draft_note
):
draft_note = project_merge_request.draft_notes.get(1, lazy=True)
draft_note.delete()
def test_publish_merge_requests_draft_note(
project_merge_request, resp_publish_merge_request_draft_note
):
draft_note = project_merge_request.draft_notes.get(1, lazy=True)
draft_note.publish()
def test_bulk_publish_merge_requests_draft_notes(
project_merge_request, resp_bulk_publish_merge_request_draft_notes
):
project_merge_request.draft_notes.bulk_publish()
| 5,089 | Python | .py | 143 | 28.818182 | 95 | 0.663546 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,172 | test_registry_protection_rules.py | python-gitlab_python-gitlab/tests/unit/objects/test_registry_protection_rules.py | """
GitLab API: https://docs.gitlab.com/ee/api/project_container_registry_protection_rules.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectRegistryProtectionRule
protected_registry_content = {
"id": 1,
"project_id": 7,
"repository_path_pattern": "test/image",
"minimum_access_level_for_push": "maintainer",
"minimum_access_level_for_delete": "maintainer",
}
@pytest.fixture
def resp_list_protected_registries():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/registry/protection/rules",
json=[protected_registry_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_protected_registry():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/registry/protection/rules",
json=protected_registry_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_update_protected_registry():
updated_content = protected_registry_content.copy()
updated_content["repository_path_pattern"] = "abc*"
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PATCH,
url="http://localhost/api/v4/projects/1/registry/protection/rules/1",
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_project_protected_registries(project, resp_list_protected_registries):
protected_registry = project.registry_protection_rules.list()[0]
assert isinstance(protected_registry, ProjectRegistryProtectionRule)
assert protected_registry.repository_path_pattern == "test/image"
def test_create_project_protected_registry(project, resp_create_protected_registry):
protected_registry = project.registry_protection_rules.create(
{
"repository_path_pattern": "test/image",
"minimum_access_level_for_push": "maintainer",
}
)
assert isinstance(protected_registry, ProjectRegistryProtectionRule)
assert protected_registry.repository_path_pattern == "test/image"
def test_update_project_protected_registry(project, resp_update_protected_registry):
updated = project.registry_protection_rules.update(
1, {"repository_path_pattern": "abc*"}
)
assert updated["repository_path_pattern"] == "abc*"
| 2,627 | Python | .py | 66 | 32.80303 | 91 | 0.691159 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,173 | test_audit_events.py | python-gitlab_python-gitlab/tests/unit/objects/test_audit_events.py | """
GitLab API:
https://docs.gitlab.com/ee/api/audit_events.html#project-audit-events
"""
import re
import pytest
import responses
from gitlab.v4.objects.audit_events import (
AuditEvent,
GroupAuditEvent,
ProjectAuditEvent,
)
id = 5
audit_events_content = {
"id": 5,
"author_id": 1,
"entity_id": 7,
"entity_type": "Project",
"details": {
"change": "prevent merge request approval from reviewers",
"from": "",
"to": "true",
"author_name": "Administrator",
"target_id": 7,
"target_type": "Project",
"target_details": "twitter/typeahead-js",
"ip_address": "127.0.0.1",
"entity_path": "twitter/typeahead-js",
},
"created_at": "2020-05-26T22:55:04.230Z",
}
audit_events_url = re.compile(
r"http://localhost/api/v4/((groups|projects)/1/)?audit_events"
)
audit_events_url_id = re.compile(
rf"http://localhost/api/v4/((groups|projects)/1/)?audit_events/{id}"
)
@pytest.fixture
def resp_list_audit_events():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=audit_events_url,
json=[audit_events_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_audit_event():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=audit_events_url_id,
json=audit_events_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_instance_audit_events(gl, resp_list_audit_events):
audit_events = gl.audit_events.list()
assert isinstance(audit_events, list)
assert isinstance(audit_events[0], AuditEvent)
assert audit_events[0].id == id
def test_get_instance_audit_events(gl, resp_get_audit_event):
audit_event = gl.audit_events.get(id)
assert isinstance(audit_event, AuditEvent)
assert audit_event.id == id
def test_list_group_audit_events(group, resp_list_audit_events):
audit_events = group.audit_events.list()
assert isinstance(audit_events, list)
assert isinstance(audit_events[0], GroupAuditEvent)
assert audit_events[0].id == id
def test_get_group_audit_events(group, resp_get_audit_event):
audit_event = group.audit_events.get(id)
assert isinstance(audit_event, GroupAuditEvent)
assert audit_event.id == id
def test_list_project_audit_events(project, resp_list_audit_events):
audit_events = project.audit_events.list()
assert isinstance(audit_events, list)
assert isinstance(audit_events[0], ProjectAuditEvent)
assert audit_events[0].id == id
def test_get_project_audit_events(project, resp_get_audit_event):
audit_event = project.audit_events.get(id)
assert isinstance(audit_event, ProjectAuditEvent)
assert audit_event.id == id
| 2,928 | Python | .py | 86 | 28.360465 | 72 | 0.671869 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,174 | test_resource_label_events.py | python-gitlab_python-gitlab/tests/unit/objects/test_resource_label_events.py | """
GitLab API: https://docs.gitlab.com/ee/api/resource_label_events.html
"""
import pytest
import responses
from gitlab.v4.objects import (
GroupEpicResourceLabelEvent,
ProjectIssueResourceLabelEvent,
ProjectMergeRequestResourceLabelEvent,
)
@pytest.fixture()
def resp_group_epic_request_label_events():
epic_content = {"id": 1}
events_content = {"id": 1, "resource_type": "Epic"}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/groups/1/epics",
json=[epic_content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/groups/1/epics/1/resource_label_events",
json=[events_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_merge_request_label_events():
mr_content = {"iid": 1}
events_content = {"id": 1, "resource_type": "MergeRequest"}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests",
json=[mr_content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/1/resource_label_events",
json=[events_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_project_issue_label_events():
issue_content = {"iid": 1}
events_content = {"id": 1, "resource_type": "Issue"}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/issues",
json=[issue_content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/issues/1/resource_label_events",
json=[events_content],
content_type="application/json",
status=200,
)
yield rsps
def test_project_issue_label_events(project, resp_project_issue_label_events):
issue = project.issues.list()[0]
label_events = issue.resourcelabelevents.list()
assert isinstance(label_events, list)
label_event = label_events[0]
assert isinstance(label_event, ProjectIssueResourceLabelEvent)
assert label_event.resource_type == "Issue"
def test_merge_request_label_events(project, resp_merge_request_label_events):
mr = project.mergerequests.list()[0]
label_events = mr.resourcelabelevents.list()
assert isinstance(label_events, list)
label_event = label_events[0]
assert isinstance(label_event, ProjectMergeRequestResourceLabelEvent)
assert label_event.resource_type == "MergeRequest"
def test_group_epic_request_label_events(group, resp_group_epic_request_label_events):
epic = group.epics.list()[0]
label_events = epic.resourcelabelevents.list()
assert isinstance(label_events, list)
label_event = label_events[0]
assert isinstance(label_event, GroupEpicResourceLabelEvent)
assert label_event.resource_type == "Epic"
| 3,424 | Python | .py | 91 | 29.879121 | 92 | 0.649895 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,175 | test_personal_access_tokens.py | python-gitlab_python-gitlab/tests/unit/objects/test_personal_access_tokens.py | """
GitLab API:
https://docs.gitlab.com/ee/api/personal_access_tokens.html
https://docs.gitlab.com/ee/api/users.html#create-a-personal-access-token
"""
import pytest
import responses
from gitlab.v4.objects import PersonalAccessToken
user_id = 1
token_id = 1
token_name = "Test Token"
token_url = "http://localhost/api/v4/personal_access_tokens"
single_token_url = f"{token_url}/{token_id}"
self_token_url = f"{token_url}/self"
user_token_url = f"http://localhost/api/v4/users/{user_id}/personal_access_tokens"
content = {
"id": token_id,
"name": token_name,
"revoked": False,
"created_at": "2020-07-23T14:31:47.729Z",
"scopes": ["api"],
"active": True,
"user_id": user_id,
"expires_at": None,
}
@pytest.fixture
def resp_create_user_personal_access_token():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url=user_token_url,
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_personal_access_tokens():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=token_url,
json=[content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_personal_access_token():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=single_token_url,
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_personal_access_token_self():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=self_token_url,
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_delete_personal_access_token():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url=single_token_url,
status=204,
)
yield rsps
@pytest.fixture
def resp_rotate_personal_access_token(token_content):
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/personal_access_tokens/1/rotate",
json=token_content,
content_type="application/json",
status=200,
)
yield rsps
def test_create_personal_access_token(gl, resp_create_user_personal_access_token):
user = gl.users.get(1, lazy=True)
access_token = user.personal_access_tokens.create(
{"name": token_name, "scopes": "api"}
)
assert access_token.revoked is False
assert access_token.name == token_name
def test_list_personal_access_tokens(gl, resp_list_personal_access_tokens):
access_tokens = gl.personal_access_tokens.list()
assert len(access_tokens) == 1
assert access_tokens[0].revoked is False
assert access_tokens[0].name == token_name
def test_list_personal_access_tokens_filter(gl, resp_list_personal_access_tokens):
access_tokens = gl.personal_access_tokens.list(user_id=user_id)
assert len(access_tokens) == 1
assert access_tokens[0].revoked is False
assert access_tokens[0].user_id == user_id
def test_get_personal_access_token(gl, resp_get_personal_access_token):
access_token = gl.personal_access_tokens.get(token_id)
assert access_token.revoked is False
assert access_token.user_id == user_id
def test_get_personal_access_token_self(gl, resp_get_personal_access_token_self):
access_token = gl.personal_access_tokens.get("self")
assert access_token.revoked is False
assert access_token.user_id == user_id
def test_delete_personal_access_token(gl, resp_delete_personal_access_token):
access_token = gl.personal_access_tokens.get(token_id, lazy=True)
access_token.delete()
def test_revoke_personal_access_token_by_id(gl, resp_delete_personal_access_token):
gl.personal_access_tokens.delete(token_id)
def test_rotate_project_access_token(gl, resp_rotate_personal_access_token):
access_token = gl.personal_access_tokens.get(1, lazy=True)
access_token.rotate()
assert isinstance(access_token, PersonalAccessToken)
assert access_token.token == "s3cr3t"
| 4,464 | Python | .py | 124 | 29.491935 | 83 | 0.673171 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,176 | test_appearance.py | python-gitlab_python-gitlab/tests/unit/objects/test_appearance.py | """
GitLab API: https://docs.gitlab.com/ce/api/appearance.html
"""
import pytest
import responses
title = "GitLab Test Instance"
description = "gitlab-test.example.com"
new_title = "new-title"
new_description = "new-description"
@pytest.fixture
def resp_application_appearance():
content = {
"title": title,
"description": description,
"logo": "/uploads/-/system/appearance/logo/1/logo.png",
"header_logo": "/uploads/-/system/appearance/header_logo/1/header.png",
"favicon": "/uploads/-/system/appearance/favicon/1/favicon.png",
"new_project_guidelines": "Please read the FAQs for help.",
"header_message": "",
"footer_message": "",
"message_background_color": "#e75e40",
"message_font_color": "#ffffff",
"email_header_and_footer_enabled": False,
}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/application/appearance",
json=content,
content_type="application/json",
status=200,
)
updated_content = dict(content)
updated_content["title"] = new_title
updated_content["description"] = new_description
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/application/appearance",
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
def test_get_update_appearance(gl, resp_application_appearance):
appearance = gl.appearance.get()
assert appearance.title == title
assert appearance.description == description
appearance.title = new_title
appearance.description = new_description
appearance.save()
assert appearance.title == new_title
assert appearance.description == new_description
def test_update_appearance(gl, resp_application_appearance):
gl.appearance.update(title=new_title, description=new_description)
| 2,063 | Python | .py | 54 | 31.074074 | 79 | 0.664164 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,177 | test_project_merge_request_approvals.py | python-gitlab_python-gitlab/tests/unit/objects/test_project_merge_request_approvals.py | """
Gitlab API: https://docs.gitlab.com/ee/api/merge_request_approvals.html
"""
import copy
import pytest
import responses
import gitlab
from gitlab.mixins import UpdateMethod
approval_rule_id = 7
approval_rule_name = "security"
approvals_required = 3
user_ids = [5, 50]
group_ids = [5]
new_approval_rule_name = "new approval rule"
new_approval_rule_user_ids = user_ids
new_approval_rule_approvals_required = 2
updated_approval_rule_user_ids = [5]
updated_approval_rule_approvals_required = 1
@pytest.fixture
def resp_prj_approval_rules():
prj_ars_content = [
{
"id": approval_rule_id,
"name": approval_rule_name,
"rule_type": "regular",
"report_type": None,
"eligible_approvers": [
{
"id": user_ids[0],
"name": "John Doe",
"username": "jdoe",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/0?s=80&d=identicon",
"web_url": "http://localhost/jdoe",
},
{
"id": user_ids[1],
"name": "Group Member 1",
"username": "group_member_1",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/0?s=80&d=identicon",
"web_url": "http://localhost/group_member_1",
},
],
"approvals_required": approvals_required,
"users": [
{
"id": 5,
"name": "John Doe",
"username": "jdoe",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/0?s=80&d=identicon",
"web_url": "http://localhost/jdoe",
}
],
"groups": [
{
"id": 5,
"name": "group1",
"path": "group1",
"description": "",
"visibility": "public",
"lfs_enabled": False,
"avatar_url": None,
"web_url": "http://localhost/groups/group1",
"request_access_enabled": False,
"full_name": "group1",
"full_path": "group1",
"parent_id": None,
"ldap_cn": None,
"ldap_access": None,
}
],
"applies_to_all_protected_branches": False,
"protected_branches": [
{
"id": 1,
"name": "main",
"push_access_levels": [
{
"access_level": 30,
"access_level_description": "Developers + Maintainers",
}
],
"merge_access_levels": [
{
"access_level": 30,
"access_level_description": "Developers + Maintainers",
}
],
"unprotect_access_levels": [
{"access_level": 40, "access_level_description": "Maintainers"}
],
"code_owner_approval_required": "false",
}
],
"contains_hidden_groups": False,
}
]
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/approval_rules",
json=prj_ars_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/approval_rules/7",
json=prj_ars_content[0],
content_type="application/json",
status=200,
)
new_prj_ars_content = dict(prj_ars_content[0])
new_prj_ars_content["name"] = new_approval_rule_name
new_prj_ars_content["approvals_required"] = new_approval_rule_approvals_required
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/approval_rules",
json=new_prj_ars_content,
content_type="application/json",
status=200,
)
updated_mr_ars_content = copy.deepcopy(prj_ars_content[0])
updated_mr_ars_content["eligible_approvers"] = [
prj_ars_content[0]["eligible_approvers"][0]
]
updated_mr_ars_content["approvals_required"] = (
updated_approval_rule_approvals_required
)
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/approval_rules/7",
json=updated_mr_ars_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_mr_approval_rules():
mr_ars_content = [
{
"id": approval_rule_id,
"name": approval_rule_name,
"rule_type": "regular",
"eligible_approvers": [
{
"id": user_ids[0],
"name": "John Doe",
"username": "jdoe",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/0?s=80&d=identicon",
"web_url": "http://localhost/jdoe",
},
{
"id": user_ids[1],
"name": "Group Member 1",
"username": "group_member_1",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/0?s=80&d=identicon",
"web_url": "http://localhost/group_member_1",
},
],
"approvals_required": approvals_required,
"source_rule": None,
"users": [
{
"id": 5,
"name": "John Doe",
"username": "jdoe",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/0?s=80&d=identicon",
"web_url": "http://localhost/jdoe",
}
],
"groups": [
{
"id": 5,
"name": "group1",
"path": "group1",
"description": "",
"visibility": "public",
"lfs_enabled": False,
"avatar_url": None,
"web_url": "http://localhost/groups/group1",
"request_access_enabled": False,
"full_name": "group1",
"full_path": "group1",
"parent_id": None,
"ldap_cn": None,
"ldap_access": None,
}
],
"contains_hidden_groups": False,
"overridden": False,
}
]
approval_state_rules = copy.deepcopy(mr_ars_content)
approval_state_rules[0]["approved"] = False
approval_state_rules[0]["approved_by"] = []
mr_approval_state_content = {
"approval_rules_overwritten": False,
"rules": approval_state_rules,
}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/3/approval_rules",
json=mr_ars_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/3/approval_rules/7",
json=mr_ars_content[0],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/3/approval_state",
json=mr_approval_state_content,
content_type="application/json",
status=200,
)
new_mr_ars_content = dict(mr_ars_content[0])
new_mr_ars_content["name"] = new_approval_rule_name
new_mr_ars_content["approvals_required"] = new_approval_rule_approvals_required
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/merge_requests/3/approval_rules",
json=new_mr_ars_content,
content_type="application/json",
status=200,
)
updated_mr_ars_content = copy.deepcopy(mr_ars_content[0])
updated_mr_ars_content["eligible_approvers"] = [
mr_ars_content[0]["eligible_approvers"][0]
]
updated_mr_ars_content["approvals_required"] = (
updated_approval_rule_approvals_required
)
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/merge_requests/3/approval_rules/7",
json=updated_mr_ars_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_delete_mr_approval_rule():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/merge_requests/3/approval_rules/7",
status=204,
)
yield rsps
def test_project_approval_manager_update_method_post(project):
"""Ensure the
gitlab.v4.objects.merge_request_approvals.ProjectApprovalManager object has
_update_method set to UpdateMethod.POST"""
approvals = project.approvals
assert isinstance(
approvals, gitlab.v4.objects.merge_request_approvals.ProjectApprovalManager
)
assert approvals._update_method is UpdateMethod.POST
def test_list_project_approval_rules(project, resp_prj_approval_rules):
approval_rules = project.approvalrules.list()
assert len(approval_rules) == 1
assert approval_rules[0].name == approval_rule_name
assert approval_rules[0].id == approval_rule_id
assert (
repr(approval_rules[0])
== f"<ProjectApprovalRule id:{approval_rule_id} name:{approval_rule_name}>"
)
def test_list_merge_request_approval_rules(project, resp_mr_approval_rules):
approval_rules = project.mergerequests.get(3, lazy=True).approval_rules.list()
assert len(approval_rules) == 1
assert approval_rules[0].name == approval_rule_name
assert approval_rules[0].id == approval_rule_id
repr(approval_rules) # ensure that `repr()` doesn't raise an exception
def test_delete_merge_request_approval_rule(project, resp_delete_mr_approval_rule):
merge_request = project.mergerequests.get(3, lazy=True)
merge_request.approval_rules.delete(approval_rule_id)
def test_update_merge_request_approvals_set_approvers(project, resp_mr_approval_rules):
approvals = project.mergerequests.get(3, lazy=True).approvals
assert isinstance(
approvals,
gitlab.v4.objects.merge_request_approvals.ProjectMergeRequestApprovalManager,
)
assert approvals._update_method is UpdateMethod.POST
response = approvals.set_approvers(
updated_approval_rule_approvals_required,
approver_ids=updated_approval_rule_user_ids,
approver_group_ids=group_ids,
approval_rule_name=approval_rule_name,
)
assert response.approvals_required == updated_approval_rule_approvals_required
assert len(response.eligible_approvers) == len(updated_approval_rule_user_ids)
assert response.eligible_approvers[0]["id"] == updated_approval_rule_user_ids[0]
assert response.name == approval_rule_name
def test_create_merge_request_approvals_set_approvers(project, resp_mr_approval_rules):
approvals = project.mergerequests.get(3, lazy=True).approvals
assert isinstance(
approvals,
gitlab.v4.objects.merge_request_approvals.ProjectMergeRequestApprovalManager,
)
assert approvals._update_method is UpdateMethod.POST
response = approvals.set_approvers(
new_approval_rule_approvals_required,
approver_ids=new_approval_rule_user_ids,
approver_group_ids=group_ids,
approval_rule_name=new_approval_rule_name,
)
assert response.approvals_required == new_approval_rule_approvals_required
assert len(response.eligible_approvers) == len(new_approval_rule_user_ids)
assert response.eligible_approvers[0]["id"] == new_approval_rule_user_ids[0]
assert response.name == new_approval_rule_name
def test_create_merge_request_approval_rule(project, resp_mr_approval_rules):
approval_rules = project.mergerequests.get(3, lazy=True).approval_rules
data = {
"name": new_approval_rule_name,
"approvals_required": new_approval_rule_approvals_required,
"rule_type": "regular",
"user_ids": new_approval_rule_user_ids,
"group_ids": group_ids,
}
response = approval_rules.create(data)
assert response.approvals_required == new_approval_rule_approvals_required
assert len(response.eligible_approvers) == len(new_approval_rule_user_ids)
assert response.eligible_approvers[0]["id"] == new_approval_rule_user_ids[0]
assert response.name == new_approval_rule_name
def test_update_merge_request_approval_rule(project, resp_mr_approval_rules):
approval_rules = project.mergerequests.get(3, lazy=True).approval_rules
ar_1 = approval_rules.list()[0]
ar_1.user_ids = updated_approval_rule_user_ids
ar_1.approvals_required = updated_approval_rule_approvals_required
ar_1.save()
assert ar_1.approvals_required == updated_approval_rule_approvals_required
assert len(ar_1.eligible_approvers) == len(updated_approval_rule_user_ids)
assert ar_1.eligible_approvers[0]["id"] == updated_approval_rule_user_ids[0]
def test_get_merge_request_approval_rule(project, resp_mr_approval_rules):
merge_request = project.mergerequests.get(3, lazy=True)
approval_rule = merge_request.approval_rules.get(approval_rule_id)
assert isinstance(
approval_rule,
gitlab.v4.objects.merge_request_approvals.ProjectMergeRequestApprovalRule,
)
assert approval_rule.name == approval_rule_name
assert approval_rule.id == approval_rule_id
def test_get_merge_request_approval_state(project, resp_mr_approval_rules):
merge_request = project.mergerequests.get(3, lazy=True)
approval_state = merge_request.approval_state.get()
assert isinstance(
approval_state,
gitlab.v4.objects.merge_request_approvals.ProjectMergeRequestApprovalState,
)
assert not approval_state.approval_rules_overwritten
assert len(approval_state.rules) == 1
assert approval_state.rules[0]["name"] == approval_rule_name
assert approval_state.rules[0]["id"] == approval_rule_id
assert not approval_state.rules[0]["approved"]
assert approval_state.rules[0]["approved_by"] == []
| 15,314 | Python | .py | 367 | 30.166213 | 88 | 0.573193 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,178 | test_project_import_export.py | python-gitlab_python-gitlab/tests/unit/objects/test_project_import_export.py | """
GitLab API: https://docs.gitlab.com/ce/api/project_import_export.html
"""
import pytest
import responses
@pytest.fixture
def resp_import_project():
content = {
"id": 1,
"description": None,
"name": "api-project",
"name_with_namespace": "Administrator / api-project",
"path": "api-project",
"path_with_namespace": "root/api-project",
"created_at": "2018-02-13T09:05:58.023Z",
"import_status": "scheduled",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/import",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_remote_import():
content = {
"id": 1,
"description": None,
"name": "remote-project",
"name_with_namespace": "Administrator / remote-project",
"path": "remote-project",
"path_with_namespace": "root/remote-project",
"created_at": "2018-02-13T09:05:58.023Z",
"import_status": "scheduled",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/remote-import",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_remote_import_s3():
content = {
"id": 1,
"description": None,
"name": "remote-project-s3",
"name_with_namespace": "Administrator / remote-project-s3",
"path": "remote-project-s3",
"path_with_namespace": "root/remote-project-s3",
"created_at": "2018-02-13T09:05:58.023Z",
"import_status": "scheduled",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/remote-import-s3",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_import_status():
content = {
"id": 1,
"description": "Itaque perspiciatis minima aspernatur corporis consequatur.",
"name": "Gitlab Test",
"name_with_namespace": "Gitlab Org / Gitlab Test",
"path": "gitlab-test",
"path_with_namespace": "gitlab-org/gitlab-test",
"created_at": "2017-08-29T04:36:44.383Z",
"import_status": "finished",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/import",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_import_github():
content = {
"id": 27,
"name": "my-repo",
"full_path": "/root/my-repo",
"full_name": "Administrator / my-repo",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/import/github",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_import_bitbucket_server():
content = {
"id": 1,
"name": "project",
"import_status": "scheduled",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/import/bitbucket_server",
json=content,
content_type="application/json",
status=201,
)
yield rsps
def test_import_project(gl, resp_import_project):
project_import = gl.projects.import_project(
"file", "api-project", "api-project", "root"
)
assert project_import["import_status"] == "scheduled"
def test_remote_import(gl, resp_remote_import):
project_import = gl.projects.remote_import(
"https://whatever.com/url/file.tar.gz",
"remote-project",
"remote-project",
"root",
)
assert project_import["import_status"] == "scheduled"
def test_remote_import_s3(gl, resp_remote_import_s3):
project_import = gl.projects.remote_import_s3(
"remote-project",
"aws-region",
"aws-bucket-name",
"aws-file-key",
"aws-access-key-id",
"secret-access-key",
"remote-project",
"root",
)
assert project_import["import_status"] == "scheduled"
def test_import_project_with_override_params(gl, resp_import_project):
project_import = gl.projects.import_project(
"file", "api-project", override_params={"visibility": "private"}
)
assert project_import["import_status"] == "scheduled"
def test_refresh_project_import_status(project, resp_import_status):
project_import = project.imports.get()
project_import.refresh()
assert project_import.import_status == "finished"
def test_import_github(gl, resp_import_github):
base_path = "/root"
name = "my-repo"
ret = gl.projects.import_github("githubkey", 1234, base_path, name)
assert isinstance(ret, dict)
assert ret["name"] == name
assert ret["full_path"] == "/".join((base_path, name))
assert ret["full_name"].endswith(name)
def test_import_bitbucket_server(gl, resp_import_bitbucket_server):
res = gl.projects.import_bitbucket_server(
bitbucket_server_project="project",
bitbucket_server_repo="repo",
bitbucket_server_url="url",
bitbucket_server_username="username",
personal_access_token="token",
new_name="new_name",
target_namespace="namespace",
)
assert res["id"] == 1
assert res["name"] == "project"
assert res["import_status"] == "scheduled"
def test_create_project_export(project, resp_export):
export = project.exports.create()
assert export.message == "202 Accepted"
def test_refresh_project_export_status(project, resp_export):
export = project.exports.create()
export.refresh()
assert export.export_status == "finished"
def test_download_project_export(project, resp_export, binary_content):
export = project.exports.create()
download = export.download()
assert isinstance(download, bytes)
assert download == binary_content
| 6,454 | Python | .py | 189 | 26.592593 | 85 | 0.614038 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,179 | test_jobs.py | python-gitlab_python-gitlab/tests/unit/objects/test_jobs.py | """
GitLab API: https://docs.gitlab.com/ee/api/jobs.html
"""
from functools import partial
import pytest
import responses
from gitlab.v4.objects import ProjectJob
failed_job_content = {
"commit": {
"author_email": "admin@example.com",
"author_name": "Administrator",
},
"coverage": None,
"allow_failure": False,
"created_at": "2015-12-24T15:51:21.880Z",
"started_at": "2015-12-24T17:54:30.733Z",
"finished_at": "2015-12-24T17:54:31.198Z",
"duration": 0.465,
"queued_duration": 0.010,
"artifacts_expire_at": "2016-01-23T17:54:31.198Z",
"tag_list": ["docker runner", "macos-10.15"],
"id": 1,
"name": "rubocop",
"pipeline": {
"id": 1,
"project_id": 1,
},
"ref": "main",
"artifacts": [],
"runner": None,
"stage": "test",
"status": "failed",
"tag": False,
"web_url": "https://example.com/foo/bar/-/jobs/1",
"user": {"id": 1},
}
success_job_content = {
**failed_job_content,
"status": "success",
"id": failed_job_content["id"] + 1,
}
@pytest.fixture
def resp_get_job():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/jobs/1",
json=failed_job_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_cancel_job():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/jobs/1/cancel",
json=failed_job_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_retry_job():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/jobs/1/retry",
json=failed_job_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_list_job():
urls = [
"http://localhost/api/v4/projects/1/jobs",
"http://localhost/api/v4/projects/1/pipelines/1/jobs",
]
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
register_endpoint = partial(
rsps.add,
method=responses.GET,
content_type="application/json",
status=200,
)
for url in urls:
register_endpoint(
url=url,
json=[failed_job_content],
match=[responses.matchers.query_param_matcher({"scope[]": "failed"})],
)
register_endpoint(
url=url,
json=[success_job_content],
match=[responses.matchers.query_param_matcher({"scope[]": "success"})],
)
register_endpoint(
url=url,
json=[success_job_content, failed_job_content],
match=[
responses.matchers.query_string_matcher(
"scope[]=success&scope[]failed"
)
],
)
register_endpoint(
url=url,
json=[success_job_content, failed_job_content],
)
yield rsps
def test_get_project_job(project, resp_get_job):
job = project.jobs.get(1)
assert isinstance(job, ProjectJob)
assert job.ref == "main"
def test_cancel_project_job(project, resp_cancel_job):
job = project.jobs.get(1, lazy=True)
output = job.cancel()
assert output["ref"] == "main"
def test_retry_project_job(project, resp_retry_job):
job = project.jobs.get(1, lazy=True)
output = job.retry()
assert output["ref"] == "main"
def test_list_project_job(project, resp_list_job):
failed_jobs = project.jobs.list(scope="failed")
success_jobs = project.jobs.list(scope="success")
failed_and_success_jobs = project.jobs.list(scope=["failed", "success"])
pipeline_lazy = project.pipelines.get(1, lazy=True)
pjobs_failed = pipeline_lazy.jobs.list(scope="failed")
pjobs_success = pipeline_lazy.jobs.list(scope="success")
pjobs_failed_and_success = pipeline_lazy.jobs.list(scope=["failed", "success"])
prepared_urls = [c.request.url for c in resp_list_job.calls]
# Both pipelines and pipelines/jobs should behave the same way
# When `scope` is scalar, one can use scope=value or scope[]=value
assert set(failed_and_success_jobs) == set(failed_jobs + success_jobs)
assert set(pjobs_failed_and_success) == set(pjobs_failed + pjobs_success)
assert prepared_urls == [
"http://localhost/api/v4/projects/1/jobs?scope%5B%5D=failed",
"http://localhost/api/v4/projects/1/jobs?scope%5B%5D=success",
"http://localhost/api/v4/projects/1/jobs?scope%5B%5D=failed&scope%5B%5D=success",
"http://localhost/api/v4/projects/1/pipelines/1/jobs?scope%5B%5D=failed",
"http://localhost/api/v4/projects/1/pipelines/1/jobs?scope%5B%5D=success",
"http://localhost/api/v4/projects/1/pipelines/1/jobs?scope%5B%5D=failed&scope%5B%5D=success",
]
| 5,248 | Python | .py | 145 | 28.124138 | 101 | 0.603387 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,180 | test_keys.py | python-gitlab_python-gitlab/tests/unit/objects/test_keys.py | """
GitLab API: https://docs.gitlab.com/ce/api/keys.html
"""
import pytest
import responses
from gitlab.v4.objects import Key
key_content = {"id": 1, "title": "title", "key": "ssh-keytype AAAAC3Nza/key comment"}
@pytest.fixture
def resp_get_key_by_id():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/keys/1",
json=key_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_key_by_fingerprint():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/keys?fingerprint=foo",
json=key_content,
content_type="application/json",
status=200,
)
yield rsps
def test_get_key_by_id(gl, resp_get_key_by_id):
key = gl.keys.get(1)
assert isinstance(key, Key)
assert key.id == 1
assert key.title == "title"
def test_get_key_by_fingerprint(gl, resp_get_key_by_fingerprint):
key = gl.keys.get(fingerprint="foo")
assert isinstance(key, Key)
assert key.id == 1
assert key.title == "title"
def test_get_key_missing_attrs(gl):
with pytest.raises(AttributeError):
gl.keys.get()
| 1,330 | Python | .py | 42 | 25.119048 | 85 | 0.632941 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,181 | test_submodules.py | python-gitlab_python-gitlab/tests/unit/objects/test_submodules.py | """
GitLab API: https://docs.gitlab.com/ce/api/repository_submodules.html
"""
import pytest
import responses
@pytest.fixture
def resp_update_submodule():
content = {
"id": "ed899a2f4b50b4370feeea94676502b42383c746",
"short_id": "ed899a2f4b5",
"title": "Message",
"author_name": "Author",
"author_email": "author@example.com",
"committer_name": "Author",
"committer_email": "author@example.com",
"created_at": "2018-09-20T09:26:24.000-07:00",
"message": "Message",
"parent_ids": ["ae1d9fb46aa2b07ee9836d49862ec4e2c46fbbba"],
"committed_date": "2018-09-20T09:26:24.000-07:00",
"authored_date": "2018-09-20T09:26:24.000-07:00",
"status": None,
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/repository/submodules/foo%2Fbar",
json=content,
content_type="application/json",
status=200,
)
yield rsps
def test_update_submodule(project, resp_update_submodule):
ret = project.update_submodule(
submodule="foo/bar",
branch="main",
commit_sha="4c3674f66071e30b3311dac9b9ccc90502a72664",
commit_message="Message",
)
assert isinstance(ret, dict)
assert ret["message"] == "Message"
assert ret["id"] == "ed899a2f4b50b4370feeea94676502b42383c746"
| 1,455 | Python | .py | 41 | 28.195122 | 85 | 0.635653 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,182 | test_commits.py | python-gitlab_python-gitlab/tests/unit/objects/test_commits.py | """
GitLab API: https://docs.gitlab.com/ce/api/commits.html
"""
import pytest
import responses
@pytest.fixture
def resp_create_commit():
content = {
"id": "ed899a2f4b50b4370feeea94676502b42383c746",
"short_id": "ed899a2f",
"title": "Commit message",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/repository/commits",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_commit():
get_content = {
"id": "6b2257eabcec3db1f59dafbd84935e3caea04235",
"short_id": "6b2257ea",
"title": "Initial commit",
}
revert_content = {
"id": "8b090c1b79a14f2bd9e8a738f717824ff53aebad",
"short_id": "8b090c1b",
"title": 'Revert "Initial commit"',
}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/repository/commits/6b2257ea",
json=get_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/repository/commits/6b2257ea/revert",
json=revert_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_commit_gpg_signature():
content = {
"gpg_key_id": 1,
"gpg_key_primary_keyid": "8254AAB3FBD54AC9",
"gpg_key_user_name": "John Doe",
"gpg_key_user_email": "johndoe@example.com",
"verification_status": "verified",
"gpg_key_subkey_id": None,
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/repository/commits/6b2257ea/signature",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_commit_sequence():
content = {
"count": 1,
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/repository/commits/6b2257ea/sequence",
json=content,
content_type="application/json",
status=200,
)
yield rsps
def test_get_commit(project, resp_commit):
commit = project.commits.get("6b2257ea")
assert commit.short_id == "6b2257ea"
assert commit.title == "Initial commit"
def test_create_commit(project, resp_create_commit):
data = {
"branch": "main",
"commit_message": "Commit message",
"actions": [
{
"action": "create",
"file_path": "README",
"content": "",
}
],
}
commit = project.commits.create(data)
assert commit.short_id == "ed899a2f"
assert commit.title == data["commit_message"]
def test_revert_commit(project, resp_commit):
commit = project.commits.get("6b2257ea", lazy=True)
revert_commit = commit.revert(branch="main")
assert revert_commit["short_id"] == "8b090c1b"
assert revert_commit["title"] == 'Revert "Initial commit"'
def test_get_commit_gpg_signature(project, resp_get_commit_gpg_signature):
commit = project.commits.get("6b2257ea", lazy=True)
signature = commit.signature()
assert signature["gpg_key_primary_keyid"] == "8254AAB3FBD54AC9"
assert signature["verification_status"] == "verified"
def test_get_commit_sequence(project, resp_get_commit_sequence):
commit = project.commits.get("6b2257ea", lazy=True)
sequence = commit.sequence()
assert sequence["count"] == 1
| 3,938 | Python | .py | 115 | 26.295652 | 91 | 0.615 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,183 | test_merge_requests.py | python-gitlab_python-gitlab/tests/unit/objects/test_merge_requests.py | """
GitLab API:
https://docs.gitlab.com/ce/api/merge_requests.html
https://docs.gitlab.com/ee/api/deployments.html#list-of-merge-requests-associated-with-a-deployment
"""
import re
import pytest
import responses
from gitlab.base import RESTObjectList
from gitlab.v4.objects import (
ProjectDeploymentMergeRequest,
ProjectIssue,
ProjectMergeRequest,
ProjectMergeRequestReviewerDetail,
)
mr_content = {
"id": 1,
"iid": 1,
"project_id": 3,
"title": "test1",
"description": "fixed login page css paddings",
"state": "merged",
"merged_by": {
"id": 87854,
"name": "Douwe Maan",
"username": "DouweM",
"state": "active",
"avatar_url": "https://gitlab.example.com/uploads/-/system/user/avatar/87854/avatar.png",
"web_url": "https://gitlab.com/DouweM",
},
"reviewers": [
{
"id": 2,
"name": "Sam Bauch",
"username": "kenyatta_oconnell",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/956c92487c6f6f7616b536927e22c9a0?s=80&d=identicon",
"web_url": "http://gitlab.example.com//kenyatta_oconnell",
}
],
}
reviewers_content = [
{
"user": {
"id": 2,
"name": "Sam Bauch",
"username": "kenyatta_oconnell",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/956c92487c6f6f7616b536927e22c9a0?s=80&d=identicon",
"web_url": "http://gitlab.example.com//kenyatta_oconnell",
},
"state": "unreviewed",
"created_at": "2022-07-27T17:03:27.684Z",
}
]
related_issues = [
{
"id": 1,
"iid": 1,
"project_id": 1,
"title": "Fake Title for Merge Requests via API",
"description": "Something here",
"state": "closed",
"created_at": "2024-05-14T04:01:40.042Z",
"updated_at": "2024-06-13T05:29:13.661Z",
"closed_at": "2024-06-13T05:29:13.602Z",
"closed_by": {
"id": 2,
"name": "Sam Bauch",
"username": "kenyatta_oconnell",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/956c92487c6f6f7616b536927e22c9a0?s=80&d=identicon",
"web_url": "http://gitlab.example.com/kenyatta_oconnell",
},
"labels": [
"FakeCategory",
"fake:ml",
],
"assignees": [
{
"id": 2,
"name": "Sam Bauch",
"username": "kenyatta_oconnell",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/956c92487c6f6f7616b536927e22c9a0?s=80&d=identicon",
"web_url": "http://gitlab.example.com/kenyatta_oconnell",
}
],
"author": {
"id": 2,
"name": "Sam Bauch",
"username": "kenyatta_oconnell",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/956c92487c6f6f7616b536927e22c9a0?s=80&d=identicon",
"web_url": "http://gitlab.example.com//kenyatta_oconnell",
},
"type": "ISSUE",
"assignee": {
"id": 4459593,
"username": "fakeuser",
"name": "Fake User",
"state": "active",
"locked": False,
"avatar_url": "https://example.com/uploads/-/system/user/avatar/4459593/avatar.png",
"web_url": "https://example.com/fakeuser",
},
"user_notes_count": 9,
"merge_requests_count": 0,
"upvotes": 1,
"downvotes": 0,
"due_date": None,
"confidential": False,
"discussion_locked": None,
"issue_type": "issue",
"web_url": "https://example.com/fakeorg/fakeproject/-/issues/461536",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": None,
"human_total_time_spent": None,
},
"task_completion_status": {"count": 0, "completed_count": 0},
"weight": None,
"blocking_issues_count": 0,
}
]
@pytest.fixture
def resp_list_merge_requests():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(
r"http://localhost/api/v4/projects/1/(deployments/1/)?merge_requests"
),
json=[mr_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_merge_request_reviewers():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/1",
json=mr_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/3/merge_requests/1/reviewers",
json=reviewers_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_merge_requests_related_issues():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/1",
json=mr_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/1/related_issues",
json=related_issues,
content_type="application/json",
status=200,
)
yield rsps
def test_list_project_merge_requests(project, resp_list_merge_requests):
mrs = project.mergerequests.list()
assert isinstance(mrs[0], ProjectMergeRequest)
assert mrs[0].iid == mr_content["iid"]
def test_list_deployment_merge_requests(project, resp_list_merge_requests):
deployment = project.deployments.get(1, lazy=True)
mrs = deployment.mergerequests.list()
assert isinstance(mrs[0], ProjectDeploymentMergeRequest)
assert mrs[0].iid == mr_content["iid"]
def test_get_merge_request_reviewers(project, resp_get_merge_request_reviewers):
mr = project.mergerequests.get(1)
reviewers_details = mr.reviewer_details.list()
assert isinstance(mr, ProjectMergeRequest)
assert isinstance(reviewers_details, list)
assert isinstance(reviewers_details[0], ProjectMergeRequestReviewerDetail)
assert mr.reviewers[0]["name"] == reviewers_details[0].user["name"]
assert reviewers_details[0].state == "unreviewed"
assert reviewers_details[0].created_at == "2022-07-27T17:03:27.684Z"
def test_list_related_issues(project, resp_list_merge_requests_related_issues):
mr = project.mergerequests.get(1)
this_mr_related_issues = mr.related_issues()
the_issue = next(iter(this_mr_related_issues))
assert isinstance(mr, ProjectMergeRequest)
assert isinstance(this_mr_related_issues, RESTObjectList)
assert isinstance(the_issue, ProjectIssue)
assert the_issue.title == related_issues[0]["title"]
| 7,271 | Python | .py | 201 | 27.432836 | 114 | 0.590071 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,184 | test_remote_mirrors.py | python-gitlab_python-gitlab/tests/unit/objects/test_remote_mirrors.py | """
GitLab API: https://docs.gitlab.com/ce/api/remote_mirrors.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectRemoteMirror
@pytest.fixture
def resp_remote_mirrors():
content = {
"enabled": True,
"id": 1,
"last_error": None,
"last_successful_update_at": "2020-01-06T17:32:02.823Z",
"last_update_at": "2020-01-06T17:32:02.823Z",
"last_update_started_at": "2020-01-06T17:31:55.864Z",
"only_protected_branches": True,
"update_status": "none",
"url": "https://*****:*****@gitlab.com/gitlab-org/security/gitlab.git",
}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/remote_mirrors",
json=[content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/remote_mirrors",
json=content,
content_type="application/json",
status=200,
)
updated_content = dict(content)
updated_content["update_status"] = "finished"
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/remote_mirrors/1",
json=updated_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/remote_mirrors/1",
status=204,
)
yield rsps
def test_list_project_remote_mirrors(project, resp_remote_mirrors):
mirrors = project.remote_mirrors.list()
assert isinstance(mirrors, list)
assert isinstance(mirrors[0], ProjectRemoteMirror)
assert mirrors[0].enabled
def test_create_project_remote_mirror(project, resp_remote_mirrors):
mirror = project.remote_mirrors.create({"url": "https://example.com"})
assert isinstance(mirror, ProjectRemoteMirror)
assert mirror.update_status == "none"
def test_update_project_remote_mirror(project, resp_remote_mirrors):
mirror = project.remote_mirrors.create({"url": "https://example.com"})
mirror.only_protected_branches = True
mirror.save()
assert mirror.update_status == "finished"
assert mirror.only_protected_branches
def test_delete_project_remote_mirror(project, resp_remote_mirrors):
mirror = project.remote_mirrors.create({"url": "https://example.com"})
mirror.delete()
| 2,607 | Python | .py | 67 | 31.044776 | 79 | 0.643423 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,185 | test_projects.py | python-gitlab_python-gitlab/tests/unit/objects/test_projects.py | """
GitLab API: https://docs.gitlab.com/ce/api/projects.html
"""
from unittest.mock import mock_open, patch
import pytest
import responses
from gitlab import exceptions
from gitlab.const import DEVELOPER_ACCESS, SEARCH_SCOPE_ISSUES
from gitlab.v4.objects import (
Project,
ProjectFork,
ProjectUser,
StarredProject,
UserProject,
)
from gitlab.v4.objects.projects import ProjectStorage
project_content = {"name": "name", "id": 1}
project_with_owner_content = {
"name": "name",
"id": 1,
"owner": {"id": 1, "username": "owner_username", "name": "owner_name"},
}
languages_content = {
"python": 80.00,
"ruby": 99.99,
"CoffeeScript": 0.01,
}
user_content = {
"name": "first",
"id": 1,
"state": "active",
}
forks_content = [
{
"id": 1,
},
]
project_forked_from_content = {
"name": "name",
"id": 2,
"forks_count": 0,
"forked_from_project": {"id": 1, "name": "name", "forks_count": 1},
}
project_starrers_content = {
"starred_since": "2019-01-28T14:47:30.642Z",
"user": {
"id": 1,
"name": "name",
},
}
upload_file_content = {
"alt": "filename",
"url": "/uploads/66dbcd21ec5d24ed6ea225176098d52b/filename.png",
"full_path": "/namespace/project/uploads/66dbcd21ec5d24ed6ea225176098d52b/filename.png",
"markdown": "",
}
share_project_content = {
"id": 1,
"project_id": 1,
"group_id": 1,
"group_access": 30,
"expires_at": None,
}
push_rules_content = {"id": 1, "deny_delete_tag": True}
search_issues_content = [
{
"id": 1,
"iid": 1,
"project_id": 1,
"title": "Issue",
}
]
pipeline_trigger_content = {
"id": 1,
"iid": 1,
"project_id": 1,
"ref": "main",
"status": "created",
"source": "trigger",
}
@pytest.fixture
def resp_get_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1",
json=project_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects",
json=project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_create_user_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/user/1",
json=project_with_owner_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_fork_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/fork",
json=project_forked_from_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_update_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1",
json=project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_get_project_storage():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/storage",
json={"project_id": 1, "disk_path": "/disk/path"},
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_user_projects():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1/projects",
json=[project_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_star_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/star",
json=project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_unstar_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/unstar",
json=project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_list_project_starrers():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/starrers",
json=[project_starrers_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_starred_projects():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1/starred_projects",
json=[project_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_users():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/users",
json=[user_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_forks():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/forks",
json=forks_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_languages():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/languages",
json=languages_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_projects():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects",
json=[project_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_transfer_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/transfer",
json=project_content,
content_type="application/json",
status=200,
match=[
responses.matchers.json_params_matcher({"namespace": "test-namespace"})
],
)
yield rsps
@pytest.fixture
def resp_archive_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/archive",
json=project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_unarchive_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/unarchive",
json=project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_delete_project(accepted_content):
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1",
json=accepted_content,
content_type="application/json",
status=202,
)
yield rsps
@pytest.fixture
def resp_upload_file_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/uploads",
json=upload_file_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_share_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/share",
json=share_project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_unshare_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/share/1",
status=204,
)
yield rsps
@pytest.fixture
def resp_create_fork_relation():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/2/fork/1",
json=project_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_delete_fork_relation():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/2/fork",
status=204,
)
yield rsps
@pytest.fixture
def resp_trigger_pipeline():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/trigger/pipeline",
json=pipeline_trigger_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_search_project_resources_by_name():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/search?scope=issues&search=Issue",
json=search_issues_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_start_housekeeping():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/housekeeping",
json={},
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_list_push_rules_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/push_rule",
json=push_rules_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_push_rules_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/push_rule",
json=push_rules_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_update_push_rules_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/push_rule",
json=push_rules_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/push_rule",
json=push_rules_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_delete_push_rules_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/push_rule",
json=push_rules_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/push_rule",
status=204,
)
yield rsps
@pytest.fixture
def resp_restore_project(created_content):
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/restore",
json=created_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_start_pull_mirroring_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/mirror/pull",
json={},
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_pull_mirror_details_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/mirror/pull",
json={
"id": 101486,
"last_error": None,
"last_successful_update_at": "2020-01-06T17:32:02.823Z",
"last_update_at": "2020-01-06T17:32:02.823Z",
"last_update_started_at": "2020-01-06T17:31:55.864Z",
"update_status": "finished",
"url": "https://*****:*****@gitlab.com/gitlab-org/security/gitlab.git",
},
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_snapshot_project():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/snapshot",
content_type="application/x-tar",
status=200,
)
yield rsps
@pytest.fixture
def resp_artifact():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/jobs/artifacts/ref_name/raw/artifact_path?job=job",
content_type="application/x-tar",
status=200,
)
yield rsps
def test_get_project(gl, resp_get_project):
data = gl.projects.get(1)
assert isinstance(data, Project)
assert data.name == "name"
assert data.id == 1
def test_list_projects(gl, resp_list_projects):
projects = gl.projects.list()
assert isinstance(projects[0], Project)
assert projects[0].name == "name"
def test_list_user_projects(user, resp_list_user_projects):
user_project = user.projects.list()[0]
assert isinstance(user_project, UserProject)
assert user_project.name == "name"
assert user_project.id == 1
def test_list_user_starred_projects(user, resp_list_starred_projects):
starred_projects = user.starred_projects.list()[0]
assert isinstance(starred_projects, StarredProject)
assert starred_projects.name == "name"
assert starred_projects.id == 1
def test_list_project_users(project, resp_list_users):
user = project.users.list()[0]
assert isinstance(user, ProjectUser)
assert user.id == 1
assert user.name == "first"
assert user.state == "active"
def test_create_project(gl, resp_create_project):
project = gl.projects.create({"name": "name"})
assert project.id == 1
assert project.name == "name"
def test_create_user_project(user, resp_create_user_project):
user_project = user.projects.create({"name": "name"})
assert user_project.id == 1
assert user_project.name == "name"
assert user_project.owner
assert user_project.owner.get("id") == user.id
assert user_project.owner.get("name") == "owner_name"
assert user_project.owner.get("username") == "owner_username"
def test_update_project(project, resp_update_project):
project.snippets_enabled = 1
project.save()
def test_fork_project(project, resp_fork_project):
fork = project.forks.create({})
assert fork.id == 2
assert fork.name == "name"
assert fork.forks_count == 0
assert fork.forked_from_project
assert fork.forked_from_project.get("id") == project.id
assert fork.forked_from_project.get("name") == "name"
assert fork.forked_from_project.get("forks_count") == 1
def test_list_project_forks(project, resp_list_forks):
fork = project.forks.list()[0]
assert isinstance(fork, ProjectFork)
assert fork.id == 1
def test_star_project(project, resp_star_project):
project.star()
def test_unstar_project(project, resp_unstar_project):
project.unstar()
@pytest.mark.skip(reason="missing test")
def test_list_project_starrers(project, resp_list_project_starrers):
pass
def test_get_project_languages(project, resp_list_languages):
python = project.languages().get("python")
ruby = project.languages().get("ruby")
coffee_script = project.languages().get("CoffeeScript")
assert python == 80.00
assert ruby == 99.99
assert coffee_script == 00.01
def test_get_project_storage(project, resp_get_project_storage):
storage = project.storage.get()
assert isinstance(storage, ProjectStorage)
assert storage.disk_path == "/disk/path"
def test_archive_project(project, resp_archive_project):
project.archive()
def test_unarchive_project(project, resp_unarchive_project):
project.unarchive()
def test_delete_project(project, resp_delete_project):
project.delete()
def test_upload_file(project, resp_upload_file_project):
project.upload("filename.png", "raw\nfile\ndata")
def test_upload_file_with_filepath(project, resp_upload_file_project):
with patch("builtins.open", mock_open(read_data="raw\nfile\ndata")):
project.upload("filename.png", None, "/filepath")
def test_upload_file_without_filepath_nor_filedata(project):
with pytest.raises(
exceptions.GitlabUploadError, match="No file contents or path specified"
):
project.upload("filename.png")
def test_upload_file_with_filepath_and_filedata(project):
with pytest.raises(
exceptions.GitlabUploadError, match="File contents and file path specified"
):
project.upload("filename.png", "filedata", "/filepath")
def test_share_project(project, group, resp_share_project):
project.share(group.id, DEVELOPER_ACCESS)
def test_delete_shared_project_link(project, group, resp_unshare_project):
project.unshare(group.id)
def test_trigger_pipeline_project(project, resp_trigger_pipeline):
project.trigger_pipeline("MOCK_PIPELINE_TRIGGER_TOKEN", "main")
def test_create_forked_from_relationship(
project, another_project, resp_create_fork_relation
):
another_project.create_fork_relation(project.id)
def test_delete_forked_from_relationship(another_project, resp_delete_fork_relation):
another_project.delete_fork_relation()
def test_search_project_resources_by_name(
project, resp_search_project_resources_by_name
):
issue = project.search(SEARCH_SCOPE_ISSUES, "Issue")[0]
assert issue
assert issue.get("title") == "Issue"
def test_project_housekeeping(project, resp_start_housekeeping):
project.housekeeping()
def test_list_project_push_rules(project, resp_list_push_rules_project):
pr = project.pushrules.get()
assert pr
assert pr.deny_delete_tag
def test_create_project_push_rule(project, resp_create_push_rules_project):
project.pushrules.create({"deny_delete_tag": True})
def test_update_project_push_rule(
project,
resp_update_push_rules_project,
):
pr = project.pushrules.get()
pr.deny_delete_tag = False
pr.save()
def test_delete_project_push_rule(project, resp_delete_push_rules_project):
pr = project.pushrules.get()
pr.delete()
def test_transfer_project(project, resp_transfer_project):
project.transfer("test-namespace")
def test_project_pull_mirror(project, resp_start_pull_mirroring_project):
project.mirror_pull()
def test_project_pull_mirror_details(project, resp_pull_mirror_details_project):
details = project.mirror_pull_details()
assert details["last_error"] is None
assert details["update_status"] == "finished"
def test_project_restore(project, resp_restore_project):
project.restore()
def test_project_snapshot(project, resp_snapshot_project):
tar_file = project.snapshot()
assert isinstance(tar_file, bytes)
| 21,091 | Python | .py | 634 | 25.68612 | 103 | 0.630534 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,186 | test_environments.py | python-gitlab_python-gitlab/tests/unit/objects/test_environments.py | """
GitLab API: https://docs.gitlab.com/ce/api/environments.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectEnvironment, ProjectProtectedEnvironment
@pytest.fixture
def resp_get_environment():
content = {"name": "environment_name", "id": 1, "last_deployment": "sometime"}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/environments/1",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_protected_environment():
content = {
"name": "protected_environment_name",
"last_deployment": "my birthday",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/protected_environments/2",
json=content,
content_type="application/json",
status=200,
)
yield rsps
def test_project_environments(project, resp_get_environment):
environment = project.environments.get(1)
assert isinstance(environment, ProjectEnvironment)
assert environment.id == 1
assert environment.last_deployment == "sometime"
assert environment.name == "environment_name"
def test_project_protected_environments(project, resp_get_protected_environment):
protected_environment = project.protected_environments.get(2)
assert isinstance(protected_environment, ProjectProtectedEnvironment)
assert protected_environment.last_deployment == "my birthday"
assert protected_environment.name == "protected_environment_name"
| 1,722 | Python | .py | 44 | 32.409091 | 82 | 0.697479 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,187 | test_packages.py | python-gitlab_python-gitlab/tests/unit/objects/test_packages.py | """
GitLab API: https://docs.gitlab.com/ce/api/packages.html
"""
import re
import pytest
import responses
from gitlab import exceptions as exc
from gitlab.v4.objects import (
GenericPackage,
GroupPackage,
ProjectPackage,
ProjectPackageFile,
ProjectPackagePipeline,
)
package_content = {
"id": 1,
"name": "com/mycompany/my-app",
"version": "1.0-SNAPSHOT",
"package_type": "maven",
"_links": {
"web_path": "/namespace1/project1/-/packages/1",
"delete_api_path": "/namespace1/project1/-/packages/1",
},
"created_at": "2019-11-27T03:37:38.711Z",
"pipeline": {
"id": 123,
"status": "pending",
"ref": "new-pipeline",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"web_url": "https://example.com/foo/bar/pipelines/47",
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"user": {
"name": "Administrator",
"avatar_url": "https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
},
},
"versions": [
{
"id": 2,
"version": "2.0-SNAPSHOT",
"created_at": "2020-04-28T04:42:11.573Z",
"pipeline": {
"id": 234,
"status": "pending",
"ref": "new-pipeline",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"web_url": "https://example.com/foo/bar/pipelines/58",
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"user": {
"name": "Administrator",
"avatar_url": "https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
},
},
}
],
}
package_file_content = [
{
"id": 25,
"package_id": 1,
"created_at": "2018-11-07T15:25:52.199Z",
"file_name": "my-app-1.5-20181107.152550-1.jar",
"size": 2421,
"file_md5": "58e6a45a629910c6ff99145a688971ac",
"file_sha1": "ebd193463d3915d7e22219f52740056dfd26cbfe",
"pipelines": [
{
"id": 123,
"status": "pending",
"ref": "new-pipeline",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"web_url": "https://example.com/foo/bar/pipelines/47",
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"user": {
"name": "Administrator",
"avatar_url": "https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
},
}
],
},
{
"id": 26,
"package_id": 1,
"created_at": "2018-11-07T15:25:56.776Z",
"file_name": "my-app-1.5-20181107.152550-1.pom",
"size": 1122,
"file_md5": "d90f11d851e17c5513586b4a7e98f1b2",
"file_sha1": "9608d068fe88aff85781811a42f32d97feb440b5",
},
{
"id": 27,
"package_id": 1,
"created_at": "2018-11-07T15:26:00.556Z",
"file_name": "maven-metadata.xml",
"size": 767,
"file_md5": "6dfd0cce1203145a927fef5e3a1c650c",
"file_sha1": "d25932de56052d320a8ac156f745ece73f6a8cd2",
},
]
package_pipeline_content = [
{
"id": 123,
"iid": 1,
"project_id": 1,
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"ref": "new-pipeline",
"status": "failed",
"source": "push",
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"web_url": "https://example.com/foo/bar/pipelines/47",
"user": {
"id": 1,
"username": "root",
"name": "Administrator",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\u0026d=identicon",
"web_url": "http://gdk.test:3001/root",
},
},
{
"id": 234,
"iid": 2,
"project_id": 1,
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"ref": "new-pipeline",
"status": "failed",
"source": "push",
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
"web_url": "https://example.com/foo/bar/pipelines/58",
"user": {
"id": 1,
"username": "root",
"name": "Administrator",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\u0026d=identicon",
"web_url": "http://gdk.test:3001/root",
},
},
]
package_name = "hello-world"
package_version = "v1.0.0"
file_name = "hello.tar.gz"
file_content = "package content"
package_url = f"http://localhost/api/v4/projects/1/packages/generic/{package_name}/{package_version}/{file_name}"
@pytest.fixture
def resp_list_packages():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(r"http://localhost/api/v4/(groups|projects)/1/packages"),
json=[package_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_package():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/packages/1",
json=package_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_delete_package():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/packages/1",
status=204,
)
yield rsps
@pytest.fixture
def resp_delete_package_file():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/packages/1/package_files/1",
status=204,
)
yield rsps
@pytest.fixture
def resp_delete_package_file_list():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(
r"http://localhost/api/v4/projects/1/packages/1/package_files"
),
json=package_file_content,
content_type="application/json",
status=200,
)
for pkg_file_id in range(25, 28):
rsps.add(
method=responses.DELETE,
url=f"http://localhost/api/v4/projects/1/packages/1/package_files/{pkg_file_id}",
status=204,
)
yield rsps
@pytest.fixture
def resp_list_package_files():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(
r"http://localhost/api/v4/projects/1/packages/1/package_files"
),
json=package_file_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_list_package_pipelines():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=re.compile(r"http://localhost/api/v4/projects/1/packages/1/pipelines"),
json=package_pipeline_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_upload_generic_package(created_content):
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url=package_url,
json=created_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_download_generic_package(created_content):
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=package_url,
body=file_content,
content_type="application/octet-stream",
status=200,
)
yield rsps
def test_list_project_packages(project, resp_list_packages):
packages = project.packages.list()
assert isinstance(packages, list)
assert isinstance(packages[0], ProjectPackage)
assert packages[0].version == "1.0-SNAPSHOT"
def test_list_group_packages(group, resp_list_packages):
packages = group.packages.list()
assert isinstance(packages, list)
assert isinstance(packages[0], GroupPackage)
assert packages[0].version == "1.0-SNAPSHOT"
def test_get_project_package(project, resp_get_package):
package = project.packages.get(1)
assert isinstance(package, ProjectPackage)
assert package.version == "1.0-SNAPSHOT"
def test_delete_project_package(project, resp_delete_package):
package = project.packages.get(1, lazy=True)
package.delete()
def test_list_project_package_files(project, resp_list_package_files):
package = project.packages.get(1, lazy=True)
package_files = package.package_files.list()
assert isinstance(package_files, list)
assert isinstance(package_files[0], ProjectPackageFile)
assert package_files[0].id == 25
def test_delete_project_package_file_from_package_object(
project, resp_delete_package_file
):
package = project.packages.get(1, lazy=True)
package.package_files.delete(1)
def test_delete_project_package_file_from_package_file_object(
project, resp_delete_package_file_list
):
package = project.packages.get(1, lazy=True)
for package_file in package.package_files.list():
package_file.delete()
def test_list_project_package_pipelines(project, resp_list_package_pipelines):
package = project.packages.get(1, lazy=True)
pipelines = package.pipelines.list()
assert isinstance(pipelines, list)
assert isinstance(pipelines[0], ProjectPackagePipeline)
assert pipelines[0].id == 123
def test_upload_generic_package(tmp_path, project, resp_upload_generic_package):
path = tmp_path / file_name
path.write_text(file_content, encoding="utf-8")
package = project.generic_packages.upload(
package_name=package_name,
package_version=package_version,
file_name=file_name,
path=path,
)
assert isinstance(package, GenericPackage)
def test_upload_generic_package_nonexistent_path(tmp_path, project):
with pytest.raises(exc.GitlabUploadError):
project.generic_packages.upload(
package_name=package_name,
package_version=package_version,
file_name=file_name,
path="bad",
)
def test_upload_generic_package_no_file_and_no_data(tmp_path, project):
path = tmp_path / file_name
path.write_text(file_content, encoding="utf-8")
with pytest.raises(exc.GitlabUploadError):
project.generic_packages.upload(
package_name=package_name,
package_version=package_version,
file_name=file_name,
)
def test_upload_generic_package_file_and_data(tmp_path, project):
path = tmp_path / file_name
path.write_text(file_content, encoding="utf-8")
with pytest.raises(exc.GitlabUploadError):
project.generic_packages.upload(
package_name=package_name,
package_version=package_version,
file_name=file_name,
path=path,
data=path.read_bytes(),
)
def test_upload_generic_package_bytes(tmp_path, project, resp_upload_generic_package):
path = tmp_path / file_name
path.write_text(file_content, encoding="utf-8")
package = project.generic_packages.upload(
package_name=package_name,
package_version=package_version,
file_name=file_name,
data=path.read_bytes(),
)
assert isinstance(package, GenericPackage)
def test_upload_generic_package_file(tmp_path, project, resp_upload_generic_package):
path = tmp_path / file_name
path.write_text(file_content, encoding="utf-8")
package = project.generic_packages.upload(
package_name=package_name,
package_version=package_version,
file_name=file_name,
data=path.open(mode="rb"),
)
assert isinstance(package, GenericPackage)
def test_download_generic_package(project, resp_download_generic_package):
package = project.generic_packages.download(
package_name=package_name,
package_version=package_version,
file_name=file_name,
)
assert isinstance(package, bytes)
| 12,878 | Python | .py | 359 | 27.384401 | 118 | 0.611357 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,188 | test_statistics.py | python-gitlab_python-gitlab/tests/unit/objects/test_statistics.py | """
GitLab API: https://docs.gitlab.com/ee/api/statistics.html
"""
import pytest
import responses
content = {
"forks": "10",
"issues": "76",
"merge_requests": "27",
"notes": "954",
"snippets": "50",
"ssh_keys": "10",
"milestones": "40",
"users": "50",
"groups": "10",
"projects": "20",
"active_users": "50",
}
@pytest.fixture
def resp_application_statistics():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/application/statistics",
json=content,
content_type="application/json",
status=200,
)
yield rsps
def test_get_statistics(gl, resp_application_statistics):
statistics = gl.statistics.get()
assert statistics.forks == content["forks"]
assert statistics.merge_requests == content["merge_requests"]
assert statistics.notes == content["notes"]
assert statistics.snippets == content["snippets"]
assert statistics.ssh_keys == content["ssh_keys"]
assert statistics.milestones == content["milestones"]
assert statistics.users == content["users"]
assert statistics.groups == content["groups"]
assert statistics.projects == content["projects"]
assert statistics.active_users == content["active_users"]
| 1,334 | Python | .py | 41 | 27.073171 | 65 | 0.652411 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,189 | test_pipeline_schedules.py | python-gitlab_python-gitlab/tests/unit/objects/test_pipeline_schedules.py | """
GitLab API: https://docs.gitlab.com/ce/api/pipeline_schedules.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectPipelineSchedulePipeline
pipeline_content = {
"id": 48,
"iid": 13,
"project_id": 29,
"status": "pending",
"source": "scheduled",
"ref": "new-pipeline",
"sha": "eb94b618fb5865b26e80fdd8ae531b7a63ad851a",
"web_url": "https://example.com/foo/bar/pipelines/48",
"created_at": "2016-08-12T10:06:04.561Z",
"updated_at": "2016-08-12T10:09:56.223Z",
}
@pytest.fixture
def resp_create_pipeline_schedule():
content = {
"id": 14,
"description": "Build packages",
"ref": "main",
"cron": "0 1 * * 5",
"cron_timezone": "UTC",
"next_run_at": "2017-05-26T01:00:00.000Z",
"active": True,
"created_at": "2017-05-19T13:43:08.169Z",
"updated_at": "2017-05-19T13:43:08.169Z",
"last_pipeline": None,
"owner": {
"name": "Administrator",
"username": "root",
"id": 1,
"state": "active",
"avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
"web_url": "https://gitlab.example.com/root",
},
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/pipeline_schedules",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_play_pipeline_schedule(created_content):
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/pipeline_schedules/1/play",
json=created_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_list_schedule_pipelines():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipeline_schedules/1/pipelines",
json=[pipeline_content],
content_type="application/json",
status=200,
)
yield rsps
def test_create_project_pipeline_schedule(project, resp_create_pipeline_schedule):
description = "Build packages"
cronline = "0 1 * * 5"
sched = project.pipelineschedules.create(
{"ref": "main", "description": description, "cron": cronline}
)
assert sched is not None
assert description == sched.description
assert cronline == sched.cron
def test_play_project_pipeline_schedule(schedule, resp_play_pipeline_schedule):
play_result = schedule.play()
assert play_result is not None
assert "message" in play_result
assert play_result["message"] == "201 Created"
def test_list_project_pipeline_schedule_pipelines(
schedule, resp_list_schedule_pipelines
):
pipelines = schedule.pipelines.list()
assert isinstance(pipelines, list)
assert isinstance(pipelines[0], ProjectPipelineSchedulePipeline)
assert pipelines[0].source == "scheduled"
| 3,223 | Python | .py | 92 | 27.858696 | 109 | 0.633708 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,190 | test_package_protection_rules.py | python-gitlab_python-gitlab/tests/unit/objects/test_package_protection_rules.py | """
GitLab API: https://docs.gitlab.com/ee/api/project_packages_protection_rules.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectPackageProtectionRule
protected_package_content = {
"id": 1,
"project_id": 7,
"package_name_pattern": "v*",
"package_type": "npm",
"minimum_access_level_for_push": "maintainer",
}
@pytest.fixture
def resp_list_protected_packages():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/packages/protection/rules",
json=[protected_package_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_protected_package():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/packages/protection/rules",
json=protected_package_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_update_protected_package():
updated_content = protected_package_content.copy()
updated_content["package_name_pattern"] = "abc*"
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PATCH,
url="http://localhost/api/v4/projects/1/packages/protection/rules/1",
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_delete_protected_package():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/packages/protection/rules/1",
status=204,
)
yield rsps
def test_list_project_protected_packages(project, resp_list_protected_packages):
protected_package = project.package_protection_rules.list()[0]
assert isinstance(protected_package, ProjectPackageProtectionRule)
assert protected_package.package_type == "npm"
def test_create_project_protected_package(project, resp_create_protected_package):
protected_package = project.package_protection_rules.create(
{
"package_name_pattern": "v*",
"package_type": "npm",
"minimum_access_level_for_push": "maintainer",
}
)
assert isinstance(protected_package, ProjectPackageProtectionRule)
assert protected_package.package_type == "npm"
def test_update_project_protected_package(project, resp_update_protected_package):
updated = project.package_protection_rules.update(
1, {"package_name_pattern": "abc*"}
)
assert updated["package_name_pattern"] == "abc*"
def test_delete_project_protected_package(project, resp_delete_protected_package):
project.package_protection_rules.delete(1)
| 2,951 | Python | .py | 78 | 30.679487 | 82 | 0.67578 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,191 | test_secure_files.py | python-gitlab_python-gitlab/tests/unit/objects/test_secure_files.py | """
GitLab API: https://docs.gitlab.com/ee/api/secure_files.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectSecureFile
secure_file_content = {
"id": 1,
"name": "myfile.jks",
"checksum": "16630b189ab34b2e3504f4758e1054d2e478deda510b2b08cc0ef38d12e80aac",
"checksum_algorithm": "sha256",
"created_at": "2022-02-22T22:22:22.222Z",
"expires_at": None,
"metadata": None,
}
@pytest.fixture
def resp_list_secure_files():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/secure_files",
json=[secure_file_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_secure_file():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/secure_files",
json=secure_file_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_download_secure_file(binary_content):
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/secure_files/1",
json=secure_file_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/secure_files/1/download",
body=binary_content,
content_type="application/octet-stream",
status=200,
)
yield rsps
@pytest.fixture
def resp_remove_secure_file():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/secure_files/1",
status=204,
)
yield rsps
def test_list_secure_files(project, resp_list_secure_files):
secure_files = project.secure_files.list()
assert len(secure_files) == 1
assert secure_files[0].id == 1
assert secure_files[0].name == "myfile.jks"
def test_create_secure_file(project, resp_create_secure_file):
secure_files = project.secure_files.create({"name": "test", "file": "myfile.jks"})
assert secure_files.id == 1
assert secure_files.name == "myfile.jks"
def test_download_secure_file(project, binary_content, resp_download_secure_file):
secure_file = project.secure_files.get(1)
secure_content = secure_file.download()
assert isinstance(secure_file, ProjectSecureFile)
assert secure_content == binary_content
def test_remove_secure_file(project, resp_remove_secure_file):
project.secure_files.delete(1)
| 2,942 | Python | .py | 80 | 29.5375 | 86 | 0.659866 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,192 | test_cluster_agents.py | python-gitlab_python-gitlab/tests/unit/objects/test_cluster_agents.py | """
GitLab API: https://docs.gitlab.com/ee/api/cluster_agents.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectClusterAgent
agent_content = {
"id": 1,
"name": "agent-1",
"config_project": {
"id": 20,
"description": "",
"name": "test",
"name_with_namespace": "Administrator / test",
"path": "test",
"path_with_namespace": "root/test",
"created_at": "2022-03-20T20:42:40.221Z",
},
"created_at": "2022-04-20T20:42:40.221Z",
"created_by_user_id": 42,
}
@pytest.fixture
def resp_list_project_cluster_agents():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/cluster_agents",
json=[agent_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_project_cluster_agent():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/cluster_agents/1",
json=agent_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_project_cluster_agent():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/cluster_agents",
json=agent_content,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_delete_project_cluster_agent():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/cluster_agents/1",
status=204,
)
yield rsps
def test_list_project_cluster_agents(project, resp_list_project_cluster_agents):
agent = project.cluster_agents.list()[0]
assert isinstance(agent, ProjectClusterAgent)
assert agent.name == "agent-1"
def test_get_project_cluster_agent(project, resp_get_project_cluster_agent):
agent = project.cluster_agents.get(1)
assert isinstance(agent, ProjectClusterAgent)
assert agent.name == "agent-1"
def test_create_project_cluster_agent(project, resp_create_project_cluster_agent):
agent = project.cluster_agents.create({"name": "agent-1"})
assert isinstance(agent, ProjectClusterAgent)
assert agent.name == "agent-1"
def test_delete_project_cluster_agent(project, resp_delete_project_cluster_agent):
agent = project.cluster_agents.get(1, lazy=True)
agent.delete()
| 2,710 | Python | .py | 78 | 27.705128 | 82 | 0.647532 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,193 | test_variables.py | python-gitlab_python-gitlab/tests/unit/objects/test_variables.py | """
GitLab API:
https://docs.gitlab.com/ee/api/instance_level_ci_variables.html
https://docs.gitlab.com/ee/api/project_level_variables.html
https://docs.gitlab.com/ee/api/group_level_variables.html
"""
import re
import pytest
import responses
from gitlab.v4.objects import GroupVariable, ProjectVariable, Variable
key = "TEST_VARIABLE_1"
value = "TEST_1"
new_value = "TEST_2"
variable_content = {
"key": key,
"variable_type": "env_var",
"value": value,
"protected": False,
"masked": True,
}
variables_url = re.compile(
r"http://localhost/api/v4/(((groups|projects)/1)|(admin/ci))/variables"
)
variables_key_url = re.compile(
rf"http://localhost/api/v4/(((groups|projects)/1)|(admin/ci))/variables/{key}"
)
@pytest.fixture
def resp_list_variables():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=variables_url,
json=[variable_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_variable():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url=variables_key_url,
json=variable_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_variable():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url=variables_url,
json=variable_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_update_variable():
updated_content = dict(variable_content)
updated_content["value"] = new_value
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.PUT,
url=variables_key_url,
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_delete_variable():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url=variables_key_url,
status=204,
)
yield rsps
def test_list_instance_variables(gl, resp_list_variables):
variables = gl.variables.list()
assert isinstance(variables, list)
assert isinstance(variables[0], Variable)
assert variables[0].value == value
def test_get_instance_variable(gl, resp_get_variable):
variable = gl.variables.get(key)
assert isinstance(variable, Variable)
assert variable.value == value
def test_create_instance_variable(gl, resp_create_variable):
variable = gl.variables.create({"key": key, "value": value})
assert isinstance(variable, Variable)
assert variable.value == value
def test_update_instance_variable(gl, resp_update_variable):
variable = gl.variables.get(key, lazy=True)
variable.value = new_value
variable.save()
assert variable.value == new_value
def test_delete_instance_variable(gl, resp_delete_variable):
variable = gl.variables.get(key, lazy=True)
variable.delete()
def test_list_project_variables(project, resp_list_variables):
variables = project.variables.list()
assert isinstance(variables, list)
assert isinstance(variables[0], ProjectVariable)
assert variables[0].value == value
def test_get_project_variable(project, resp_get_variable):
variable = project.variables.get(key)
assert isinstance(variable, ProjectVariable)
assert variable.value == value
def test_create_project_variable(project, resp_create_variable):
variable = project.variables.create({"key": key, "value": value})
assert isinstance(variable, ProjectVariable)
assert variable.value == value
def test_update_project_variable(project, resp_update_variable):
variable = project.variables.get(key, lazy=True)
variable.value = new_value
variable.save()
assert variable.value == new_value
def test_delete_project_variable(project, resp_delete_variable):
variable = project.variables.get(key, lazy=True)
variable.delete()
def test_list_group_variables(group, resp_list_variables):
variables = group.variables.list()
assert isinstance(variables, list)
assert isinstance(variables[0], GroupVariable)
assert variables[0].value == value
def test_get_group_variable(group, resp_get_variable):
variable = group.variables.get(key)
assert isinstance(variable, GroupVariable)
assert variable.value == value
def test_create_group_variable(group, resp_create_variable):
variable = group.variables.create({"key": key, "value": value})
assert isinstance(variable, GroupVariable)
assert variable.value == value
def test_update_group_variable(group, resp_update_variable):
variable = group.variables.get(key, lazy=True)
variable.value = new_value
variable.save()
assert variable.value == new_value
def test_delete_group_variable(group, resp_delete_variable):
variable = group.variables.get(key, lazy=True)
variable.delete()
| 5,173 | Python | .py | 144 | 30.131944 | 82 | 0.69717 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,194 | test_todos.py | python-gitlab_python-gitlab/tests/unit/objects/test_todos.py | """
GitLab API: https://docs.gitlab.com/ce/api/todos.html
"""
import pytest
import responses
from gitlab.v4.objects import Todo
@pytest.fixture
def json_content():
return [
{
"id": 102,
"project": {
"id": 2,
"name": "Gitlab Ce",
"name_with_namespace": "Gitlab Org / Gitlab Ce",
"path": "gitlab-ce",
"path_with_namespace": "gitlab-org/gitlab-ce",
},
"author": {
"name": "Administrator",
"username": "root",
"id": 1,
},
"action_name": "marked",
"target_type": "MergeRequest",
"target": {
"id": 34,
"iid": 7,
"project_id": 2,
"assignee": {
"name": "Administrator",
"username": "root",
"id": 1,
},
},
}
]
@pytest.fixture
def resp_todo(json_content):
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/todos",
json=json_content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/todos/102/mark_as_done",
json=json_content[0],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_mark_all_as_done():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/todos/mark_as_done",
status=204,
)
yield rsps
def test_todo(gl, resp_todo):
todo = gl.todos.list()[0]
assert isinstance(todo, Todo)
assert todo.id == 102
assert todo.target_type == "MergeRequest"
assert todo.target["assignee"]["username"] == "root"
todo.mark_as_done()
def test_todo_mark_all_as_done(gl, resp_mark_all_as_done):
gl.todos.mark_all_as_done()
| 2,193 | Python | .py | 73 | 19.876712 | 77 | 0.504983 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,195 | test_bridges.py | python-gitlab_python-gitlab/tests/unit/objects/test_bridges.py | """
GitLab API: https://docs.gitlab.com/ee/api/jobs.html#list-pipeline-bridges
"""
import pytest
import responses
from gitlab.v4.objects import ProjectPipelineBridge
@pytest.fixture
def resp_list_bridges():
export_bridges_content = {
"commit": {
"author_email": "admin@example.com",
"author_name": "Administrator",
"created_at": "2015-12-24T16:51:14.000+01:00",
"id": "0ff3ae198f8601a285adcf5c0fff204ee6fba5fd",
"message": "Test the CI integration.",
"short_id": "0ff3ae19",
"title": "Test the CI integration.",
},
"allow_failure": False,
"created_at": "2015-12-24T15:51:21.802Z",
"started_at": "2015-12-24T17:54:27.722Z",
"finished_at": "2015-12-24T17:58:27.895Z",
"duration": 240,
"id": 7,
"name": "teaspoon",
"pipeline": {
"id": 6,
"ref": "main",
"sha": "0ff3ae198f8601a285adcf5c0fff204ee6fba5fd",
"status": "pending",
"created_at": "2015-12-24T15:50:16.123Z",
"updated_at": "2015-12-24T18:00:44.432Z",
"web_url": "https://example.com/foo/bar/pipelines/6",
},
"ref": "main",
"stage": "test",
"status": "pending",
"tag": False,
"web_url": "https://example.com/foo/bar/-/jobs/7",
"user": {
"id": 1,
"name": "Administrator",
"username": "root",
"state": "active",
"avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
"web_url": "http://gitlab.dev/root",
"created_at": "2015-12-21T13:14:24.077Z",
"public_email": "",
"skype": "",
"linkedin": "",
"twitter": "",
"website_url": "",
"organization": "",
},
"downstream_pipeline": {
"id": 5,
"sha": "f62a4b2fb89754372a346f24659212eb8da13601",
"ref": "main",
"status": "pending",
"created_at": "2015-12-24T17:54:27.722Z",
"updated_at": "2015-12-24T17:58:27.896Z",
"web_url": "https://example.com/diaspora/diaspora-client/pipelines/5",
},
}
export_pipelines_content = [
{
"id": 6,
"status": "pending",
"ref": "new-pipeline",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"web_url": "https://example.com/foo/bar/pipelines/47",
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z",
},
]
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipelines/6/bridges",
json=[export_bridges_content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/pipelines",
json=export_pipelines_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_projects_pipelines_bridges(project, resp_list_bridges):
pipeline = project.pipelines.list()[0]
bridges = pipeline.bridges.list()
assert isinstance(bridges, list)
assert isinstance(bridges[0], ProjectPipelineBridge)
assert bridges[0].downstream_pipeline["id"] == 5
assert (
bridges[0].downstream_pipeline["sha"]
== "f62a4b2fb89754372a346f24659212eb8da13601"
)
| 3,665 | Python | .py | 101 | 26.366337 | 109 | 0.546554 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,196 | test_users.py | python-gitlab_python-gitlab/tests/unit/objects/test_users.py | """
GitLab API:
https://docs.gitlab.com/ce/api/users.html
https://docs.gitlab.com/ee/api/projects.html#list-projects-starred-by-a-user
"""
import pytest
import responses
from gitlab.v4.objects import StarredProject, User, UserMembership, UserStatus
from .test_projects import project_content
@pytest.fixture
def resp_get_user():
content = {
"name": "name",
"id": 1,
"password": "password",
"username": "username",
"email": "email",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_user_memberships():
content = [
{
"source_id": 1,
"source_name": "Project one",
"source_type": "Project",
"access_level": "20",
},
{
"source_id": 3,
"source_name": "Group three",
"source_type": "Namespace",
"access_level": "20",
},
]
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1/memberships",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_activate():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/activate",
json={},
content_type="application/json",
status=201,
)
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/deactivate",
json={},
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_approve():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/approve",
json={"message": "Success"},
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_reject():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/reject",
json={"message": "Success"},
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_ban():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/ban",
json={},
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_unban():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/unban",
json={},
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_get_user_status():
content = {
"message": "test",
"message_html": "<h1>Message</h1>",
"emoji": "thumbsup",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1/status",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_delete_user_identity():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/users/1/identities/test_provider",
status=204,
)
yield rsps
@pytest.fixture
def resp_follow_unfollow():
user = {
"id": 1,
"username": "john_smith",
"name": "John Smith",
"state": "active",
"avatar_url": "http://localhost:3000/uploads/user/avatar/1/cd8.jpeg",
"web_url": "http://localhost:3000/john_smith",
}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/follow",
json=user,
content_type="application/json",
status=201,
)
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/users/1/unfollow",
json=user,
content_type="application/json",
status=201,
)
yield rsps
@pytest.fixture
def resp_followers_following():
content = [
{
"id": 2,
"name": "Lennie Donnelly",
"username": "evette.kilback",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/7955171a55ac4997ed81e5976287890a?s=80&d=identicon",
"web_url": "http://127.0.0.1:3000/evette.kilback",
},
{
"id": 4,
"name": "Serena Bradtke",
"username": "cammy",
"state": "active",
"avatar_url": "https://www.gravatar.com/avatar/a2daad869a7b60d3090b7b9bef4baf57?s=80&d=identicon",
"web_url": "http://127.0.0.1:3000/cammy",
},
]
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1/followers",
json=content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1/following",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_starred_projects():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/users/1/starred_projects",
json=[project_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_runner_create():
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/user/runners",
json={"id": "6", "token": "6337ff461c94fd3fa32ba3b1ff4125"},
content_type="application/json",
status=201,
)
yield rsps
def test_get_user(gl, resp_get_user):
user = gl.users.get(1)
assert isinstance(user, User)
assert user.name == "name"
assert user.id == 1
def test_user_memberships(user, resp_get_user_memberships):
memberships = user.memberships.list()
assert isinstance(memberships[0], UserMembership)
assert memberships[0].source_type == "Project"
def test_user_status(user, resp_get_user_status):
status = user.status.get()
assert isinstance(status, UserStatus)
assert status.message == "test"
assert status.emoji == "thumbsup"
def test_user_activate_deactivate(user, resp_activate):
user.activate()
user.deactivate()
def test_user_approve_(user, resp_approve):
user.approve()
def test_user_approve_reject(user, resp_reject):
user.reject()
def test_user_ban(user, resp_ban):
user.ban()
def test_user_unban(user, resp_unban):
user.unban()
def test_delete_user_identity(user, resp_delete_user_identity):
user.identityproviders.delete("test_provider")
def test_user_follow_unfollow(user, resp_follow_unfollow):
user.follow()
user.unfollow()
def test_list_followers(user, resp_followers_following):
followers = user.followers_users.list()
followings = user.following_users.list()
assert isinstance(followers[0], User)
assert followers[0].id == 2
assert isinstance(followings[0], User)
assert followings[1].id == 4
def test_list_starred_projects(user, resp_starred_projects):
projects = user.starred_projects.list()
assert isinstance(projects[0], StarredProject)
assert projects[0].id == project_content["id"]
def test_create_user_runner(current_user, resp_runner_create):
runner = current_user.runners.create({"runner_type": "instance_type"})
assert runner.id == "6"
assert runner.token == "6337ff461c94fd3fa32ba3b1ff4125"
| 8,577 | Python | .py | 268 | 23.578358 | 110 | 0.590716 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,197 | test_resource_milestone_events.py | python-gitlab_python-gitlab/tests/unit/objects/test_resource_milestone_events.py | """
GitLab API: https://docs.gitlab.com/ee/api/resource_milestone_events.html
"""
import pytest
import responses
from gitlab.v4.objects import (
ProjectIssueResourceMilestoneEvent,
ProjectMergeRequestResourceMilestoneEvent,
)
@pytest.fixture()
def resp_merge_request_milestone_events():
mr_content = {"iid": 1}
events_content = {"id": 1, "resource_type": "MergeRequest"}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests",
json=[mr_content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/merge_requests/1/resource_milestone_events",
json=[events_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture()
def resp_project_issue_milestone_events():
issue_content = {"iid": 1}
events_content = {"id": 1, "resource_type": "Issue"}
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/issues",
json=[issue_content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/issues/1/resource_milestone_events",
json=[events_content],
content_type="application/json",
status=200,
)
yield rsps
def test_project_issue_milestone_events(project, resp_project_issue_milestone_events):
issue = project.issues.list()[0]
milestone_events = issue.resourcemilestoneevents.list()
assert isinstance(milestone_events, list)
milestone_event = milestone_events[0]
assert isinstance(milestone_event, ProjectIssueResourceMilestoneEvent)
assert milestone_event.resource_type == "Issue"
def test_merge_request_milestone_events(project, resp_merge_request_milestone_events):
mr = project.mergerequests.list()[0]
milestone_events = mr.resourcemilestoneevents.list()
assert isinstance(milestone_events, list)
milestone_event = milestone_events[0]
assert isinstance(milestone_event, ProjectMergeRequestResourceMilestoneEvent)
assert milestone_event.resource_type == "MergeRequest"
| 2,458 | Python | .py | 63 | 31.507937 | 96 | 0.671698 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,198 | test_services.py | python-gitlab_python-gitlab/tests/unit/objects/test_services.py | """
GitLab API: https://docs.gitlab.com/ce/api/integrations.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectIntegration, ProjectService
@pytest.fixture
def resp_integration():
content = {
"id": 100152,
"title": "Pipelines emails",
"slug": "pipelines-email",
"created_at": "2019-01-14T08:46:43.637+01:00",
"updated_at": "2019-07-01T14:10:36.156+02:00",
"active": True,
"commit_events": True,
"push_events": True,
"issues_events": True,
"confidential_issues_events": True,
"merge_requests_events": True,
"tag_push_events": True,
"note_events": True,
"confidential_note_events": True,
"pipeline_events": True,
"wiki_page_events": True,
"job_events": True,
"comment_on_event_enabled": True,
"project_id": 1,
}
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/integrations",
json=[content],
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/integrations",
json=content,
content_type="application/json",
status=200,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/integrations/pipelines-email",
json=content,
content_type="application/json",
status=200,
)
updated_content = dict(content)
updated_content["issues_events"] = False
rsps.add(
method=responses.PUT,
url="http://localhost/api/v4/projects/1/integrations/pipelines-email",
json=updated_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_active_integrations(project, resp_integration):
integrations = project.integrations.list()
assert isinstance(integrations, list)
assert isinstance(integrations[0], ProjectIntegration)
assert integrations[0].active
assert integrations[0].push_events
def test_list_available_integrations(project, resp_integration):
integrations = project.integrations.available()
assert isinstance(integrations, list)
assert isinstance(integrations[0], str)
def test_get_integration(project, resp_integration):
integration = project.integrations.get("pipelines-email")
assert isinstance(integration, ProjectIntegration)
assert integration.push_events is True
def test_update_integration(project, resp_integration):
integration = project.integrations.get("pipelines-email")
integration.issues_events = False
integration.save()
assert integration.issues_events is False
def test_get_service_returns_service(project, resp_integration):
# todo: remove when services are removed
service = project.services.get("pipelines-email")
assert isinstance(service, ProjectService)
| 3,169 | Python | .py | 84 | 29.833333 | 82 | 0.657003 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
23,199 | test_project_access_tokens.py | python-gitlab_python-gitlab/tests/unit/objects/test_project_access_tokens.py | """
GitLab API: https://docs.gitlab.com/ee/api/project_access_tokens.html
"""
import pytest
import responses
from gitlab.v4.objects import ProjectAccessToken
@pytest.fixture
def resp_list_project_access_token(token_content):
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/access_tokens",
json=[token_content],
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_get_project_access_token(token_content):
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/access_tokens/1",
json=token_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_create_project_access_token(token_content):
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/access_tokens",
json=token_content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_revoke_project_access_token():
content = [
{
"user_id": 141,
"scopes": ["api"],
"name": "token",
"expires_at": "2021-01-31",
"id": 42,
"active": True,
"created_at": "2021-01-20T22:11:48.151Z",
"revoked": False,
}
]
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
rsps.add(
method=responses.DELETE,
url="http://localhost/api/v4/projects/1/access_tokens/42",
status=204,
)
rsps.add(
method=responses.GET,
url="http://localhost/api/v4/projects/1/access_tokens",
json=content,
content_type="application/json",
status=200,
)
yield rsps
@pytest.fixture
def resp_rotate_project_access_token(token_content):
with responses.RequestsMock() as rsps:
rsps.add(
method=responses.POST,
url="http://localhost/api/v4/projects/1/access_tokens/1/rotate",
json=token_content,
content_type="application/json",
status=200,
)
yield rsps
def test_list_project_access_tokens(gl, resp_list_project_access_token):
access_tokens = gl.projects.get(1, lazy=True).access_tokens.list()
assert len(access_tokens) == 1
assert access_tokens[0].revoked is False
assert access_tokens[0].name == "token"
def test_get_project_access_token(project, resp_get_project_access_token):
access_token = project.access_tokens.get(1)
assert isinstance(access_token, ProjectAccessToken)
assert access_token.revoked is False
assert access_token.name == "token"
def test_create_project_access_token(gl, resp_create_project_access_token):
access_tokens = gl.projects.get(1, lazy=True).access_tokens.create(
{"name": "test", "scopes": ["api"]}
)
assert access_tokens.revoked is False
assert access_tokens.user_id == 141
assert access_tokens.expires_at == "2021-01-31"
def test_revoke_project_access_token(
gl, resp_list_project_access_token, resp_revoke_project_access_token
):
gl.projects.get(1, lazy=True).access_tokens.delete(42)
access_token = gl.projects.get(1, lazy=True).access_tokens.list()[0]
access_token.delete()
def test_rotate_project_access_token(project, resp_rotate_project_access_token):
access_token = project.access_tokens.get(1, lazy=True)
access_token.rotate()
assert isinstance(access_token, ProjectAccessToken)
assert access_token.token == "s3cr3t"
| 3,982 | Python | .py | 106 | 29.707547 | 80 | 0.647288 | python-gitlab/python-gitlab | 2,230 | 648 | 106 | LGPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |