id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
140,748 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.ServicecardWidget
|
class ServicecardWidget(Widget):
"""ServiceCard Widget."""
|
class ServicecardWidget(Widget):
'''ServiceCard Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,749 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.SignatureWidget
|
class SignatureWidget(Widget):
"""Signature Widget."""
|
class SignatureWidget(Widget):
'''Signature Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,750 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.SupergridWidget
|
class SupergridWidget(Widget):
"""Supergrid Widget."""
|
class SupergridWidget(Widget):
'''Supergrid Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,751 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.TasknavigationbarWidget
|
class TasknavigationbarWidget(Widget):
"""Tasknavigationbar Widget."""
|
class TasknavigationbarWidget(Widget):
'''Tasknavigationbar Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,752 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.TasksWidget
|
class TasksWidget(Widget):
"""Tasks Widget."""
|
class TasksWidget(Widget):
'''Tasks Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,753 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.ProgressWidget
|
class ProgressWidget(Widget):
"""
Progress bar Widget.
This widget is deprecated as of June 2024.
"""
|
class ProgressWidget(Widget):
'''
Progress bar Widget.
This widget is deprecated as of June 2024.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 6 | 1 | 1 | 1 | 0 | 4 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,754 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.ThirdpartyWidget
|
class ThirdpartyWidget(Widget):
"""Thirdparty Widget."""
|
class ThirdpartyWidget(Widget):
'''Thirdparty Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,755 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.WeatherWidget
|
class WeatherWidget(Widget):
"""Weather Widget."""
|
class WeatherWidget(Widget):
'''Weather Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,756 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/workflow.py
|
pykechain.models.workflow.Status
|
class Status(Base, CrudActionsMixin):
"""Status object."""
url_detail_name = "status"
url_list_name = "statuses"
url_pk_name = "status_id"
def __init__(self, json, **kwargs) -> None:
"""Initialize a Status object."""
super().__init__(json, **kwargs)
self.description: str = json.get("description", "")
self.ref: str = json.get("ref", "")
self.status_category: StatusCategory = json.get("status_category")
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Status"]:
"""Retrieve a list of Status objects through the client."""
return super().list(client=client, **kwargs)
@classmethod
def get(cls, client: "Client", **kwargs) -> "Status":
"""Retrieve a Status object through the client."""
return super().get(client=client, **kwargs)
|
class Status(Base, CrudActionsMixin):
'''Status object.'''
def __init__(self, json, **kwargs) -> None:
'''Initialize a Status object.'''
pass
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Status"]:
'''Retrieve a list of Status objects through the client.'''
pass
@classmethod
def get(cls, client: "Client", **kwargs) -> "Status":
'''Retrieve a Status object through the client.'''
pass
| 6 | 4 | 4 | 0 | 3 | 1 | 1 | 0.27 | 2 | 3 | 1 | 0 | 1 | 3 | 3 | 6 | 23 | 4 | 15 | 12 | 9 | 4 | 13 | 10 | 9 | 1 | 1 | 0 | 3 |
140,757 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/workflow.py
|
pykechain.models.workflow.Transition
|
class Transition(Base, CrudActionsMixin):
"""Transition Object."""
url_detail_name = "transition"
url_list_name = "transitions"
url_pk_name = "transition_id"
def __init__(self, json, **kwargs) -> None:
"""Initialise a Transition object."""
super().__init__(json, **kwargs)
self.description: str = json.get("description", "")
self.ref: str = json.get("ref", "")
self.derived_from_id: Optional[ObjectID] = json.get("derived_from")
self.from_status: List[Status] = [
Status(j, client=self._client) for j in json.get("grom_status", [])
]
self.to_status: Status = json.get("to_status")
self.transition_type: TransitionType = json.get("transition_type")
self.conditions: dict = json.get("conditions", {})
self.validators: dict = json.get("validators", {})
self.post_functions: dict = json.get("post_functions", {})
self.transition_screen_id: Optional[ObjectID] = json.get("transition_screen")
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Transition"]:
"""Retrieve a list of Transition objects through the client."""
return super().list(client=client, **kwargs)
@classmethod
def get(cls, client: "Client", **kwargs) -> "Transition":
"""Retrieve a Transition object through the client."""
return super().get(client=client, **kwargs)
|
class Transition(Base, CrudActionsMixin):
'''Transition Object.'''
def __init__(self, json, **kwargs) -> None:
'''Initialise a Transition object.'''
pass
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Transition"]:
'''Retrieve a list of Transition objects through the client.'''
pass
@classmethod
def get(cls, client: "Client", **kwargs) -> "Transition":
'''Retrieve a Transition object through the client.'''
pass
| 6 | 4 | 8 | 1 | 6 | 1 | 1 | 0.17 | 2 | 5 | 2 | 0 | 1 | 10 | 3 | 6 | 34 | 6 | 24 | 19 | 18 | 4 | 20 | 17 | 16 | 1 | 1 | 0 | 3 |
140,758 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/workflow.py
|
pykechain.models.workflow.Workflow
|
class Workflow(
BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin
):
"""Workflow object."""
url_detail_name = "workflow"
url_list_name = "workflows"
url_pk_name: str = "workflow_id"
def __init__(self, json, **kwargs) -> None:
"""Initialize a Workflow Object."""
super().__init__(json, **kwargs)
self.description: str = json.get("description", "")
self.ref: str = json.get("ref", "")
self.derived_from_id: Optional[ObjectID] = json.get("derived_from_id")
self._transitions: List[Transition] = [
Transition(j, client=self._client) for j in json.get("transitions", [])
]
self.category: WorkflowCategory = json.get("category")
self.options: dict = json.get("options", {})
self.active: bool = json.get("active")
self._statuses: List[Status] = [
Status(j, client=self._client) for j in json.get("statuses")
]
def __repr__(self) -> str: # pragma: no cover
return f"<pyke Workflow '{self.name}' '{self.category}' id {self.id[-8:]}>"
def edit(
self, name: str = Empty(), description: str = Empty(), *args, **kwargs
) -> None:
"""Change the workflow object.
Change the name and description of a workflow. It is also possible to update the workflow
options and also the 'active' flag. To change the active flag of the workflow we
kindly refer to the `activate()` and `deactivate()` methods on the workflow.
:type name: name of the workflow is required.
:type description: (optional) description of the workflow
"""
if isinstance(name, Empty):
name = self.name
data = {
"name": check_text(name, "name"),
"description": check_text(description, "description"),
"active": check_type(kwargs.get("active", Empty()), bool, "active"),
"options": check_type(kwargs.get("options", Empty()), bool, "options"),
}
url = self._client._build_url("workflow", workflow_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"PUT",
url=url,
params=query_params,
json=clean_empty_values(data, nones=False),
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not edit the workflow", response=response)
self.refresh(json=response.json()["results"][0])
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Workflow"]:
"""Retrieve a list of Workflow objects through the client."""
return super().list(client=client, **kwargs)
@classmethod
def get(cls, client: "Client", **kwargs) -> "Workflow":
"""Retrieve a single Workflow object using the client."""
return super().get(client=client, **kwargs)
def delete(self):
"""Delete Workflow."""
return super().delete()
@classmethod
def create(
cls,
client: "Client",
name: str,
scope: Union["Scope", ObjectID],
category: WorkflowCategory = WorkflowCategory.DEFINED,
description: str = None,
options: dict = None,
active: bool = False,
**kwargs,
) -> "Workflow":
"""
Create a new Workflow object using the client.
:param client: Client object.
:param name: Name of the workflow
:param scope: Scope of the workflow
:param category: (optional) category of the workflow, defaults to WorkflowCategory.DEFINED
:param description: (optional) description of the workflow
:param options: (optional) JSON/dictionary with workflow options
:param active: (optional) boolean flag to set the workflow to active. Defaults to False
:param kwargs: (optional) additional kwargs.
:return: a Workflow object
:raises APIError: When the Workflow could not be created.
"""
from pykechain.models import Scope # avoiding circular imports here.
data = {
"name": check_text(name, "name"),
"scope": check_base(scope, Scope, "scope"),
"category": check_enum(category, WorkflowCategory, "category"),
"description": check_text(description, "description"),
"options": check_type(options, dict, "options"),
"active": check_type(active, bool, "active"),
}
kwargs.update(API_EXTRA_PARAMS[cls.url_list_name])
response = client._request(
"POST", client._build_url(cls.url_list_name), params=kwargs, json=data
)
if response.status_code != requests.codes.created: # pragma: no cover
raise APIError(f"Could not create {cls.__name__}", response=response)
return cls(json=response.json()["results"][0], client=client)
@property
def status_order(self) -> List[Status]:
"""Statuses in the right order."""
return self.statuses
@status_order.setter
def status_order(self, value: List[Union[ObjectID, Status]]):
"""
Set the order of the statuses specifically in a certain order.
:param value: a determined ordered list of Status or status UUID's
"""
if not value:
raise IllegalArgumentError(
f"To set the order of statises, provide a list of status objects, got: '{value}'"
)
data = {"status_order": check_list_of_base(value, Status, "statuses")}
url = self._client._build_url("workflow_set_status_order", workflow_id=self.id)
response = self._client._request("PUT", url=url, json=data)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(
"Could not alter the order of the statuses", response=response
)
self.refresh(json=response.json()["results"][0])
#
# Subclass finders and managers.
#
def transition(
self,
value: str = None,
attr: str = None,
) -> Transition:
"""
Retrieve the Transition belonging to this workflow based on its name, ref or uuid.
:param value: transition name, ref or UUID to search for
:param attr: the attribute to match on. E.g. to_status=<Status Obj>
:return: a single :class:`Transition`
:raises NotFoundError: if the `Transition` is not part of the `Workflow`
:raises MultipleFoundError
Example
-------
>>> workflow = project.workflow('Simple Flow')
>>> transition = workflow.transition('in progress')
>>> todo_status = client.status(name="To Do")
>>> transition = workflow.transition(todo_status, attr="to_status")
"""
return find_obj_in_list(value, iterable=self._transitions, attribute=attr)
@property
def transitions(self):
"""
Retrieve the Transitions belonging to this workflow.
:return: multiple :class:`Transition`
"""
return self._transitions
def status(self, value: str = None, attr: str = None) -> Status:
"""
Retrieve the Status belonging to this workflow based on its name, ref or uuid.
:param value: status name, ref or UUID to search for
:param attr: the attribute to match on.
:return: a single :class:`Status`
:raises NotFoundError: if the `Status` is not part of the `Workflow`
:raises MultipleFoundError
Example
-------
>>> workflow = project.workflow('Simple Flow')
>>> status = workflow.status('To Do')
"""
return find_obj_in_list(value, iterable=self._statuses, attribute=attr)
@property
def statuses(self):
"""
Retrieve the Statuses belonging to this workflow.
:return: multiple :class:`Status`
"""
return self._statuses
#
# Mutable methods on the object
#
def activate(self):
"""Set the active status to True."""
if not self.active:
url = self._client._build_url("workflow_activate", workflow_id=self.id)
response = self._client._request("PUT", url=url)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not activate the workflow", response=response)
# we need to do a full refresh here from the server as the
# API of workflow/<id>/activate does not return the full object as response.
self.refresh(
url=self._client._build_url("workflow", workflow_id=self.id),
extra_params=API_EXTRA_PARAMS.get(self.url_list_name),
)
def deactivate(self):
"""Set the active status to False."""
if self.active:
url = self._client._build_url("workflow_deactivate", workflow_id=self.id)
response = self._client._request("PUT", url=url)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not activate the workflow", response=response)
# we need to do a full refresh here from the server as the
# API of workflow/<id>/deactivate does not return the full object as response.
self.refresh(
url=self._client._build_url("workflow", workflow_id=self.id),
extra_params=API_EXTRA_PARAMS.get(self.url_list_name),
)
def clone(
self,
target_scope: "Scope" = Empty(),
name: Optional[str] = Empty(),
description: Optional[str] = Empty(),
) -> "Workflow":
"""Clone the current workflow into a new workflow.
Also used to 'import' a catalog workflow into a scope.
:param target_scope: (optional) target scope where to clone the Workflow to.
Defaults current scope.
:param name: (optional) name of the new workflow
:param description: (optional) description of the new workflow
"""
from pykechain.models import Scope
if isinstance(target_scope, Empty):
target_scope = self.scope_id
data = {
"target_scope": check_base(target_scope, Scope, "scope"),
"name": check_text(name, "name"),
"description": check_text(description, "description"),
}
url = self._client._build_url("workflow_clone", workflow_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST",
url=url,
params=query_params,
json=clean_empty_values(data, nones=False),
)
if response.status_code != requests.codes.created: # pragma: no cover
raise APIError("Could not clone the workflow", response=response)
return Workflow(json=response.json()["results"][0], client=self._client)
def update_transition(
self,
transition: Union[Transition, ObjectID],
name: Optional[str] = Empty(),
description: Optional[str] = Empty(),
from_status: Optional[List[str]] = Empty(),
) -> Transition:
"""Update a specific Transition in the current workflow.
Update the transition inside the worfklow based on a transition_id.
:param transition: Transition object or transition id to alter
:param name: (optional) name to change
:param description: (optional) description to change
:param from_status: (optional) a list of from statuses to update
"""
data = {
"transition_id": check_base(transition, Transition, "transition_id"),
"name": check_text(name, "name"),
"decription": check_text(description, "description"),
"from_status": check_list_of_base(from_status, Status, "from_statuses"),
}
url = self._client._build_url("workflow_update_transition", workflow_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=data
)
if response.status_code != requests.codes.ok:
raise APIError(
f"Could not update the specific transition '{transition}' in the "
"workflow",
response=response,
)
# an updated transition will be altered, so we want to refresh the workflow.
self.refresh()
return Transition(json=response.json()["results"][0])
def delete_transition(self, transition: Union[Transition, ObjectID]) -> None:
"""Remove Transition from the current Workflow and delete it.
If the Transition is still connected to *other* Workflows, it will *not* be
removed, and will result in a 400 reporting all attached Workflows.
:param transition: object or uuid of a transition to delete.
"""
transition_id = check_base(transition, Transition, "transition_id")
url = self._client._build_url(
"workflow_delete_transition",
workflow_id=self.id,
transition_id=transition_id,
)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request("DELETE", url=url, params=query_params)
if response.status_code != requests.codes.no_content:
raise APIError(
f"Could not delete the specific transition '{transition}' from the "
"workflow",
response=response,
)
# a deleted transition will be unlinked, so we want to refresh the workflow.
self.refresh()
def create_transition(
self,
name: str,
to_status: Union[Status, ObjectID],
transition_type: TransitionType = TransitionType.GLOBAL,
from_status: Optional[List[Union[Status, ObjectID]]] = Empty(),
description: Optional[str] = Empty(),
):
"""
Create a new Transition and associate it to the current Workflow.
:param name: name of the transition.
:param to_status: status where to transition to (a single status or status id)
:param transition_type: transition type to transition to. (defaults to Global)
:param from_status: (optional) status to transition from. Not used for Global transitions.
:param description: (optional) description.
"""
data = {
"name": check_text(name, "name"),
"to_status": check_base(to_status, Status, "to_status"),
"transition_type": check_enum(
transition_type, TransitionType, "transition_type"
),
"from_status": check_list_of_base(from_status, Status, "from_statuses"),
"description": check_text(description, "description"),
}
url = self._client._build_url("workflow_create_transition", workflow_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=clean_empty_values(data)
)
if response.status_code != requests.codes.created:
raise APIError(
"Could not create the specific transition in the " "workflow",
response=response,
)
# a new transition will be linked to the workflow, so we want to refresh the workflow.
self.refresh()
return Transition(json=response.json()["results"][0], client=self._client)
def create_status(
self,
name: str,
category: StatusCategory = StatusCategory.UNDEFINED,
description: Optional[str] = Empty(),
) -> Status:
"""Create a new Status.
Will create a new status, a new global transition to that status and
will link the new Global transition to that status to the current
workflow.
:param name: name of the status
:param category: status category (defaults to UNDEFINED)
:param description: (optional) description of the status
"""
data = {
"name": check_text(name, "name"),
"status_category": check_enum(category, StatusCategory, "status_category"),
"description": check_text(description, "description"),
}
url = self._client._build_url("workflow_create_status", workflow_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=clean_empty_values(data)
)
if response.status_code != requests.codes.created:
raise APIError(
"Could not create the specific status, a global transition and"
"link it to the workflow",
response=response,
)
# a new status will create a new global transition to that status,
# so we want to update the current workflow.
self.refresh()
return Status(json=response.json()["results"][0], client=self._client)
def link_transitions(self, transitions: List[Union[Transition, ObjectID]]):
"""
Link a list of Transitions to a Workflow.
:param transitions: a list of Transition Objects or transition_ids to link to the workflow.
"""
data = {"transitions": check_list_of_base(transitions, Transition)}
url = self._client._build_url("workflow_link_transitions", workflow_id=self.id)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=data
)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not create the specific status, a global transition and"
"link it to the workflow",
response=response,
)
self.refresh(json=response.json()["results"][0])
def unlink_transitions(
self, transitions: List[Union[Transition, ObjectID]]
) -> None:
"""
Unlink a list of Transitions to a Workflow.
:param transitions: a list of Transition Objects or transition_ids to link to the workflow.
"""
data = {"transitions": check_list_of_base(transitions, Transition)}
url = self._client._build_url(
"workflow_unlink_transitions", workflow_id=self.id
)
query_params = API_EXTRA_PARAMS.get(self.url_list_name)
response = self._client._request(
"POST", url=url, params=query_params, json=data
)
if response.status_code != requests.codes.ok:
raise APIError(
"Could not create the specific status, a global transition and"
"link it to the workflow",
response=response,
)
self.refresh(json=response.json()["results"][0])
|
class Workflow(
BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin
):
'''Workflow object.'''
def __init__(self, json, **kwargs) -> None:
'''Initialize a Workflow Object.'''
pass
def __repr__(self) -> str:
pass
def edit(
self, name: str = Empty(), description:
'''Change the workflow object.
Change the name and description of a workflow. It is also possible to update the workflow
options and also the 'active' flag. To change the active flag of the workflow we
kindly refer to the `activate()` and `deactivate()` methods on the workflow.
:type name: name of the workflow is required.
:type description: (optional) description of the workflow
'''
pass
@classmethod
def list(cls, client: "Client", **kwargs) -> List["Workflow"]:
'''Retrieve a list of Workflow objects through the client.'''
pass
@classmethod
def get(cls, client: "Client", **kwargs) -> "Workflow":
'''Retrieve a single Workflow object using the client.'''
pass
def delete(self):
'''Delete Workflow.'''
pass
@classmethod
def create(
cls,
client: "Client",
name: str,
scope: Union["Scope", ObjectID],
category: WorkflowCategory = WorkflowCategory.DEFINED,
description: str = None,
options: dict = None,
active: bool = False,
**kwargs,
) -> "Workflow":
'''
Create a new Workflow object using the client.
:param client: Client object.
:param name: Name of the workflow
:param scope: Scope of the workflow
:param category: (optional) category of the workflow, defaults to WorkflowCategory.DEFINED
:param description: (optional) description of the workflow
:param options: (optional) JSON/dictionary with workflow options
:param active: (optional) boolean flag to set the workflow to active. Defaults to False
:param kwargs: (optional) additional kwargs.
:return: a Workflow object
:raises APIError: When the Workflow could not be created.
'''
pass
@property
def status_order(self) -> List[Status]:
'''Statuses in the right order.'''
pass
@status_order.setter
def status_order(self) -> List[Status]:
'''
Set the order of the statuses specifically in a certain order.
:param value: a determined ordered list of Status or status UUID's
'''
pass
def transition(
self,
value: str = None,
attr: str = None,
) -> Transition:
'''
Retrieve the Transition belonging to this workflow based on its name, ref or uuid.
:param value: transition name, ref or UUID to search for
:param attr: the attribute to match on. E.g. to_status=<Status Obj>
:return: a single :class:`Transition`
:raises NotFoundError: if the `Transition` is not part of the `Workflow`
:raises MultipleFoundError
Example
-------
>>> workflow = project.workflow('Simple Flow')
>>> transition = workflow.transition('in progress')
>>> todo_status = client.status(name="To Do")
>>> transition = workflow.transition(todo_status, attr="to_status")
'''
pass
@property
def transitions(self):
'''
Retrieve the Transitions belonging to this workflow.
:return: multiple :class:`Transition`
'''
pass
def status_order(self) -> List[Status]:
'''
Retrieve the Status belonging to this workflow based on its name, ref or uuid.
:param value: status name, ref or UUID to search for
:param attr: the attribute to match on.
:return: a single :class:`Status`
:raises NotFoundError: if the `Status` is not part of the `Workflow`
:raises MultipleFoundError
Example
-------
>>> workflow = project.workflow('Simple Flow')
>>> status = workflow.status('To Do')
'''
pass
@property
def statuses(self):
'''
Retrieve the Statuses belonging to this workflow.
:return: multiple :class:`Status`
'''
pass
def activate(self):
'''Set the active status to True.'''
pass
def deactivate(self):
'''Set the active status to False.'''
pass
def clone(
self,
target_scope: "Scope" = Empty(),
name:
'''Clone the current workflow into a new workflow.
Also used to 'import' a catalog workflow into a scope.
:param target_scope: (optional) target scope where to clone the Workflow to.
Defaults current scope.
:param name: (optional) name of the new workflow
:param description: (optional) description of the new workflow
'''
pass
def update_transition(
self,
transition: Union[Transition, ObjectID],
name: Optional[str] = Empty(),
description:
'''Update a specific Transition in the current workflow.
Update the transition inside the worfklow based on a transition_id.
:param transition: Transition object or transition id to alter
:param name: (optional) name to change
:param description: (optional) description to change
:param from_status: (optional) a list of from statuses to update
'''
pass
def delete_transition(self, transition: Union[Transition, ObjectID]) -> None:
'''Remove Transition from the current Workflow and delete it.
If the Transition is still connected to *other* Workflows, it will *not* be
removed, and will result in a 400 reporting all attached Workflows.
:param transition: object or uuid of a transition to delete.
'''
pass
def create_transition(
self,
name: str,
to_status: Union[Status, ObjectID],
transition_type: TransitionType = TransitionType.GLOBAL,
from_status: Optional[List[Union[Status, ObjectID]]] = Empty(),
description:
'''
Create a new Transition and associate it to the current Workflow.
:param name: name of the transition.
:param to_status: status where to transition to (a single status or status id)
:param transition_type: transition type to transition to. (defaults to Global)
:param from_status: (optional) status to transition from. Not used for Global transitions.
:param description: (optional) description.
'''
pass
def create_status(
self,
name: str,
category: StatusCategory = StatusCategory.UNDEFINED,
description: Optional[str] = Empty(),
) -> Status:
'''Create a new Status.
Will create a new status, a new global transition to that status and
will link the new Global transition to that status to the current
workflow.
:param name: name of the status
:param category: status category (defaults to UNDEFINED)
:param description: (optional) description of the status
'''
pass
def link_transitions(self, transitions: List[Union[Transition, ObjectID]]):
'''
Link a list of Transitions to a Workflow.
:param transitions: a list of Transition Objects or transition_ids to link to the workflow.
'''
pass
def unlink_transitions(
self, transitions: List[Union[Transition, ObjectID]]
) -> None:
'''
Unlink a list of Transitions to a Workflow.
:param transitions: a list of Transition Objects or transition_ids to link to the workflow.
'''
pass
| 30 | 22 | 19 | 1 | 12 | 6 | 2 | 0.47 | 4 | 12 | 8 | 0 | 19 | 9 | 22 | 38 | 463 | 56 | 283 | 128 | 208 | 132 | 135 | 77 | 110 | 3 | 2 | 2 | 39 |
140,759 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/utils.py
|
pykechain.utils.Empty
|
class Empty:
"""
Represents an empty value.
In edit functions we want to be able to edit values of model properties, e.g. the due_date of a process.
Consider the following example:
def edit(self, start_date, due_date)
self.start_date = start_date
self.due_date = due_date
self.save()
This is ok, we can edit both the start and due date. But what if we want to be able to edit one of the two dates
without providing or touching the other.
We would have to change it as follows:
def edit(self, start_date=None, due_date=None)
if start_date:
self.start_date = start_date
if due_date:
self.due_date = due_date
self.save()
Now, if we provide a start_date but not a due_date, the due_date would automatically get a None value. This way
only the non-None values are edited and saved. Looks OK.
But what if we want to empty a date and set it to null(None) in the database? If we send None as a due_date value
it would not get saved due to the None value checker we implemented in order to have optional parameters.
Here comes the Empty class into play!
The Empty class is just a Python class which does absolutely nothing and only serves the purpose of being unique.
If we give the parameters in our edit function a default value which is an instance of the Empty class, we can check
on that in order to know if we want to save the value. Like this:
def edit(self, start_date=Empty(), due_date=Empty())
if not isinstance(start_date, Empty):
self.start_date = start_date
if not isinstance(due_date, Empty):
self.due_date = due_date
self.save()
Now both start_date and due_date are optional, but they can also hold a None value which will lead to an actual
edit.
Happy coding!
"""
__instance = None
def __new__(cls, *args, **kwargs):
"""Only create a single instance of this class, i.e. simple singleton pattern."""
if cls.__instance is None:
cls.__instance = super().__new__(cls)
return cls.__instance
|
class Empty:
'''
Represents an empty value.
In edit functions we want to be able to edit values of model properties, e.g. the due_date of a process.
Consider the following example:
def edit(self, start_date, due_date)
self.start_date = start_date
self.due_date = due_date
self.save()
This is ok, we can edit both the start and due date. But what if we want to be able to edit one of the two dates
without providing or touching the other.
We would have to change it as follows:
def edit(self, start_date=None, due_date=None)
if start_date:
self.start_date = start_date
if due_date:
self.due_date = due_date
self.save()
Now, if we provide a start_date but not a due_date, the due_date would automatically get a None value. This way
only the non-None values are edited and saved. Looks OK.
But what if we want to empty a date and set it to null(None) in the database? If we send None as a due_date value
it would not get saved due to the None value checker we implemented in order to have optional parameters.
Here comes the Empty class into play!
The Empty class is just a Python class which does absolutely nothing and only serves the purpose of being unique.
If we give the parameters in our edit function a default value which is an instance of the Empty class, we can check
on that in order to know if we want to save the value. Like this:
def edit(self, start_date=Empty(), due_date=Empty())
if not isinstance(start_date, Empty):
self.start_date = start_date
if not isinstance(due_date, Empty):
self.due_date = due_date
self.save()
Now both start_date and due_date are optional, but they can also hold a None value which will lead to an actual
edit.
Happy coding!
'''
def __new__(cls, *args, **kwargs):
'''Only create a single instance of this class, i.e. simple singleton pattern.'''
pass
| 2 | 2 | 5 | 0 | 4 | 1 | 2 | 6 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 56 | 14 | 6 | 3 | 4 | 36 | 6 | 3 | 4 | 2 | 0 | 1 | 2 |
140,760 |
KE-works/pykechain
|
KE-works_pykechain/tests/classes.py
|
tests.classes.EnvironmentVarGuard
|
class EnvironmentVarGuard(collections.abc.MutableMapping):
"""Class to help protect the environment variable properly.
Can be used as a context manager."""
def __init__(self):
self._environ = os.environ
self._changed = {}
def __getitem__(self, envvar):
return self._environ[envvar]
def __setitem__(self, envvar, value):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
self._environ[envvar] = value
def __delitem__(self, envvar):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
if envvar in self._environ:
del self._environ[envvar]
def keys(self):
return self._environ.keys()
def __iter__(self):
return iter(self._environ)
def __len__(self):
return len(self._environ)
def set(self, envvar, value):
self[envvar] = value
def unset(self, envvar):
del self[envvar]
def copy(self):
# We do what os.environ.copy() does.
return dict(self)
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
for (k, v) in self._changed.items():
if v is None:
if k in self._environ:
del self._environ[k]
else:
self._environ[k] = v
os.environ = self._environ
|
class EnvironmentVarGuard(collections.abc.MutableMapping):
'''Class to help protect the environment variable properly.
Can be used as a context manager.'''
def __init__(self):
pass
def __getitem__(self, envvar):
pass
def __setitem__(self, envvar, value):
pass
def __delitem__(self, envvar):
pass
def keys(self):
pass
def __iter__(self):
pass
def __len__(self):
pass
def set(self, envvar, value):
pass
def unset(self, envvar):
pass
def copy(self):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 13 | 1 | 3 | 0 | 3 | 0 | 2 | 0.14 | 1 | 1 | 0 | 0 | 12 | 2 | 12 | 12 | 55 | 13 | 37 | 16 | 24 | 5 | 36 | 16 | 23 | 4 | 1 | 3 | 18 |
140,761 |
KE-works/pykechain
|
KE-works_pykechain/tests/classes.py
|
tests.classes.TestBetamax
|
class TestBetamax(TestCase):
time = datetime.datetime(year=2020, month=1, day=1, tzinfo=pytz.UTC)
@property
def cassette_name(self):
test = self._testMethodName
return f"{self.__class__.__name__}.{test}"
def setUp(self):
# use self.env.set('var', 'value') and with self.env: ... to use custom environmental variables
self.env = EnvironmentVarGuard()
self.client = Client(url=TEST_URL)
if TEST_TOKEN:
self.client.login(token=TEST_TOKEN)
self.recorder = Betamax(session=self.client.session)
if TEST_RECORD_CASSETTES:
self.recorder.use_cassette(self.cassette_name)
self.recorder.start()
else:
self.recorder.config.record_mode = None
if TEST_SCOPE_NAME:
self.project = self.client.scope(name=TEST_SCOPE_NAME)
elif TEST_SCOPE_ID:
self.project = self.client.scope(id=TEST_SCOPE_ID)
else:
raise Exception(
"Could not retrieve the test scope, you need to provide a "
"`TEST_SCOPE_ID` or `TEST_SCOPE_NAME` in your `.env` file"
)
def tearDown(self):
self.recorder.stop()
del self.env
del self.client
|
class TestBetamax(TestCase):
@property
def cassette_name(self):
pass
def setUp(self):
pass
def tearDown(self):
pass
| 5 | 0 | 11 | 1 | 9 | 0 | 2 | 0.03 | 1 | 2 | 1 | 80 | 3 | 4 | 3 | 75 | 38 | 7 | 30 | 11 | 25 | 1 | 23 | 10 | 19 | 5 | 2 | 1 | 7 |
140,762 |
KE-works/pykechain
|
KE-works_pykechain/tests/models/test_base.py
|
tests.models.test_base.TestBase
|
class TestBase(TestCase):
json = {"id": "123", "name": "test"}
def test_id(self):
obj = Base(self.json, None)
self.assertEqual(obj.id, "123")
def test_name(self):
obj = Base(self.json, None)
self.assertEqual(obj.name, "test")
def test_given_client(self):
client = Client()
obj = Base(self.json, client)
self.assertEqual(obj._client, client)
self.assertIsInstance(obj._client, Client)
|
class TestBase(TestCase):
def test_id(self):
pass
def test_name(self):
pass
def test_given_client(self):
pass
| 4 | 0 | 5 | 1 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 75 | 21 | 8 | 13 | 9 | 9 | 0 | 13 | 9 | 9 | 1 | 2 | 0 | 3 |
140,763 |
KE-works/pykechain
|
KE-works_pykechain/tests/models/test_property_datetime.py
|
tests.models.test_property_datetime.TestPropertyDateTime
|
class TestPropertyDateTime(TestBetamax):
example_time = datetime.datetime.now()
NAME = "_TESTING DATE"
def setUp(self) -> None:
super().setUp()
self.bike_model = self.project.model("Bike")
self.property_model = self.bike_model.add_property(
name=self.NAME, property_type=PropertyType.DATETIME_VALUE
) # type: DatetimeProperty
self.property = self.project.part("Bike").property(
name=self.NAME
) # type: DatetimeProperty
self.property.value = self.example_time
def tearDown(self):
self.property_model.delete()
super().tearDown()
def test_get_datetime(self):
value = self.property.value
self.assertIsInstance(value, str)
def test_set_value_none(self):
self.property.value = None
def test_set_value_iso_string(self):
self.property.value = self.example_time.isoformat()
def test_set_value_non_datetime(self):
with self.assertRaises(IllegalArgumentError):
self.property.value = "3"
def test_set_value(self):
self.property.value = self.example_time
def test_pending_value(self):
self.property.value = None
Property.set_bulk_update(True)
self.property.value = self.example_time
live_property = self.project.property(id=self.property.id)
self.assertFalse(live_property.has_value())
Property.update_values(client=self.client)
live_property.refresh()
self.assertTrue(live_property.has_value())
def test_value_via_part(self):
self.bike_model.update(
update_dict={
self.NAME: self.example_time,
}
)
def test_to_datetime(self):
date_time_value = self.property.to_datetime()
self.assertIsInstance(date_time_value, datetime.datetime)
def test_iso_formatted(self):
date_time_value = self.property.to_datetime()
iso_format_datetime = DatetimeProperty.to_iso_format(date_time_value)
self.assertIsInstance(iso_format_datetime, str)
|
class TestPropertyDateTime(TestBetamax):
def setUp(self) -> None:
pass
def tearDown(self):
pass
def test_get_datetime(self):
pass
def test_set_value_none(self):
pass
def test_set_value_iso_string(self):
pass
def test_set_value_non_datetime(self):
pass
def test_set_value_none(self):
pass
def test_pending_value(self):
pass
def test_value_via_part(self):
pass
def test_to_datetime(self):
pass
def test_iso_formatted(self):
pass
| 12 | 0 | 5 | 1 | 4 | 0 | 1 | 0.04 | 1 | 7 | 4 | 0 | 11 | 3 | 11 | 86 | 72 | 22 | 50 | 22 | 38 | 2 | 42 | 22 | 30 | 1 | 3 | 1 | 11 |
140,764 |
KE-works/pykechain
|
KE-works_pykechain/tests/models/test_property_reference.py
|
tests.models.test_property_reference.TestPropertyActivityReference
|
class TestPropertyActivityReference(TestBetamax):
def setUp(self):
super().setUp()
root = self.project.model(name="Product")
self.part = self.project.create_model(
name="The part", parent=root, multiplicity=Multiplicity.ONE
)
self.prop = self.part.add_property(
name="activity ref", property_type=PropertyType.ACTIVITY_REFERENCES_VALUE
)
def tearDown(self):
if self.part:
self.part.delete()
super().tearDown()
def test_create(self):
self.assertIsInstance(self.prop, ActivityReferencesProperty)
def test_value(self):
wbs_root = self.project.activity(name=ActivityRootNames.WORKFLOW_ROOT)
task = wbs_root.children()[0]
self.prop.value = [task]
self.prop.refresh()
self.assertIsInstance(self.prop, ActivityReferencesProperty)
self.assertIsNotNone(self.prop.value)
self.assertEqual(task, self.prop.value[0])
def test_value_ids(self):
wbs_root = self.project.activity(name=ActivityRootNames.WORKFLOW_ROOT)
task = wbs_root.children()[0]
self.prop.value = [task]
self.prop.refresh()
ids = self.prop.value_ids()
self.assertIsInstance(ids, list)
self.assertTrue(all(isinstance(v, str) for v in ids))
def test_reload(self):
reloaded_prop = self.client.reload(obj=self.prop)
self.assertFalse(
self.prop is reloaded_prop,
msg="Must be different Python objects, based on memory allocation",
)
self.assertEqual(
self.prop,
reloaded_prop,
msg="Must be the same KE-chain prop, based on hashed UUID",
)
|
class TestPropertyActivityReference(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test_create(self):
pass
def test_value(self):
pass
def test_value_ids(self):
pass
def test_reload(self):
pass
| 7 | 0 | 8 | 1 | 7 | 0 | 1 | 0 | 1 | 7 | 4 | 0 | 6 | 2 | 6 | 81 | 54 | 11 | 43 | 16 | 36 | 0 | 32 | 16 | 25 | 2 | 3 | 1 | 7 |
140,765 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.UndefinedWidget
|
class UndefinedWidget(Widget):
"""Undefined Widget."""
schema = undefined_meta_schema
|
class UndefinedWidget(Widget):
'''Undefined Widget.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 4 | 1 | 2 | 2 | 1 | 1 | 2 | 2 | 1 | 0 | 3 | 0 | 0 |
140,766 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_about.py
|
tests.test_about.TestAbout
|
class TestAbout(TestCase):
def test_import(self):
from pykechain import __about__ as about
self.assertTrue(about)
def test_names(self):
from pykechain import __about__ as about
self.assertTrue(about.name)
self.assertTrue(about.version)
import semver
self.assertTrue(semver.VersionInfo.parse(about.version))
def test_python_fstring(self):
true = f"this is {True}"
self.assertEqual(f"{true}", true)
|
class TestAbout(TestCase):
def test_import(self):
pass
def test_names(self):
pass
def test_python_fstring(self):
pass
| 4 | 0 | 5 | 1 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 75 | 18 | 5 | 13 | 8 | 6 | 0 | 13 | 8 | 6 | 1 | 2 | 0 | 3 |
140,767 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.NotebookWidget
|
class NotebookWidget(Widget):
"""Notebook Widget."""
|
class NotebookWidget(Widget):
'''Notebook Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,768 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.MultiAttachmentviewerWidget
|
class MultiAttachmentviewerWidget(Widget):
"""Multi Attachmentviewer Widget."""
|
class MultiAttachmentviewerWidget(Widget):
'''Multi Attachmentviewer Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,769 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_activities.py
|
tests.test_activities.TestActivityClone
|
class TestActivityClone(TestBetamax):
def setUp(self):
super().setUp()
self.process = self.project.create_activity(
name="__TEST CLONE SUBPROCESS", activity_type=ActivityType.PROCESS
)
self.task = self.process.create("__TEST CLONE TASK")
self.clone = None
self.bucket = [self.process]
def tearDown(self):
for activity in self.bucket:
if activity:
try:
activity.delete()
except APIError:
pass
super().tearDown()
def test(self):
clone = self.task.clone()
self.assertIsInstance(clone, Activity)
self.assertNotEqual(self.task, clone)
self.assertEqual(self.task.parent_id, clone.parent_id)
def test_parent_id(self):
second_process = self.project.create_activity(
name="__Test process 2",
activity_type=ActivityType.PROCESS,
)
self.bucket.append(second_process)
clone = self.task.clone(
parent=second_process,
)
self.assertNotEqual(self.task.parent_id, clone.parent_id)
def test_update(self):
new_name = "__TEST TASK RENAMED"
clone = self.task.clone(
update_dict=dict(name=new_name),
)
self.assertEqual(new_name, clone.name)
def test_update_incorrect(self):
with self.assertRaises(IllegalArgumentError):
self.task.clone(part_parent_instance=True)
def test_async_via_task(self):
response = self.task.clone(asynchronous=True)
self.assertIsNone(response)
def test_async_via_client(self):
response = self.client.clone_activities(
activities=[self.task], activity_parent=self.process, asynchronous=True
)
self.assertIsInstance(response, list)
self.assertFalse(response)
|
class TestActivityClone(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test(self):
pass
def test_parent_id(self):
pass
def test_update(self):
pass
def test_update_incorrect(self):
pass
def test_async_via_task(self):
pass
def test_async_via_client(self):
pass
| 9 | 0 | 7 | 1 | 6 | 0 | 1 | 0 | 1 | 6 | 3 | 0 | 8 | 4 | 8 | 83 | 63 | 13 | 50 | 21 | 41 | 0 | 39 | 21 | 30 | 4 | 3 | 3 | 11 |
140,770 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_activities.py
|
tests.test_activities.TestActivityCloneParts
|
class TestActivityCloneParts(TestBetamax):
def setUp(self):
super().setUp()
# Create task to clone
self.process = self.project.create_activity(
name="__TEST CLONE SUBPROCESS", activity_type=ActivityType.PROCESS
)
self.task = self.process.create(name="__TEST CLONE TASK")
# Create part model to copy along
intermediate = self.project.catalog_root_model.add_model(
name="__TEST CLONE INTERMEDIATE MODEL", multiplicity=Multiplicity.ONE
)
source_parent_model = intermediate.add_model(
name="__TEST CLONE CONFIGURED MODEL - PARENT",
multiplicity=Multiplicity.ONE_MANY,
)
child_model = source_parent_model.add_model(
name="__TEST CLONE CONFIGURED MODEL - CHILD",
multiplicity=Multiplicity.ONE_MANY,
)
for prop_type in [
PropertyType.CHAR_VALUE,
PropertyType.DATE_VALUE,
]:
child_model.add_property(
name="__TEST " + prop_type, property_type=prop_type
)
# Add widget to add configured part models
wm = self.task.widgets()
wm.add_filteredgrid_widget(
parent_instance=source_parent_model.instance(),
part_model=child_model,
all_readable=True,
)
self.bike_model = self.project.model("Bike")
self.bike_instance = self.bike_model.instance()
wm.add_propertygrid_widget(
part_instance=self.bike_instance,
all_readable=True,
)
# Create target parents to move to
self.target_parent_model = self.project.product_root_model.add_model(
name="__TEST CLONE TARGET PARENT", multiplicity=Multiplicity.ONE
)
self.parent_instance = self.target_parent_model.instance()
# In tearDown, delete tasks first, then configured data models
self.bucket = [self.task, self.process, intermediate, self.target_parent_model]
def tearDown(self):
for obj in self.bucket:
if obj:
try:
obj.delete()
except APIError:
pass
super().tearDown()
def test(self):
"""Copy a data model from the catalog to the product data model tree"""
clones = self.client.clone_activities(
activities=[self.task],
activity_parent=self.process,
activity_update_dicts={
self.task.id: {"name": "__TEST CLONE ACTIVITY WITH PARTS"}
},
include_part_models=True,
include_part_instances=True,
include_children=True,
part_parent_model=self.target_parent_model,
part_parent_instance=self.parent_instance,
asynchronous=False,
)
self.assertTrue(clones)
new_children = list(self.parent_instance.children())
self.assertTrue(new_children, msg="No parts were copied")
def test_excluded_models(self):
"""Exclude the bike model from the copy"""
clones = self.client.clone_activities(
activities=[self.task],
activity_parent=self.process,
activity_update_dicts={
self.task.id: {"name": "__TEST CLONE ACTIVITY WITH PARTS"}
},
include_part_models=True,
include_part_instances=True,
include_children=True,
excluded_parts=[self.bike_model, self.bike_instance],
part_parent_model=self.target_parent_model,
part_parent_instance=self.parent_instance,
asynchronous=False,
)
self.assertTrue(clones)
new_children = list(self.parent_instance.children())
self.assertTrue(new_children, msg="No parts were copied")
self.assertNotIn(
"Bike",
{c.name for c in new_children},
msg=(
"Bike should not have been copied over. "
"Actually it is not copied over, it is moved to the parent_instance"
),
)
|
class TestActivityCloneParts(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test(self):
'''Copy a data model from the catalog to the product data model tree'''
pass
def test_excluded_models(self):
'''Exclude the bike model from the copy'''
pass
| 5 | 2 | 28 | 3 | 23 | 2 | 2 | 0.08 | 1 | 6 | 4 | 0 | 4 | 7 | 4 | 79 | 114 | 14 | 93 | 22 | 88 | 7 | 37 | 22 | 32 | 4 | 3 | 3 | 8 |
140,771 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_activities.py
|
tests.test_activities.TestActivityCloneWidgets
|
class TestActivityCloneWidgets(TestBetamax):
def setUp(self):
super().setUp()
self.form = self.project.form(name="Test Cloning Widgets")
self.workflow = self.project.workflow(name="Simple Form Flow")
self.activity_status_to_do = self.form.status_forms[0].activity
self.activity_status_in_progress = self.form.status_forms[1].activity
self.new_activity = None
self.new_form_template = None
def tearDown(self):
wm = self.activity_status_in_progress.widgets()
wm.delete_all_widgets()
if self.new_form_template:
self.new_form_template.delete()
if self.new_activity:
self.new_activity.delete()
super().tearDown()
def test_clone_widgets(self):
self.activity_status_in_progress.clone_widgets(
from_activity=self.activity_status_to_do
)
wm_to_do = self.activity_status_to_do.widgets()
wm_in_progress = self.activity_status_in_progress.widgets()
for widget in wm_in_progress:
self.assertIn(widget.title, [w.title for w in wm_to_do])
def test_clone_widgets_cross_form(self):
self.new_form_template = self.project.create_form_model(
name="Test cross form widget cloning", workflow=self.workflow, contexts=[]
)
self.new_form_template_status_to_do = self.new_form_template.status_forms[
0
].activity
with self.assertRaises(APIError):
self.new_form_template_status_to_do.clone_widgets(
from_activity=self.activity_status_to_do
)
def test_clone_widget_to_an_activity(self):
self.new_activity = self.project.create_activity(
name="Test cross activity widget cloning", activity_type=ActivityType.TASK
)
with self.assertRaises(APIError):
self.new_activity.clone_widgets(from_activity=self.activity_status_to_do)
|
class TestActivityCloneWidgets(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test_clone_widgets(self):
pass
def test_clone_widgets_cross_form(self):
pass
def test_clone_widget_to_an_activity(self):
pass
| 6 | 0 | 9 | 1 | 8 | 0 | 2 | 0 | 1 | 3 | 2 | 0 | 5 | 7 | 5 | 80 | 52 | 10 | 42 | 17 | 36 | 0 | 32 | 17 | 26 | 3 | 3 | 1 | 8 |
140,772 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/value_filter.py
|
pykechain.models.value_filter.ScopeFilter
|
class ScopeFilter(BaseFilter):
"""
Scope filter, used on scope reference properties.
:ivar tag: string
"""
# map between KE-chain field and Pykechain attribute, and whether the filter is stored as a
# list (cs-string)
MAP = [
("name__icontains", "name", False),
("status__in", "status", False),
("due_date__gte", "due_date_gte", False),
("due_date__lte", "due_date_lte", False),
("start_date__gte", "start_date_gte", False),
("start_date__lte", "start_date_lte", False),
("progress__gte", "progress_gte", False),
("progress__lte", "progress_lte", False),
("tags__contains", "tag", True),
("team__in", "team", False),
]
def __init__(
self,
tag: Optional[str] = None,
status: Optional[ScopeStatus] = None,
name: Optional[str] = None,
team: Optional[Union[str, "Team"]] = None,
due_date_gte: Optional[datetime.datetime] = None,
due_date_lte: Optional[datetime.datetime] = None,
start_date_gte: Optional[datetime.datetime] = None,
start_date_lte: Optional[datetime.datetime] = None,
progress_gte: Optional[float] = None,
progress_lte: Optional[float] = None,
**kwargs,
):
"""Create a ScopeFilter object."""
from pykechain.models import Team
filters = [
tag,
status,
name,
team,
due_date_gte,
due_date_lte,
start_date_gte,
start_date_lte,
progress_gte,
progress_lte,
]
if sum(p is not None for p in filters) + len(kwargs) != 1:
raise IllegalArgumentError(
"Every ScopeFilter object must apply only 1 filter!"
)
self.status = check_enum(status, ScopeStatus, "status")
self.name = check_text(name, "name")
self.due_date_gte = check_datetime(due_date_gte, "due_date_gte")
self.due_date_lte = check_datetime(due_date_lte, "due_date_lte")
self.start_date_gte = check_datetime(start_date_gte, "start_date_gte")
self.start_date_lte = check_datetime(start_date_lte, "start_date_lte")
self.progress_gte = check_type(progress_gte, float, "progress_gte")
self.progress_lte = check_type(progress_lte, float, "progress_lte")
self.tag = check_text(tag, "tag")
self.team = check_base(team, Team, "team")
self.extra_filter: dict = kwargs
def __repr__(self):
_repr = "ScopeFilter: "
if self.name:
_repr += f"name: `{self.name}`"
elif self.status:
_repr += f"status `{self.status}`"
elif self.due_date_gte:
_repr += f"due date greater or equal than: `{self.due_date_gte}`"
elif self.due_date_lte:
_repr += f"due date lesser or equal than: `{self.due_date_lte}`"
elif self.start_date_gte:
_repr += f"start date greater or equal than: `{self.start_date_gte}`"
elif self.start_date_lte:
_repr += f"start date lesser or equal than: `{self.start_date_lte}`"
elif self.progress_gte:
_repr += f"progress greater or equal than: {self.progress_gte * 100}%"
elif self.progress_lte:
_repr += f"progress lesser or equal than: {self.progress_lte * 100}%"
elif self.tag:
_repr += f"tag `{self.tag}`"
elif self.team:
_repr += f"team: `{self.team}`"
else:
_repr += f"{self.extra_filter}"
return _repr
@classmethod
def parse_options(cls, options: Dict) -> List["ScopeFilter"]:
"""
Convert the dict & string-based definition of a scope filter to a list of ScopeFilter obj.
:param options: options dict from a scope reference property or meta dict from a scopes
widget.
:return: list of ScopeFilter objects
:rtype list
"""
check_type(options, dict, "options")
filters_dict = options.get(MetaWidget.PREFILTERS, {})
scope_filters = []
mapping = {field: (attr, is_list) for field, attr, is_list in cls.MAP}
for field, value in filters_dict.items():
if field in mapping:
attr, is_list = mapping[field]
try:
if is_list:
values = value.split(",")
else:
values = [value]
except AttributeError:
values = value
for item in values:
scope_filters.append(cls(**{attr: item}))
else:
scope_filters.append(cls(**{field: value}))
return scope_filters
@classmethod
def write_options(cls, filters: List) -> Dict:
"""
Convert the list of Filter objects to a dict.
:param filters: List of BaseFilter objects
:returns options dict to be used to update the options dict of a property
"""
super().write_options(filters=filters)
prefilters = dict()
options = {MetaWidget.PREFILTERS: prefilters}
for f in filters: # type: cls
found = False
for field, attr, is_list in cls.MAP:
filter_value = getattr(f, attr)
if filter_value is not None:
if is_list:
# create a string with comma separted prefilters, the first item directly
# and consequent items with a ,
# TODO: refactor to create a list and then join them with a ','
if field not in prefilters:
prefilters[field] = filter_value
else:
prefilters[field] += f",{filter_value}"
else:
prefilters[field] = filter_value
found = True
break
if not found:
prefilters.update(f.extra_filter)
return options
|
class ScopeFilter(BaseFilter):
'''
Scope filter, used on scope reference properties.
:ivar tag: string
'''
def __init__(
self,
tag: Optional[str] = None,
status: Optional[ScopeStatus] = None,
name: Optional[str] = None,
team: Optional[Union[str, "Team"]] = None,
due_date_gte: Optional[datetime.datetime] = None,
due_date_lte: Optional[datetime.datetime] = None,
start_date_gte: Optional[datetime.datetime] = None,
start_date_lte: Optional[datetime.datetime] = None,
progress_gte: Optional[float] = None,
progress_lte: Optional[float] = None,
**kwargs,
):
'''Create a ScopeFilter object.'''
pass
def __repr__(self):
pass
@classmethod
def parse_options(cls, options: Dict) -> List["ScopeFilter"]:
'''
Convert the dict & string-based definition of a scope filter to a list of ScopeFilter obj.
:param options: options dict from a scope reference property or meta dict from a scopes
widget.
:return: list of ScopeFilter objects
:rtype list
'''
pass
@classmethod
def write_options(cls, filters: List) -> Dict:
'''
Convert the list of Filter objects to a dict.
:param filters: List of BaseFilter objects
:returns options dict to be used to update the options dict of a property
'''
pass
| 7 | 4 | 35 | 4 | 27 | 4 | 7 | 0.19 | 1 | 9 | 3 | 0 | 2 | 11 | 4 | 7 | 168 | 23 | 123 | 47 | 102 | 23 | 70 | 32 | 64 | 11 | 1 | 5 | 26 |
140,773 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.AssociatedObjectId
|
class AssociatedObjectId(Enum):
"""
Options to associate object id's to the meta of a widget (e.g. PaginatedGrid).
:cvar PART_INSTANCE_ID: id of the part instance
:cvar PARENT_INSTANCE_ID: id of the parent instance
:cvar PART_MODEL_ID: id of the part model
:cvar TEAM_ID: id of the team
:cvar PROPERTY_INSTANCE_ID: id of the property instance
:cvar SERVICE_ID: id of the service
:cvar ACTIVITY_ID: id of the activity
"""
PART_INSTANCE_ID = "partInstanceId"
PARENT_INSTANCE_ID = "parentInstanceId"
PARENT_MODEL_ID = "parentPartModelId"
PART_MODEL_ID = "partModelId"
TEAM_ID = "teamId"
PROPERTY_INSTANCE_ID = "propertyInstanceId"
PROPERTY_MODEL_ID = "propertyModelId"
SERVICE_ID = "serviceId"
ACTIVITY_ID = "activityId"
|
class AssociatedObjectId(Enum):
'''
Options to associate object id's to the meta of a widget (e.g. PaginatedGrid).
:cvar PART_INSTANCE_ID: id of the part instance
:cvar PARENT_INSTANCE_ID: id of the parent instance
:cvar PART_MODEL_ID: id of the part model
:cvar TEAM_ID: id of the team
:cvar PROPERTY_INSTANCE_ID: id of the property instance
:cvar SERVICE_ID: id of the service
:cvar ACTIVITY_ID: id of the activity
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 22 | 2 | 10 | 10 | 9 | 10 | 10 | 10 | 9 | 0 | 1 | 0 | 0 |
140,774 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.DashboardWidgetShowForms
|
class DashboardWidgetShowForms(Enum):
"""
Options to display information about forms in a Dashboard widget.
:cvar TOTAL_FORMS: all the forms
:cvar TODO_FORMS: forms which have an active 'to do' status
:cvar INPROGRESS_FORMS: forms which have an active 'in progress' status
:cvar DONE_FORMS: forms which have an active 'done' status
"""
TOTAL_FORMS = "TOTAL_FORMS"
TODO_FORMS = "TODO_FORMS"
INPROGRESS_FORMS = "INPROGRESS_FORMS"
DONE_FORMS = "DONE_FORMS"
|
class DashboardWidgetShowForms(Enum):
'''
Options to display information about forms in a Dashboard widget.
:cvar TOTAL_FORMS: all the forms
:cvar TODO_FORMS: forms which have an active 'to do' status
:cvar INPROGRESS_FORMS: forms which have an active 'in progress' status
:cvar DONE_FORMS: forms which have an active 'done' status
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 14 | 2 | 5 | 5 | 4 | 7 | 5 | 5 | 4 | 0 | 1 | 0 | 0 |
140,775 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.DashboardWidgetShowScopes
|
class DashboardWidgetShowScopes(Enum):
"""
Options to display information about scopes in a Dashboard widget.
:cvar TOTAL_SCOPES: all the projects
:cvar CLOSED_SCOPES: closed projects
:cvar OVERDUE_SCOPES: projects that had their due date in the past
"""
TOTAL_SCOPES = "TOTAL_SCOPES"
CLOSED_SCOPES = "CLOSED_SCOPES"
OVERDUE_SCOPES = "OVERDUE_SCOPES"
|
class DashboardWidgetShowScopes(Enum):
'''
Options to display information about scopes in a Dashboard widget.
:cvar TOTAL_SCOPES: all the projects
:cvar CLOSED_SCOPES: closed projects
:cvar OVERDUE_SCOPES: projects that had their due date in the past
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 12 | 2 | 4 | 4 | 3 | 6 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
140,776 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.DashboardWidgetShowTasks
|
class DashboardWidgetShowTasks(Enum):
"""
Options to display information about tasks in a Dashboard widget.
:cvar TOTAL_TASKS: all the tasks
:cvar CLOSED_TASKS: closed tasks
:cvar OVERDUE_TASKS: tasks that had their due date in the past
:cvar UNASSIGNED_TASKS: tasks that have no assignee
"""
TOTAL_TASKS = "TOTAL_TASKS"
CLOSED_TASKS = "CLOSED_TASKS"
OVERDUE_TASKS = "OVERDUE_TASKS"
UNASSIGNED_TASKS = "UNASSIGNED_TASKS"
|
class DashboardWidgetShowTasks(Enum):
'''
Options to display information about tasks in a Dashboard widget.
:cvar TOTAL_TASKS: all the tasks
:cvar CLOSED_TASKS: closed tasks
:cvar OVERDUE_TASKS: tasks that had their due date in the past
:cvar UNASSIGNED_TASKS: tasks that have no assignee
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 14 | 2 | 5 | 5 | 4 | 7 | 5 | 5 | 4 | 0 | 1 | 0 | 0 |
140,777 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.DashboardWidgetSourceScopes
|
class DashboardWidgetSourceScopes(Enum):
"""
Options to link the Dashboard Widget to a source.
:cvar TAGGED_SCOPES: source is a list of tags
:cvar CURRENT_SCOPE: source is the current project
:cvar SELECTED_SCOPES: source is a list of scopes
:cvar SUBPROCESS: source is an activity
:cvar OWN_SCOPES: source is list of scopes based on user
"""
TAGGED_SCOPES = "taggedScopes"
CURRENT_SCOPE = "project"
SELECTED_SCOPES = "selectedScopes"
SUBPROCESS = "subProcess"
OWN_SCOPES = "scopes"
FORMS = "forms"
|
class DashboardWidgetSourceScopes(Enum):
'''
Options to link the Dashboard Widget to a source.
:cvar TAGGED_SCOPES: source is a list of tags
:cvar CURRENT_SCOPE: source is the current project
:cvar SELECTED_SCOPES: source is a list of scopes
:cvar SUBPROCESS: source is an activity
:cvar OWN_SCOPES: source is list of scopes based on user
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.14 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 17 | 2 | 7 | 7 | 6 | 8 | 7 | 7 | 6 | 0 | 1 | 0 | 0 |
140,778 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.MetaWidget
|
class MetaWidget(Enum):
"""Options found in the meta of all widgets."""
# Common
TITLE = "title"
SHOW_TITLE_VALUE = "showTitleValue"
CUSTOM_TITLE = "customTitle"
SHOW_DESCRIPTION_VALUE = "showDescriptionValue"
DESCRIPTION_OPTION_NOTHING = "No description"
DESCRIPTION_OPTION_CUSTOM = "Custom description"
CUSTOM_DESCRIPTION = "customDescription"
COLLAPSED = "collapsed"
COLLAPSIBLE = "collapsible"
NO_BACKGROUND = "noBackground"
NO_PADDING = "noPadding"
IS_DISABLED = "isDisabled"
IS_MERGED = "isMerged"
# Prefilters
PREFILTERS = "prefilters"
EXCLUDED_PROPERTY_MODELS = "propmodelsExcl"
PROPERTY_MODELS = "property_models"
VALUES = "values"
FILTERS_TYPE = "filters_type"
# Paginated, Super Grids, Scope Members, Tasks widgets
NAME = "name"
PROPERTY_VALUE_PREFILTER = "property_value"
SORTED_COLUMN = "sortedColumn"
SORTED_DIRECTION = "sortDirection"
SHOW_COLUMNS = "showColumns"
COLLAPSE_FILTERS = "collapseFilters"
SHOW_FILTERS = "showFilterPane"
CUSTOM_PAGE_SIZE = "customPageSize"
SHOW_NAME_COLUMN = "showNameColumn"
SHOW_IMAGES = "showImages"
VISIBLE_ADD_BUTTON = "addButtonVisible"
VISIBLE_EDIT_BUTTON = "editButtonVisible"
VISIBLE_DELETE_BUTTON = "deleteButtonVisible"
VISIBLE_CLONE_BUTTON = "cloneButtonVisible"
VISIBLE_DOWNLOAD_BUTTON = "downloadButtonVisible"
VISIBLE_UPLOAD_BUTTON = "uploadButtonVisible"
VISIBLE_INCOMPLETE_ROWS = "incompleteRowsButtonVisible"
EMPHASIZE_ADD_BUTTON = "primaryAddUiValue"
EMPHASIZE_EDIT_BUTTON = "primaryEditUiValue"
EMPHASIZE_CLONE_BUTTON = "primaryCloneUiValue"
EMPHASIZE_DELETE_BUTTON = "primaryDeleteUiValue"
# ScopeGrid and Tasks widgets
VISIBLE_ACTIVE_FILTER = "activeFilterVisible"
VISIBLE_SEARCH_FILTER = "searchFilterVisible"
TAGS = "tags"
# Tasks Widget
VISIBLE_MY_TASKS_FILTER = "myTasksFilterVisible"
VISIBLE_OPEN_TASKS_FILTER = "openTasksFilterVisible"
PARENT_ACTIVITY_ID = "parent_id"
ASSIGNED = "assigned"
ACTIVITY_STATUS = "status__in"
ACTIVITY_TYPE = "activity_type"
ACTIVITY_CLASSIFICATION = "classification"
TAGS_FILTER = "tags__contains"
# Attachment viewer widgets
ALIGNMENT = "alignment"
IMAGE_FIT = "imageFit"
SHOW_DOWNLOAD_BUTTON = "showDownloadButton"
SHOW_FULL_SCREEN_IMAGE_BUTTON = "showFullscreenImageButton"
# Property Grid widget
SHOW_HEADERS = "showHeaders"
CUSTOM_HEIGHT = "customHeight"
# Service Widget and Service Card Widget
EMPHASIZE_BUTTON = "emphasizeButton"
SHOW_DOWNLOAD_LOG = "showDownloadLog"
SHOW_LOG = "showLog"
BUTTON_TEXT_DEFAULT = "Default"
BUTTON_NO_TEXT = "No text"
BUTTON_TEXT_CUSTOM = "Custom text"
# Progress Bar widget
COLOR_NO_PROGRESS = "colorNoProgress"
SHOW_PROGRESS_TEXT = "showProgressText"
COLOR_IN_PROGRESS = "colorInProgress"
COLOR_COMPLETED_PROGRESS = "colorCompleted"
COLOR_IN_PROGRESS_BACKGROUND = "colorInProgressBackground"
# Signature widget
SHOW_UNDO_BUTTON = "showUndoButtonValue"
CUSTOM_UNDO_BUTTON_TEXT = "customUndoText"
CUSTOM_TEXT = "customText" # Used for task-navigation bar and signature widgets
SHOW_BUTTON_VALUE = "showButtonValue"
SHOW_NAME_AND_DATE = "showNameAndDate"
# Dashboard Widget
SOURCE = "source"
SCOPE_TAG = "scopeTag"
SCOPE_LIST = "scopeList"
ORDER = "order"
SELECTED = "selected"
SHOW_NUMBERS = "showNumbers"
SHOW_NUMBERS_FORMS = "showNumbersForForms"
SHOW_NUMBERS_PROJECTS = "showNumbersProjects"
SHOW_ASSIGNEES = "showAssignees"
SHOW_ASSIGNEES_TABLE = "showAssigneesTable"
SHOW_OPEN_TASK_ASSIGNEES = "showOpenTaskAssignees"
SHOW_OPEN_VS_CLOSED_TASKS = "showOpenVsClosedTasks"
SHOW_OPEN_VS_CLOSED_TASKS_ASSIGNEES = "showOpenClosedTasksAssignees"
SHOW_FORM_STATUS_PER_ASSIGNEES = "showFormStatusPerAssignees"
SHOW_ASSIGNEES_FOR_FORM_STATUSES = "showAssigneesForFormStatuses"
SHOW_STATUS_CATEGORY_FORMS = "showStatusCategoryForms"
# Card Widget and Service Card Widget
CUSTOM_IMAGE = "customImage"
SHOW_IMAGE_VALUE = "showImageValue"
CUSTOM_LINK = "customLink"
SHOW_LINK_VALUE = "showLinkValue"
# Task Navigation Widget
EMPHASIZED = "emphasized"
EMPHASIZE = "emphasize"
LINK = "link"
SHOW_HEIGHT_VALUE = "showHeightValue"
TASK_BUTTONS = "taskButtons"
# Meta Panel Widget
SHOW_ALL = "showAll"
# Scope members Widget
SHOW_ADD_USER_BUTTON = "showAddUserButton"
SHOW_EDIT_ROLE_BUTTON = "showEditRoleButton"
SHOW_REMOVE_USER_BUTTON = "showRemoveUserButton"
SHOW_USERNAME_COLUMN = "showUsernameColumn"
SHOW_EMAIL_COLUMN = "showEmailColumn"
SHOW_ROLE_COLUMN = "showRoleColumn"
|
class MetaWidget(Enum):
'''Options found in the meta of all widgets.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.16 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 136 | 15 | 105 | 105 | 104 | 17 | 105 | 105 | 104 | 0 | 1 | 0 | 0 |
140,779 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.MulticolumnWidget
|
class MulticolumnWidget(Widget):
"""Multicolumn Widget."""
|
class MulticolumnWidget(Widget):
'''Multicolumn Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,780 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.PropertyReferenceOptions
|
class PropertyReferenceOptions(Enum):
"""Options to be set for a `Part Reference Property`."""
PREFILTER_PROPERTY_MODELS = "property_models"
PREFILTER_VALUES = "values"
PREFILTER_FILTER_TYPES = "filters_type"
PROPMODELS_EXCLUDED = "propmodels_excl"
SORTED_COLUMN = "sorted_column"
SORTED_DIRECTION = "sort_direction"
NAME = "name"
|
class PropertyReferenceOptions(Enum):
'''Options to be set for a `Part Reference Property`.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.13 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 13 | 4 | 8 | 8 | 7 | 1 | 8 | 8 | 7 | 0 | 1 | 0 | 0 |
140,781 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.TasksWidgetColumns
|
class TasksWidgetColumns(Enum):
"""Columns shown in a `TasksWidget`."""
ASSIGNEES = "assignees"
PROGRESS = "progress"
START_DATE = "start_date"
DUE_DATE = "due_date"
STATUS = "status"
TAGS = "tags"
|
class TasksWidgetColumns(Enum):
'''Columns shown in a `TasksWidget`.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.14 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 9 | 1 | 7 | 7 | 6 | 1 | 7 | 7 | 6 | 0 | 1 | 0 | 0 |
140,782 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget.py
|
pykechain.models.widgets.widget.Widget
|
class Widget(BaseInScope):
"""A virtual object representing a KE-chain Widget.
:cvar basestring id: UUID of the widget
:cvar basestring title: Title of the widget
:cvar basestring ref: Reference of the widget
:cvar basestring widget_type: Type of the widget. Should be one of :class:`WidgetTypes`
:cvar dict meta: Meta definition of the widget
:cvar int order: Order of the widget in the list of widgets
:cvar bool has_subwidgets: if the widgets contains any subwidgets. In case this widget being eg. a Multicolumn
:cvar float progress: Progress of the widget
"""
schema = widget_meta_schema
def __init__(self, json: Dict, manager: "WidgetsManager" = None, **kwargs) -> None:
"""Construct a Widget from a KE-chain 2 json response.
:param json: the json response to construct the :class:`Part` from
:type json: dict
"""
# we need to run the init of 'Base' instead of 'Part' as we do not need the instantiation of properties
super().__init__(json, **kwargs)
del self.name
self.title = json.get("title")
self.ref = json.get("ref")
self.manager = manager
self.widget_type = json.get("widget_type")
# set schema
if self._client:
self.schema = self._client.widget_schema(self.widget_type)
self.meta = self.validate_meta(json.get("meta"))
self.order = json.get("order")
self._activity_id = json.get("activity_id")
self._parent_id = json.get("parent_id")
self.has_subwidgets = json.get("has_subwidgets")
self._scope_id = json.get(
"scope_id"
) # TODO duplicate with `scope_id` attribute
def __repr__(self): # pragma: no cover
return (
f"<pyke {self.__class__.__name__} '{self.widget_type}' id {self.id[-8:]}>"
)
@property
def title_visible(self) -> Optional[str]:
"""
Return the title of the widget displayed in KE-chain.
:return: title string
:rtype str
"""
show_title_value = self.meta.get(MetaWidget.SHOW_TITLE_VALUE)
if show_title_value == WidgetTitleValue.NO_TITLE:
return None
elif show_title_value == WidgetTitleValue.CUSTOM_TITLE:
return self.meta.get(MetaWidget.CUSTOM_TITLE)
elif show_title_value == WidgetTitleValue.DEFAULT:
try:
if self.widget_type == WidgetTypes.PROPERTYGRID:
if self.meta.get(AssociatedObjectId.PART_INSTANCE_ID):
return self._client.part(
pk=self.meta.get(AssociatedObjectId.PART_INSTANCE_ID)
).name
else:
return self._client.part(
pk=self.meta.get(AssociatedObjectId.PART_MODEL_ID)
).name
elif self.widget_type in [
WidgetTypes.FILTEREDGRID,
WidgetTypes.SUPERGRID,
]:
return self._client.part(
pk=self.meta.get(AssociatedObjectId.PART_MODEL_ID),
category=None,
).name
elif self.widget_type in [WidgetTypes.SERVICE, WidgetTypes.NOTEBOOK]:
return self._client.service(
pk=self.meta.get(AssociatedObjectId.SERVICE_ID)
).name
elif self.widget_type in [
WidgetTypes.ATTACHMENTVIEWER,
WidgetTypes.SIGNATURE,
WidgetTypes.WEATHER,
]:
if self.meta.get(AssociatedObjectId.PROPERTY_INSTANCE_ID):
return self._client.property(
pk=self.meta.get(AssociatedObjectId.PROPERTY_INSTANCE_ID),
category=None,
).name
else:
return self._client.property(
pk=self.meta.get(AssociatedObjectId.PROPERTY_MODEL_ID),
category=None,
).name
elif self.widget_type == WidgetTypes.CARD:
return self.scope.name
else:
# TODO Weather, Scope and Task widgets display type in user's language: retrieve from locize API?
# https://api.locize.app/b3df49f9-caf4-4282-9785-43113bff1ff7/latest/nl/common
return None
except NotFoundError: # pragma: no cover
return None
else: # pragma: no cover
return None
def activity(self) -> "Activity":
"""Activity associated to the widget.
:return: The Activity
:rtype: :class:`Activity`
"""
return self._client.activity(id=self._activity_id)
def parent(self) -> "Widget":
"""Parent widget.
:return: The parent of this widget.
:rtype: :class:`Widget`
"""
if not self._parent_id:
raise NotFoundError("Widget has no parent widget (parent_id is null).")
return self._client.widget(pk=self._parent_id)
def validate_meta(self, meta: Dict) -> Dict:
"""Validate the meta and return the meta if validation is successfull.
:param meta: meta of the widget to be validated.
:type meta: dict
:return meta: if the meta is validated correctly
:raise: `ValidationError`
"""
return validate(meta, self.schema) is None and meta
@classmethod
def create(cls, json: Dict, **kwargs) -> "Widget":
"""Create a widget based on the json data.
This method will attach the right class to a widget, enabling the use of type-specific methods.
It does not create a widget object in KE-chain. But a pseudo :class:`Widget` object.
:param json: the json from which the :class:`Widget` object to create
:type json: dict
:return: a :class:`Widget` object
:rtype: :class:`Widget`
"""
def _type_to_classname(type_widget: str):
"""
Generate corresponding inner classname based on the widget type.
:param type_widget: type of the widget (one of :class:`WidgetTypes`)
:type type_widget: str
:return: classname corresponding to the widget type
:rtype: str
"""
return (
f"{type_widget.title()}Widget" if type_widget else WidgetTypes.UNDEFINED
)
widget_type = json.get("widget_type")
# dispatcher to instantiate the right widget class based on the widget type
# load all difference widget types from the pykechain.model.widgets module.
import importlib
all_widgets = importlib.import_module("pykechain.models.widgets")
if hasattr(all_widgets, _type_to_classname(widget_type)):
return getattr(all_widgets, _type_to_classname(widget_type))(
json, client=kwargs.pop("client"), **kwargs
)
else:
return getattr(all_widgets, _type_to_classname(WidgetTypes.UNDEFINED))(
json, client=kwargs.pop("client"), **kwargs
)
#
# Searchers and retrievers
#
def parts(self, *args, **kwargs) -> Any:
"""Retrieve parts belonging to this widget.
Without any arguments it retrieves the Instances related to this widget only.
This call only returns the configured properties in an widget. So properties that are not configured
are not in the returned parts.
See :class:`pykechain.Client.parts` for additional available parameters.
"""
return self._client.parts(*args, widget=self.id, **kwargs)
def associated_parts(self, *args, **kwargs) -> (Any, Any):
"""Retrieve models and instances belonging to this widget.
This is a convenience method for the :func:`Widget.parts()` method, which is used to retrieve both the
`Category.MODEL` as well as the `Category.INSTANCE` in a tuple.
This call only returns the configured (associated) properties in a widget. So properties that are not
configured (associated) are not in the returned parts.
If you want to retrieve only the models associated to this task it is better to use:
`Widget.parts(category=Category.MODEL)`.
See :func:`pykechain.Client.parts` for additional available parameters.
:returns: a tuple(models of :class:`PartSet`, instances of :class:`PartSet`)
"""
models_and_instances = self._client.parts(
*args, widget=self.id, category=None, **kwargs
)
models = [p for p in models_and_instances if p.category == Category.MODEL]
instances = [p for p in models_and_instances if p.category == Category.INSTANCE]
return models, instances
#
# Write methods
#
def update_associations(
self,
readable_models: Optional[List] = None,
writable_models: Optional[List] = None,
part_instance: Optional[Union["Part", str]] = None,
parent_part_instance: Optional[Union["Part", str]] = None,
**kwargs,
) -> None:
"""
Update associations on this widget.
This is a patch to the list of associations: Existing associations are modified but not removed.
Alternatively you may use `inputs` or `outputs` as a alias to `readable_models` and `writable_models`
respectively.
:param readable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
read rights (alias = inputs)
:type readable_models: List[Property] or List[UUID] or None
:param writable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
write rights (alias = outputs)
:type writable_models: List[Property] or List[UUID] or None
:param part_instance: Part object or UUID to be used as instance of the widget
:type part_instance: Part or UUID
:param parent_part_instance: Part object or UUID to be used as parent of the widget
:type parent_part_instance: Part or UUID
:param kwargs: additional keyword arguments to be passed into the API call as param.
:return: None
:raises APIError: when the associations could not be changed
:raise IllegalArgumentError: when the list is not of the right type
"""
self._client.update_widget_associations(
widget=self,
readable_models=readable_models,
writable_models=writable_models,
part_instance=part_instance,
parent_part_instance=parent_part_instance,
**kwargs,
)
def set_associations(
self,
readable_models: Optional[List] = None,
writable_models: Optional[List] = None,
part_instance: Optional[Union["Part", str]] = None,
parent_part_instance: Optional[Union["Part", str]] = None,
**kwargs,
) -> None:
"""
Set associations on this widget.
This is an absolute list of associations. If you provide No models, than the associations are cleared.
Alternatively you may use `inputs` or `outputs` as a alias to `readable_models` and `writable_models`
respectively.
:param readable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
read rights (alias = inputs)
:type readable_models: List[Property] or List[UUID] or None
:param writable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
write rights (alias = outputs)
:type writable_models: List[Property] or List[UUID] or None
:param part_instance: Part object or UUID to be used as instance of the widget
:type part_instance: Part or UUID
:param parent_part_instance: Part object or UUID to be used as parent of the widget
:type parent_part_instance: Part or UUID
:param kwargs: additional keyword arguments to be passed into the API call as param.
:return: None
:raises APIError: when the associations could not be set
:raise IllegalArgumentError: when the list is not of the right type
"""
self._client.set_widget_associations(
widget=self,
readable_models=readable_models,
writable_models=writable_models,
part_instance=part_instance,
parent_part_instance=parent_part_instance,
**kwargs,
)
def remove_associations(
self, models: List[Union["Property", str]], **kwargs
) -> None:
"""
Remove associated properties from the widget.
:param models: list of Properties or their uuids
:return: None
"""
self._client.remove_widget_associations(widget=self, models=models, **kwargs)
def edit(
self,
title: Union[TITLE_TYPING, Empty] = empty,
meta: Optional[Dict] = None,
**kwargs,
) -> None:
"""Edit the details of a widget.
:param title: New title for the widget
* False: use the default title, depending on the widget type
* String value: use this title
* None: No title at all
:type title: basestring, None or False
:param meta: (optional) new Meta definition
:type meta: dict or None
:raises APIError: if the widget could not be updated.
"""
update_dict = dict()
if meta is not None:
self.meta.update(meta)
update_dict.update(dict(meta=self.meta))
if title is not empty:
_set_title(meta=self.meta, title=title)
update_dict.update(meta=self.meta)
if kwargs: # pragma: no cover
update_dict.update(**kwargs)
url = self._client._build_url("widget", widget_id=self.id)
response = self._client._request(
"PUT", url, params=API_EXTRA_PARAMS["widgets"], json=update_dict
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Widget {self}", response=response)
self.refresh(json=response.json().get("results")[0])
def delete(self) -> bool:
"""Delete the widget.
:return: True when successful
:rtype: bool
:raises APIError: when unable to delete the activity
"""
if self.manager:
return self.manager.delete_widget(self)
else:
self._client.delete_widget(widget=self)
def copy(
self, target_activity: "Activity", order: Optional[int] = None
) -> "Widget":
"""Copy the widget.
:param target_activity: `Activity` object under which the desired `Widget` is copied
:type target_activity: :class:`Activity`
:param order: (optional) order in the activity of the widget.
:type order: int or None
:returns: copied :class:`Widget `
:raises IllegalArgumentError: if target_activity is not :class:`Activity`
>>> source_activity = project.activity('Source task')
>>> target_activity = project.activity('Target task')
>>> widget_manager = source_activity.widgets()
>>> widget_to_copy = widget_manager[1]
>>> widget_to_copy.copy(target_activity=target_activity, order=3)
"""
from pykechain.models import Activity
if not isinstance(target_activity, Activity):
raise IllegalArgumentError(
"`target_activity` needs to be an activity, got '{}'".format(
type(target_activity)
)
)
# Retrieve the widget manager of the target activity
widget_manager = target_activity.widgets()
# Get the writable and readable models of the original widget
associated_part = self.parts(category=Category.MODEL)[0]
readable_models = list()
writable_models = list()
for associated_property in associated_part.properties:
if associated_property.output:
writable_models.append(associated_property)
else:
readable_models.append(associated_property)
# Create a perfect copy of the widget
copied_widget = widget_manager.create_widget(
meta=self.meta,
widget_type=self.widget_type,
title=self.title,
writable_models=writable_models,
readable_models=readable_models,
order=order,
)
return copied_widget
def move(
self, target_activity: "Activity", order: Optional[int] = None
) -> "Widget":
"""Move the widget.
:param target_activity: `Activity` object under which the desired `Widget` is moved
:type target_activity: :class:`Activity`
:param order: (optional) order in the activity of the widget.
:type order: int or None
:returns: copied :class:`Widget `
:raises IllegalArgumentError: if target_activity is not :class:`Activity`
"""
moved_widget = self.copy(target_activity=target_activity, order=order)
self.delete()
return moved_widget
@staticmethod
def _validate_excel_export_inputs(
target_dir: str,
file_name: str,
user: "User",
default_file_name: Callable,
) -> Tuple[str, str, "User"]:
"""Check, convert and return the inputs for the Excel exporter functions."""
if target_dir is None:
target_dir = os.getcwd()
elif not isinstance(target_dir, str) or not os.path.isdir(target_dir):
raise IllegalArgumentError("`target_dir` must be a valid directory.")
if file_name is None:
file_name = default_file_name()
else:
if not isinstance(file_name, str):
raise IllegalArgumentError(
f'`file_name` must be a string, "{file_name}" is not.'
)
elif ".xls" in file_name:
file_name = file_name.split(".xls")[0]
file_name = slugify_ref(file_name)
if not file_name.endswith(".xlsx"):
file_name += ".xlsx"
from pykechain.models import User
if user is not None and not isinstance(user, User):
raise IllegalArgumentError(
f'`user` must be a Pykechain User object, "{user}" is not.'
)
return target_dir, file_name, user
def download_as_excel(
self,
target_dir: Optional[str] = None,
file_name: Optional[str] = None,
user: "User" = None,
) -> str:
"""
Export a grid widget as an Excel sheet.
:param target_dir: directory (path) to store the Excel sheet.
:type target_dir: str
:param file_name: optional, name of the Excel file
:type file_name: str
:param user: User object to create timezone-aware datetime values
:type user: User
:return: file path of the created Excel sheet
:rtype str
"""
grid_widgets = {WidgetTypes.SUPERGRID, WidgetTypes.FILTEREDGRID}
if self.widget_type not in grid_widgets:
raise IllegalArgumentError(
f"Only widgets of type {grid_widgets} can be exported to Excel,"
f" `{self.widget_type}` is not."
)
part_model_id = self.meta.get("partModelId")
parent_instance_id = self.meta.get("parentInstanceId")
def default_file_name():
return (
self._client.model(pk=part_model_id).name if file_name is None else ""
)
target_dir, file_name, user = self._validate_excel_export_inputs(
target_dir, file_name, user, default_file_name
)
json = dict(
model_id=part_model_id,
parent_id=parent_instance_id,
widget_id=self.id,
export_format="xlsx",
)
if user:
now_utc = datetime.datetime.now(tz=pytz.utc)
now_local = user.now_in_my_timezone()
offset_minutes = int(round((now_utc - now_local).total_seconds() / 60.0))
else:
offset_minutes = 0
params = dict(offset=offset_minutes)
url = self._client._build_url("parts_export")
response = self._client._request("GET", url, data=json, params=params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(
f"Could not export widget {str(response)}: {response.content}"
)
full_path = os.path.join(target_dir, file_name)
with open(full_path, "wb") as f:
for chunk in response:
f.write(chunk)
return full_path
|
class Widget(BaseInScope):
'''A virtual object representing a KE-chain Widget.
:cvar basestring id: UUID of the widget
:cvar basestring title: Title of the widget
:cvar basestring ref: Reference of the widget
:cvar basestring widget_type: Type of the widget. Should be one of :class:`WidgetTypes`
:cvar dict meta: Meta definition of the widget
:cvar int order: Order of the widget in the list of widgets
:cvar bool has_subwidgets: if the widgets contains any subwidgets. In case this widget being eg. a Multicolumn
:cvar float progress: Progress of the widget
'''
def __init__(self, json: Dict, manager: "WidgetsManager" = None, **kwargs) -> None:
'''Construct a Widget from a KE-chain 2 json response.
:param json: the json response to construct the :class:`Part` from
:type json: dict
'''
pass
def __repr__(self):
pass
@property
def title_visible(self) -> Optional[str]:
'''
Return the title of the widget displayed in KE-chain.
:return: title string
:rtype str
'''
pass
def activity(self) -> "Activity":
'''Activity associated to the widget.
:return: The Activity
:rtype: :class:`Activity`
'''
pass
def parent(self) -> "Widget":
'''Parent widget.
:return: The parent of this widget.
:rtype: :class:`Widget`
'''
pass
def validate_meta(self, meta: Dict) -> Dict:
'''Validate the meta and return the meta if validation is successfull.
:param meta: meta of the widget to be validated.
:type meta: dict
:return meta: if the meta is validated correctly
:raise: `ValidationError`
'''
pass
@classmethod
def create(cls, json: Dict, **kwargs) -> "Widget":
'''Create a widget based on the json data.
This method will attach the right class to a widget, enabling the use of type-specific methods.
It does not create a widget object in KE-chain. But a pseudo :class:`Widget` object.
:param json: the json from which the :class:`Widget` object to create
:type json: dict
:return: a :class:`Widget` object
:rtype: :class:`Widget`
'''
pass
def _type_to_classname(type_widget: str):
'''
Generate corresponding inner classname based on the widget type.
:param type_widget: type of the widget (one of :class:`WidgetTypes`)
:type type_widget: str
:return: classname corresponding to the widget type
:rtype: str
'''
pass
def parts(self, *args, **kwargs) -> Any:
'''Retrieve parts belonging to this widget.
Without any arguments it retrieves the Instances related to this widget only.
This call only returns the configured properties in an widget. So properties that are not configured
are not in the returned parts.
See :class:`pykechain.Client.parts` for additional available parameters.
'''
pass
def associated_parts(self, *args, **kwargs) -> (Any, Any):
'''Retrieve models and instances belonging to this widget.
This is a convenience method for the :func:`Widget.parts()` method, which is used to retrieve both the
`Category.MODEL` as well as the `Category.INSTANCE` in a tuple.
This call only returns the configured (associated) properties in a widget. So properties that are not
configured (associated) are not in the returned parts.
If you want to retrieve only the models associated to this task it is better to use:
`Widget.parts(category=Category.MODEL)`.
See :func:`pykechain.Client.parts` for additional available parameters.
:returns: a tuple(models of :class:`PartSet`, instances of :class:`PartSet`)
'''
pass
def update_associations(
self,
readable_models: Optional[List] = None,
writable_models: Optional[List] = None,
part_instance: Optional[Union["Part", str]] = None,
parent_part_instance: Optional[Union["Part", str]] = None,
**kwargs,
) -> None:
'''
Update associations on this widget.
This is a patch to the list of associations: Existing associations are modified but not removed.
Alternatively you may use `inputs` or `outputs` as a alias to `readable_models` and `writable_models`
respectively.
:param readable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
read rights (alias = inputs)
:type readable_models: List[Property] or List[UUID] or None
:param writable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
write rights (alias = outputs)
:type writable_models: List[Property] or List[UUID] or None
:param part_instance: Part object or UUID to be used as instance of the widget
:type part_instance: Part or UUID
:param parent_part_instance: Part object or UUID to be used as parent of the widget
:type parent_part_instance: Part or UUID
:param kwargs: additional keyword arguments to be passed into the API call as param.
:return: None
:raises APIError: when the associations could not be changed
:raise IllegalArgumentError: when the list is not of the right type
'''
pass
def set_associations(
self,
readable_models: Optional[List] = None,
writable_models: Optional[List] = None,
part_instance: Optional[Union["Part", str]] = None,
parent_part_instance: Optional[Union["Part", str]] = None,
**kwargs,
) -> None:
'''
Set associations on this widget.
This is an absolute list of associations. If you provide No models, than the associations are cleared.
Alternatively you may use `inputs` or `outputs` as a alias to `readable_models` and `writable_models`
respectively.
:param readable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
read rights (alias = inputs)
:type readable_models: List[Property] or List[UUID] or None
:param writable_models: list of property models (of :class:`Property` or property_ids (uuids) that has
write rights (alias = outputs)
:type writable_models: List[Property] or List[UUID] or None
:param part_instance: Part object or UUID to be used as instance of the widget
:type part_instance: Part or UUID
:param parent_part_instance: Part object or UUID to be used as parent of the widget
:type parent_part_instance: Part or UUID
:param kwargs: additional keyword arguments to be passed into the API call as param.
:return: None
:raises APIError: when the associations could not be set
:raise IllegalArgumentError: when the list is not of the right type
'''
pass
def remove_associations(
self, models: List[Union["Property", str]], **kwargs
) -> None:
'''
Remove associated properties from the widget.
:param models: list of Properties or their uuids
:return: None
'''
pass
def edit(
self,
title: Union[TITLE_TYPING, Empty] = empty,
meta: Optional[Dict] = None,
**kwargs,
) -> None:
'''Edit the details of a widget.
:param title: New title for the widget
* False: use the default title, depending on the widget type
* String value: use this title
* None: No title at all
:type title: basestring, None or False
:param meta: (optional) new Meta definition
:type meta: dict or None
:raises APIError: if the widget could not be updated.
'''
pass
def delete(self) -> bool:
'''Delete the widget.
:return: True when successful
:rtype: bool
:raises APIError: when unable to delete the activity
'''
pass
def copy(
self, target_activity: "Activity", order: Optional[int] = None
) -> "Widget":
'''Copy the widget.
:param target_activity: `Activity` object under which the desired `Widget` is copied
:type target_activity: :class:`Activity`
:param order: (optional) order in the activity of the widget.
:type order: int or None
:returns: copied :class:`Widget `
:raises IllegalArgumentError: if target_activity is not :class:`Activity`
>>> source_activity = project.activity('Source task')
>>> target_activity = project.activity('Target task')
>>> widget_manager = source_activity.widgets()
>>> widget_to_copy = widget_manager[1]
>>> widget_to_copy.copy(target_activity=target_activity, order=3)
'''
pass
def move(
self, target_activity: "Activity", order: Optional[int] = None
) -> "Widget":
'''Move the widget.
:param target_activity: `Activity` object under which the desired `Widget` is moved
:type target_activity: :class:`Activity`
:param order: (optional) order in the activity of the widget.
:type order: int or None
:returns: copied :class:`Widget `
:raises IllegalArgumentError: if target_activity is not :class:`Activity`
'''
pass
@staticmethod
def _validate_excel_export_inputs(
target_dir: str,
file_name: str,
user: "User",
default_file_name: Callable,
) -> Tuple[str, str, "User"]:
'''Check, convert and return the inputs for the Excel exporter functions.'''
pass
def download_as_excel(
self,
target_dir: Optional[str] = None,
file_name: Optional[str] = None,
user: "User" = None,
) -> str:
'''
Export a grid widget as an Excel sheet.
:param target_dir: directory (path) to store the Excel sheet.
:type target_dir: str
:param file_name: optional, name of the Excel file
:type file_name: str
:param user: User object to create timezone-aware datetime values
:type user: User
:return: file path of the created Excel sheet
:rtype str
'''
pass
def default_file_name():
pass
| 24 | 19 | 26 | 4 | 14 | 9 | 3 | 0.64 | 1 | 18 | 9 | 26 | 16 | 11 | 18 | 25 | 551 | 98 | 281 | 103 | 219 | 179 | 147 | 63 | 123 | 12 | 2 | 4 | 55 |
140,783 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.AttachmentviewerWidget
|
class AttachmentviewerWidget(Widget):
"""Attachmentviewer Widget."""
|
class AttachmentviewerWidget(Widget):
'''Attachmentviewer Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,784 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.CardWidget
|
class CardWidget(Widget):
"""Card Widget."""
|
class CardWidget(Widget):
'''Card Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,785 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.FilteredgridWidget
|
class FilteredgridWidget(Widget):
"""Filteredgrid Widget."""
|
class FilteredgridWidget(Widget):
'''Filteredgrid Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,786 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.FormmetapanelWidget
|
class FormmetapanelWidget(Widget):
"""FormMetapanel Widget."""
|
class FormmetapanelWidget(Widget):
'''FormMetapanel Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,787 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.HtmlWidget
|
class HtmlWidget(Widget):
"""HTML Widget."""
|
class HtmlWidget(Widget):
'''HTML Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,788 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.JsonWidget
|
class JsonWidget(Widget):
"""JSON Widget."""
|
class JsonWidget(Widget):
'''JSON Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,789 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.MarkdownWidget
|
class MarkdownWidget(Widget):
"""HTML Widget."""
|
class MarkdownWidget(Widget):
'''HTML Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,790 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.MetapanelWidget
|
class MetapanelWidget(Widget):
"""Metapanel Widget."""
|
class MetapanelWidget(Widget):
'''Metapanel Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,791 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/enums.py
|
pykechain.models.widgets.enums.TasksAssignmentFilterTypes
|
class TasksAssignmentFilterTypes(Enum):
"""User assignment filter options of a `TasksWidget`."""
ALL = "ALL"
FILTER_ASSIGNED_TO_USER = "LOGGED_USER_ASSIGNED"
FILTER_ASSIGNED = "ASSIGNED"
FILTER_UNASSIGNED = "UNASSIGNED"
|
class TasksAssignmentFilterTypes(Enum):
'''User assignment filter options of a `TasksWidget`.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 7 | 1 | 5 | 5 | 4 | 1 | 5 | 5 | 4 | 0 | 1 | 0 | 0 |
140,792 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/representations.py
|
pykechain.models.representations.representations.ScopeMembersOnlyRepresentation
|
class ScopeMembersOnlyRepresentation(SimpleConfigValueKeyRepresentation):
"""Representation for the users shown inside a `ScopeMembersReferencesProperty`."""
rtype = PropertyRepresentation.SHOW_ONLY_SCOPE_MEMBERS
|
class ScopeMembersOnlyRepresentation(SimpleConfigValueKeyRepresentation):
'''Representation for the users shown inside a `ScopeMembersReferencesProperty`.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 4 | 1 | 2 | 2 | 1 | 1 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
140,793 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/widgets/widget_models.py
|
pykechain.models.widgets.widget_models.DashboardWidget
|
class DashboardWidget(Widget):
"""Dashboard Widget."""
|
class DashboardWidget(Widget):
'''Dashboard Widget.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 25 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
140,794 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/representations/representations.py
|
pykechain.models.representations.representations.GeoCoordinateRepresentation
|
class GeoCoordinateRepresentation(BaseRepresentation):
"""Representation for Geocoordinate properties.
It should look like this in the value_options
# "representations": [
# {
# "rtype": "geoCoordinate",
# "config": {
# "geoCoordinate": "rd_amersfoort" # can be any of GeoCoordinateConfig
# }
# }
# ]
# },
"""
rtype = PropertyRepresentation.GEOCOORDINATE
_config_value_key = "geoCoordinate"
def validate_representation(self, value: GeoCoordinateConfig) -> None:
"""
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: one of GeoCoordinateConfig
:return: None
"""
if value not in GeoCoordinateConfig.values():
raise IllegalArgumentError(
"{} value '{}' is not correct: Not a GeoCoordinateConfig option: {}".format(
self.__class__.__name__, value, GeoCoordinateConfig.values()
)
)
|
class GeoCoordinateRepresentation(BaseRepresentation):
'''Representation for Geocoordinate properties.
It should look like this in the value_options
# "representations": [
# {
# "rtype": "geoCoordinate",
# "config": {
# "geoCoordinate": "rd_amersfoort" # can be any of GeoCoordinateConfig
# }
# }
# ]
# },
'''
def validate_representation(self, value: GeoCoordinateConfig) -> None:
'''
Validate whether the representation value can be set.
:param value: representation value to set.
:type value: one of GeoCoordinateConfig
:return: None
'''
pass
| 2 | 2 | 14 | 1 | 7 | 6 | 2 | 1.8 | 1 | 2 | 2 | 0 | 1 | 0 | 1 | 9 | 32 | 4 | 10 | 4 | 8 | 18 | 6 | 4 | 4 | 2 | 1 | 1 | 2 |
140,795 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_exceptions.py
|
tests.test_exceptions.TestExceptions
|
class TestExceptions(TestCase):
def test_api_error(self):
api_error = APIError()
with self.assertRaises(Exception):
raise api_error
def test_api_error_with_message(self):
api_error = APIError("This is the error message.")
with self.assertRaises(APIError):
raise api_error
def test_api_error_with_objects(self):
APIError(["text in a list"])
APIError(("text in a tuple",))
APIError(dict(text="in a dict"))
def test_inheritance(self):
self.assertTrue(issubclass(APIError, BaseException))
self.assertTrue(issubclass(ForbiddenError, APIError))
self.assertTrue(issubclass(MultipleFoundError, APIError))
self.assertTrue(issubclass(NotFoundError, APIError))
self.assertTrue(issubclass(ClientError, APIError))
self.assertFalse(issubclass(IllegalArgumentError, APIError))
self.assertFalse(issubclass(InspectorComponentError, APIError))
def test_creation(self):
for test_class in [
APIError,
ForbiddenError,
MultipleFoundError,
NotFoundError,
ClientError,
IllegalArgumentError,
InspectorComponentError,
]:
with self.subTest(msg=test_class.__name__):
test_class()
|
class TestExceptions(TestCase):
def test_api_error(self):
pass
def test_api_error_with_message(self):
pass
def test_api_error_with_objects(self):
pass
def test_inheritance(self):
pass
def test_creation(self):
pass
| 6 | 0 | 7 | 1 | 6 | 0 | 1 | 0 | 1 | 10 | 7 | 0 | 5 | 0 | 5 | 77 | 40 | 7 | 33 | 9 | 27 | 0 | 25 | 9 | 19 | 2 | 2 | 2 | 6 |
140,796 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_enums.py
|
tests.test_enums.TestEnums
|
class TestEnums(TestCase):
def test_inheritance(self):
values = SecondEnum.values()
self.assertIn("first slug", values)
|
class TestEnums(TestCase):
def test_inheritance(self):
pass
| 2 | 0 | 4 | 1 | 3 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
140,797 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_enums.py
|
tests.test_enums.SecondEnum
|
class SecondEnum(FirstEnum):
SLUG_2 = "second slug"
|
class SecondEnum(FirstEnum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
140,798 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_enums.py
|
tests.test_enums.FirstEnum
|
class FirstEnum(Enum):
SLUG_1 = "first slug"
|
class FirstEnum(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
140,799 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_contexts.py
|
tests.test_contexts.TestContexts
|
class TestContexts(TestContextSetup):
def test_retrieve_contexts_via_client_using_scope_filter(self):
with self.subTest("via uuid"):
contexts = self.client.contexts(scope=self.project.id)
self.assertIsInstance(contexts[0], Context)
with self.subTest("via Scope"):
contexts = self.client.contexts(scope=self.project)
self.assertIsInstance(contexts[0], Context)
with self.subTest("via uuid string"):
contexts = self.client.contexts(scope=str(self.project.id))
self.assertIsInstance(contexts[0], Context)
def test_retrieve_single_context_via_client_with_pk_filter(self):
self.assertIsInstance(self.client.context(pk=self.context.id), Context)
self.assertTrue(self.client.context(pk=self.context.id), Context)
def test_create_contexts_bound_to_an_activity(self):
task = self.project.create_activity("__Test task")
self.assertIsInstance(task, Activity)
self.context.link_activities(activities=[task])
self.context.refresh()
self.assertTrue(self.context.activities, [task])
def test_retrieve_multiple_context_via_client_using_filters(self):
contexts = self.client.contexts(
name__contains="__my first context for testing",
context_type=ContextType.TIME_PERIOD,
scope=self.project.id
)
self.assertEqual(len(contexts), 1)
def test_link_context_to_activity(self):
self.assertFalse(self.context.activities)
self.context.link_activities(
activities=[self.project.activity(name="Specify wheel diameter")]
)
self.assertTrue(self.context.activities)
def test_context_consequetive_link_many_activities(self):
self.assertFalse(self.context.activities)
self.context.link_activities(
activities=[self.project.activity(name="Specify wheel diameter")]
)
self.assertEqual(len(self.context.activities), 1)
self.context.link_activities(activities=[self.project.activity(name="Task - Form")])
self.assertEqual(len(self.context.activities), 2)
def test_unlink_context_to_activity(self):
self.assertFalse(self.context.activities)
self.context.link_activities(
activities=[self.project.activity(name="Specify wheel diameter")]
)
self.assertTrue(self.context.activities)
self.context.unlink_activities(
activities=[self.project.activity(name="Specify wheel diameter")]
)
self.assertFalse(self.context.activities)
def test_context_unlink_single_activity_when_more_activities(self):
self.assertFalse(self.context.activities)
self.context.link_activities(
activities=[
self.project.activity(name="Specify wheel diameter"),
self.project.activity(name="Task - Form"),
]
)
self.assertEqual(len(self.context.activities), 2)
self.context.unlink_activities(
activities=[self.project.activity(name="Specify wheel diameter")]
)
self.assertEqual(len(self.context.activities), 1)
self.assertListEqual(
list(self.context.activities), [self.project.activity(name="Task - Form").id]
)
|
class TestContexts(TestContextSetup):
def test_retrieve_contexts_via_client_using_scope_filter(self):
pass
def test_retrieve_single_context_via_client_with_pk_filter(self):
pass
def test_create_contexts_bound_to_an_activity(self):
pass
def test_retrieve_multiple_context_via_client_using_filters(self):
pass
def test_link_context_to_activity(self):
pass
def test_context_consequetive_link_many_activities(self):
pass
def test_unlink_context_to_activity(self):
pass
def test_context_unlink_single_activity_when_more_activities(self):
pass
| 9 | 0 | 9 | 0 | 8 | 0 | 1 | 0 | 1 | 4 | 2 | 0 | 8 | 0 | 8 | 85 | 77 | 10 | 67 | 12 | 58 | 0 | 46 | 12 | 37 | 1 | 4 | 1 | 8 |
140,800 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_contexts.py
|
tests.test_contexts.TestContextSetup
|
class TestContextSetup(TestBetamax):
"""Only for test setup, will create a context
:ivar context: context
"""
def setUp(self):
super().setUp()
self.context = self.client.create_context(
name="__my first context for testing",
context_type=ContextType.TIME_PERIOD,
scope=self.project.id,
tags=["testing"],
) # type: Context
def tearDown(self):
self.context.delete()
super().tearDown()
|
class TestContextSetup(TestBetamax):
'''Only for test setup, will create a context
:ivar context: context
'''
def setUp(self):
pass
def tearDown(self):
pass
| 3 | 1 | 6 | 0 | 6 | 1 | 1 | 0.33 | 1 | 2 | 1 | 1 | 2 | 1 | 2 | 77 | 18 | 3 | 12 | 4 | 9 | 4 | 7 | 4 | 4 | 1 | 3 | 0 | 2 |
140,801 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_contexts.py
|
tests.test_contexts.TestContextCreate
|
class TestContextCreate(TestBetamax):
def test_create_context(self):
context = self.client.create_context(
name="__my first context for testing",
context_type=ContextType.TIME_PERIOD,
scope=self.project,
tags=["testing"],
)
self.assertTrue(context)
self.assertSetEqual(set(context.tags), {"testing"})
self.assertTrue(context.scope_id == self.project.id)
self.assertEqual(context.name, "__my first context for testing")
self.assertEqual(context.context_type, ContextType.TIME_PERIOD)
# destroy
context.delete()
|
class TestContextCreate(TestBetamax):
def test_create_context(self):
pass
| 2 | 0 | 15 | 1 | 13 | 1 | 1 | 0.07 | 1 | 2 | 1 | 0 | 1 | 1 | 1 | 76 | 16 | 1 | 14 | 4 | 12 | 1 | 9 | 3 | 7 | 1 | 3 | 0 | 1 |
140,802 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_client.py
|
tests.test_client.TestCloneScopeAsync
|
class TestCloneScopeAsync(TestBetamax):
def setUp(self):
super().setUp()
self.temp_scope = None
self.source = self.client.create_scope(
name="_Async to be cloned scope SOURCE",
)
time.sleep(3)
def tearDown(self):
self.source.delete()
if self.temp_scope:
self.temp_scope.delete()
super().tearDown()
def test_clone_asynchronous(self):
# setUp
clone_name = "_Async cloned scope TARGET"
self.client.clone_scope(
name=clone_name,
source_scope=self.source,
asynchronous=True,
)
for _ in range(5):
try:
self.temp_scope = self.client.scope(name=clone_name)
except NotFoundError:
time.sleep(3)
continue
else:
break
# testing
self.assertIsInstance(self.temp_scope, Scope)
|
class TestCloneScopeAsync(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test_clone_asynchronous(self):
pass
| 4 | 0 | 11 | 1 | 9 | 1 | 2 | 0.07 | 1 | 4 | 2 | 0 | 3 | 2 | 3 | 78 | 36 | 5 | 29 | 8 | 25 | 2 | 23 | 8 | 19 | 3 | 3 | 2 | 6 |
140,803 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.TransitionType
|
class TransitionType(Enum):
"""
Options for the Type of a Transition.
:cvar INITIAL: Initial transition, the initial transition to follow when the form is created.
:cvar GLOBAL: Global transition, possibility to transition to all statuses from any
:cvar DIRECTED: A Directed transition, a transition with a specific from -> to direction
"""
INITIAL = "INITIAL"
GLOBAL = "GLOBAL"
DIRECTED = "DIRECTED"
|
class TransitionType(Enum):
'''
Options for the Type of a Transition.
:cvar INITIAL: Initial transition, the initial transition to follow when the form is created.
:cvar GLOBAL: Global transition, possibility to transition to all statuses from any
:cvar DIRECTED: A Directed transition, a transition with a specific from -> to direction
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 12 | 2 | 4 | 4 | 3 | 6 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
140,804 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.TeamRoles
|
class TeamRoles(Enum):
"""Roles that exist for a team member.
:cvar MEMBER: A normal team member
:cvar MANAGER: A team member that may manage the team (add or remove members, change team)
:cvar OWNER: The owner of a team
"""
MEMBER = "MEMBER"
MANAGER = "MANAGER"
OWNER = "OWNER"
|
class TeamRoles(Enum):
'''Roles that exist for a team member.
:cvar MEMBER: A normal team member
:cvar MANAGER: A team member that may manage the team (add or remove members, change team)
:cvar OWNER: The owner of a team
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 11 | 2 | 4 | 4 | 3 | 5 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
140,805 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_client.py
|
tests.test_client.TestClient
|
class TestClient(TestCase):
def setUp(self):
self.env = EnvironmentVarGuard()
def test_init_default_url(self):
client = Client()
self.assertEqual(client.api_root, "http://localhost:8000/")
def test_init_custom_url(self):
client = Client(url="http://testing.com:1234")
self.assertEqual(client.api_root, "http://testing.com:1234")
def test_init_no_login(self):
client = Client()
self.assertNotIn("Authorization", client.headers)
self.assertIsNone(client.auth)
def test_init_basic_auth(self):
client = Client()
client.login("someuser", "withpass")
self.assertNotIn("Authorization", client.headers)
self.assertTrue(client.auth)
def test_init_token(self):
client = Client()
PSEUDO_TOKEN = "123123"
client.login(token=PSEUDO_TOKEN)
self.assertTrue(client.headers["Authorization"], f"Token {PSEUDO_TOKEN}")
self.assertIsNone(client.auth)
def test_init_no_ssl(self):
client = Client(check_certificates=False)
self.assertFalse(client.session.verify)
# 1.12
def test_client_raises_error_with_false_url(self):
with self.assertRaises(ClientError):
Client(url="wrongurl")
def test_client_from_env(self):
"""
Test if the client does not provide a warning when no env file can be found
Userwarning: 'Could not any envfile.'
'.../lib/python3.5/site-packages/envparse.py'
"""
self.env.set("KECHAIN_URL", "http://localhost:8000")
with self.env:
with warnings.catch_warnings(record=True) as captured_warnings:
client = Client.from_env()
self.assertEqual(len(captured_warnings), 0)
# noinspection PyTypeChecker
def test_reload(self):
client = Client()
not_a_kechain_object = 3
with self.assertRaises(
IllegalArgumentError, msg="Reload must receive an object of type Base."
):
client.reload(not_a_kechain_object)
empty_kechain_object = Base(
json=dict(name="empty", id="1234567890"), client=client
)
with self.assertRaises(
IllegalArgumentError, msg="Reload cant find API resource for type Base"
):
client.reload(empty_kechain_object)
|
class TestClient(TestCase):
def setUp(self):
pass
def test_init_default_url(self):
pass
def test_init_custom_url(self):
pass
def test_init_no_login(self):
pass
def test_init_basic_auth(self):
pass
def test_init_token(self):
pass
def test_init_no_ssl(self):
pass
def test_client_raises_error_with_false_url(self):
pass
def test_client_from_env(self):
'''
Test if the client does not provide a warning when no env file can be found
Userwarning: 'Could not any envfile.'
'.../lib/python3.5/site-packages/envparse.py'
'''
pass
def test_reload(self):
pass
| 11 | 1 | 7 | 1 | 5 | 1 | 1 | 0.14 | 1 | 6 | 4 | 0 | 10 | 1 | 10 | 82 | 77 | 20 | 50 | 24 | 39 | 7 | 44 | 23 | 33 | 1 | 2 | 2 | 10 |
140,806 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.SubprocessDisplayMode
|
class SubprocessDisplayMode(Enum):
"""
URL variations to vary the display of a subprocess activity.
:cvar ACTIVITIES: "activities"
:cvar TREEVIEW: "treeview"
"""
ACTIVITIES = "activities"
TREEVIEW = "treeview"
|
class SubprocessDisplayMode(Enum):
'''
URL variations to vary the display of a subprocess activity.
:cvar ACTIVITIES: "activities"
:cvar TREEVIEW: "treeview"
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 10 | 2 | 3 | 3 | 2 | 5 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
140,807 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.StoredFileSize
|
class StoredFileSize(Enum):
"""
Options for the StoredFile Size.
:cvar XS: XS (100, None) # pixels width
:cvar S: S (320, None)
:cvar M: M (640, None)
:cvar L: L (1024, None)
:cvar XL: XL (2048, None)
:cvar FULL_SIZE: full_size
:cvar SOURCE: source file
"""
XS = "XS"
S = "S"
M = "M"
L = "L"
XL = "XL"
FULL_SIZE = "full_size"
SOURCE = "source"
|
class StoredFileSize(Enum):
'''
Options for the StoredFile Size.
:cvar XS: XS (100, None) # pixels width
:cvar S: S (320, None)
:cvar M: M (640, None)
:cvar L: L (1024, None)
:cvar XL: XL (2048, None)
:cvar FULL_SIZE: full_size
:cvar SOURCE: source file
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 20 | 2 | 8 | 8 | 7 | 10 | 8 | 8 | 7 | 0 | 1 | 0 | 0 |
140,808 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.StoredFileClassification
|
class StoredFileClassification(Enum):
"""
Classification of Stored files.
:cvar GLOBAL: Global classification
:cvar SCOPED: Scoped classification
"""
GLOBAL = "GLOBAL"
SCOPED = "SCOPED"
|
class StoredFileClassification(Enum):
'''
Classification of Stored files.
:cvar GLOBAL: Global classification
:cvar SCOPED: Scoped classification
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 10 | 2 | 3 | 3 | 2 | 5 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
140,809 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.StoredFileCategory
|
class StoredFileCategory(Enum):
"""
Category of Stored files.
:cvar GLOBAL: Global status
:cvar REFERENCED: Referenced status
"""
GLOBAL = "GLOBAL"
REFERENCED = "REFERENCED"
|
class StoredFileCategory(Enum):
'''
Category of Stored files.
:cvar GLOBAL: Global status
:cvar REFERENCED: Referenced status
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 10 | 2 | 3 | 3 | 2 | 5 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
140,810 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_client.py
|
tests.test_client.TestClientLive
|
class TestClientLive(TestBetamax):
def setUp(self):
super().setUp()
self.temp_scope = None
def tearDown(self):
"""Teardown the test, remove the scope.
When you create a scope, assign it to self.temp_scope such that it is deleted when the test is complete
"""
if self.temp_scope:
self.temp_scope.delete()
super().tearDown()
def test_login(self):
self.assertTrue(self.project.parts())
def test_no_login(self):
self.client.login("wrong", "user")
with self.assertRaises(ForbiddenError):
self.client.parts()
# 3.6.3
def test_get_current_user(self):
user = self.client.current_user()
from pykechain.models import User
self.assertIsInstance(user, User)
self.client.auth = None
self.client.headers = None
with self.assertRaises(APIError):
self.client.current_user()
# 3.7.0
def test_reload_deleted_object(self):
bike_model = self.project.model(name="Bike")
bike = bike_model.instance()
wheel_model = bike_model.child(name="Wheel")
wheel_name = "__new wheel: test for reloading"
new_wheel_1 = bike.add(name=wheel_name, model=wheel_model)
new_wheel_2 = self.project.part(name=wheel_name)
self.assertFalse(
new_wheel_1 is new_wheel_2, "Parts must be separate in Python memory"
)
self.assertEqual(new_wheel_1, new_wheel_2, "Parts must be identical in UUIDs")
new_wheel_2.delete()
with self.assertRaises(NotFoundError):
self.project.part(name=wheel_name)
with self.assertRaises(
NotFoundError, msg="Wheel cant be reloaded after it was deleted"
):
self.client.reload(new_wheel_1)
# 2.6.0
def test_create_scope(self):
# setUp
client = self.client
scope_name = "New scope (pykechain testing - remove me)"
scope_description = "This is a new scope for testing"
scope_status = ScopeStatus.ACTIVE
scope_tags = ["test_tag", "new_project_tag"]
scope_start_date = datetime.datetime(2019, 4, 12, tzinfo=pytz.UTC)
scope_due_date = datetime.datetime(2020, 4, 12, tzinfo=pytz.UTC)
scope_team = client.teams()[0]
self.temp_scope = client.create_scope(
name=scope_name,
description=scope_description,
status=scope_status,
tags=scope_tags,
start_date=scope_start_date,
due_date=scope_due_date,
team=scope_team,
)
# testing
self.assertEqual(self.temp_scope.name, scope_name)
self.assertEqual(scope_start_date, self.temp_scope.start_date)
self.assertEqual(scope_due_date, self.temp_scope.due_date)
self.assertIn(scope_tags[0], self.temp_scope.tags)
self.assertIn(scope_tags[1], self.temp_scope.tags)
self.assertEqual(scope_team, self.temp_scope.team)
def test_create_scope_with_team_name(self):
# setUp
team_name = self.client.teams()[0].name
self.temp_scope = self.client.create_scope(
name="New scope using the team name", team=team_name
)
# testing
self.assertTrue(self.temp_scope.team)
self.assertIsInstance(self.temp_scope.team, Team)
self.assertEqual(team_name, self.temp_scope.team.name)
def test_create_scope_with_team_uuid(self):
# setUp
team_id = self.client.teams()[0].id
self.temp_scope = self.client.create_scope(
name="New scope using the team ID", team=team_id
)
# testing
self.assertTrue(self.temp_scope.team)
self.assertIsInstance(self.temp_scope.team, Team)
self.assertEqual(team_id, self.temp_scope.team.id)
def test_create_scope_no_arguments(self):
# setUp
self.temp_scope = self.client.create_scope(name="New scope no arguments")
# testing
self.assertEqual(self.temp_scope.name, "New scope no arguments")
self.assertTrue(self.temp_scope._json_data["start_date"])
self.assertFalse(self.temp_scope.tags)
# noinspection PyTypeChecker
def test_create_scope_with_wrong_arguments(self):
# testing
with self.assertRaises(IllegalArgumentError):
self.client.create_scope(name=12)
with self.assertRaises(IllegalArgumentError):
self.client.create_scope(name="Failed scope", status="LIMBO")
with self.assertRaises(IllegalArgumentError):
self.client.create_scope(name="Failed scope", description=True)
with self.assertRaises(IllegalArgumentError):
self.client.create_scope(name="Failed scope", tags="One tag no list")
with self.assertRaises(IllegalArgumentError):
self.client.create_scope(name="Failed scope", tags=[12, "this", "fails"])
with self.assertRaises(IllegalArgumentError):
self.client.create_scope(name="Failed scope", team=["Fake team"])
def test_clone_scope(self):
# setUp
self.temp_scope = self.client.clone_scope(source_scope=self.project)
# testing
self.assertIsInstance(self.temp_scope, Scope)
self.assertEqual(self.temp_scope.name, f"CLONE - {self.project.name}")
self.assertEqual(self.temp_scope.status, self.project.status)
self.assertEqual(self.temp_scope.start_date, self.project.start_date)
self.assertEqual(self.temp_scope.due_date, self.project.due_date)
self.assertEqual(self.temp_scope.description, self.project.description)
self.assertListEqual(self.temp_scope.tags, self.project.tags)
def test_clone_scope_with_arguments(self):
# setUp
now = datetime.datetime.now()
name = "test clone"
status = ScopeStatus.CLOSED
description = "test description"
tags = ["one", "two"]
team = self.project.team
self.temp_scope = self.client.clone_scope(
name=name,
source_scope=self.project,
status=status,
start_date=now,
due_date=now,
description=description,
tags=tags,
team=team,
)
self.assertIsInstance(self.temp_scope, Scope)
self.assertEqual(self.temp_scope.name, name)
self.assertEqual(self.temp_scope.status, status)
self.assertEqual(self.temp_scope.start_date, now)
self.assertEqual(self.temp_scope.due_date, now)
self.assertEqual(self.temp_scope.description, description)
self.assertEqual(self.temp_scope.team, team)
self.assertListEqual(self.temp_scope.tags, tags)
def test_scope_delete(self):
new_scope = self.project.clone(asynchronous=False)
self.assertNotEqual(self.project.id, new_scope.id)
new_scope.delete(asynchronous=False)
with self.assertRaisesRegex(NotFoundError, "fit criteria"):
# throw in arbitrary sleep to give backend time to actually delete the scope.
time.sleep(1)
self.client.scope(pk=new_scope.id)
|
class TestClientLive(TestBetamax):
def setUp(self):
pass
def tearDown(self):
'''Teardown the test, remove the scope.
When you create a scope, assign it to self.temp_scope such that it is deleted when the test is complete
'''
pass
def test_login(self):
pass
def test_no_login(self):
pass
def test_get_current_user(self):
pass
def test_reload_deleted_object(self):
pass
def test_create_scope(self):
pass
def test_create_scope_with_team_name(self):
pass
def test_create_scope_with_team_uuid(self):
pass
def test_create_scope_no_arguments(self):
pass
def test_create_scope_with_wrong_arguments(self):
pass
def test_clone_scope(self):
pass
def test_clone_scope_with_arguments(self):
pass
def test_scope_delete(self):
pass
| 15 | 1 | 12 | 1 | 10 | 1 | 1 | 0.14 | 1 | 9 | 6 | 0 | 14 | 2 | 14 | 89 | 192 | 33 | 139 | 42 | 123 | 20 | 114 | 41 | 98 | 2 | 3 | 1 | 15 |
140,811 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.StatusCategory
|
class StatusCategory(Enum):
"""
Category of statuses.
:cvar UNDEFINED: Undefined status
:cvar TODO: Todo status
:cvar INPROGRESS: In progress status
:cvar DONE: Done status
"""
UNDEFINED = "UNDEFINED"
TODO = "TODO"
INPROGRESS = "INPROGRESS"
DONE = "DONE"
|
class StatusCategory(Enum):
'''
Category of statuses.
:cvar UNDEFINED: Undefined status
:cvar TODO: Todo status
:cvar INPROGRESS: In progress status
:cvar DONE: Done status
'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 14 | 2 | 5 | 5 | 4 | 7 | 5 | 5 | 4 | 0 | 1 | 0 | 0 |
140,812 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_exceptions.py
|
tests.test_exceptions.TestExceptionsLive
|
class TestExceptionsLive(TestBetamax):
def setUp(self):
super().setUp()
url = self.client._build_url("activities")
self.response = self.client._request(method="GET", url=url, params={"limit": 1})
def test_api_error_with_response(self):
api_error = APIError(response=self.response)
# testing
self.assertIsInstance(api_error.request, PreparedRequest)
self.assertEqual(self.response, api_error.response)
with self.assertRaises(APIError):
raise api_error
def test_api_error_with_argument_and_response(self):
APIError(dict(text="my dict"), response=self.response)
|
class TestExceptionsLive(TestBetamax):
def setUp(self):
pass
def test_api_error_with_response(self):
pass
def test_api_error_with_argument_and_response(self):
pass
| 4 | 0 | 5 | 0 | 4 | 0 | 1 | 0.08 | 1 | 4 | 1 | 0 | 3 | 1 | 3 | 78 | 17 | 3 | 13 | 7 | 9 | 1 | 13 | 7 | 9 | 1 | 3 | 1 | 3 |
140,813 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_forms.py
|
tests.test_forms.TestForms
|
class TestForms(TestBetamax):
"""
Test retrieval and forms attributes and methods.
"""
def setUp(self):
super().setUp()
self.cross_scope_project = self.client.scope(ref="cannondale-project")
self.workflow = self.client.workflow(
name="Simple Form Flow", category=WorkflowCategory.CATALOG
)
self.discipline_context = self.project.context(name="Discipline 1")
self.asset_context = self.project.context(name="Object 1")
self.form_model_name = "__TEST__FORM_MODEL"
self.form_model_name_2 = "__TEST__FORM_MODEL_2"
self.form_model = self.client.create_form_model(
name=self.form_model_name,
scope=self.project,
workflow=self.workflow,
category=FormCategory.MODEL,
contexts=[self.asset_context, self.discipline_context],
)
self.form_model_2 = self.project.create_form_model(
name=self.form_model_name_2,
workflow=self.workflow,
category=FormCategory.MODEL,
contexts=[self.asset_context],
)
self.form_instance = self.form_model.instantiate(name="__TEST_FORM_INSTANCE")
self.test_form_instance = None
self.cloned_form_model = None
self.form_model_for_deletion = None
self.cloned_workflow = None
def tearDown(self):
super().tearDown()
if self.form_instance:
try:
self.form_instance.delete()
except (NotFoundError, APIError):
pass
if self.test_form_instance:
try:
self.test_form_instance.delete()
except (NotFoundError, APIError):
pass
if self.form_model:
try:
self.form_model.delete()
except (NotFoundError, APIError):
pass
if self.form_model_2:
try:
self.form_model_2.delete()
except (NotFoundError, APIError):
pass
if self.form_model_for_deletion:
try:
self.form_model_for_deletion.delete()
except (NotFoundError, APIError):
pass
if self.cloned_form_model:
try:
self.cloned_form_model.delete()
except (NotFoundError, APIError):
pass
if self.cloned_workflow:
try:
self.cloned_workflow.delete()
except (NotFoundError, APIError):
pass
def test_form_attributes(self):
attributes = [
"_client",
"_json_data",
"id",
"name",
"created_at",
"updated_at",
"derived_from_id",
"ref",
"description",
"active_status",
"category",
"tags",
"form_model_root",
"form_instance_root",
"model_id",
"scope_id",
"status_forms",
]
for attr in attributes:
with self.subTest(attr):
self.assertTrue(
hasattr(self.form_model, attr),
f"Could not find '{attr}' in the form: '{self.form_model.__dict__.keys()}",
)
def test_create(self):
self.assertIsInstance(self.form_model, Form)
self.assertEqual(self.form_model.category, FormCategory.MODEL)
self.assertIsInstance(self.form_model_2, Form)
self.assertEqual(self.form_model_2.category, FormCategory.MODEL)
self.assertIsInstance(self.form_instance, Form)
self.assertEqual(self.form_instance.category, FormCategory.INSTANCE)
def test_form_instances(self):
with self.subTest("testing instances"):
form_instances = self.form_model.instances()
self.assertTrue(len(form_instances) >= 1)
form_instance = form_instances[0]
self.assertTrue(form_instance.category, FormCategory.INSTANCE)
self.assertTrue(form_instance.model_id, self.form_model.id)
with self.subTest("testing instance"):
form_instance = self.form_model.instances()[0]
self.assertTrue(form_instance.category, FormCategory.INSTANCE)
self.assertTrue(form_instance.model_id, self.form_model.id)
def test_model_form_instantiation(self):
self.test_form_instance = self.form_model.instantiate(
name="__TEST_FORM_INSTANCE"
)
self.assertTrue(self.test_form_instance.model_id, self.form_model.id)
def test_model_form_instantiation_from_client(self):
self.test_form_instance = self.client.instantiate_form(
name="___TEST_FORM_INSTANCE", model=self.form_model
)
self.assertIsInstance(self.test_form_instance, Form)
self.assertEqual(self.test_form_instance.category, FormCategory.INSTANCE)
self.assertTrue(self.test_form_instance.model_id, self.form_model.id)
def test_model_form_instantiation_from_scope(self):
self.test_form_instance = self.project.instantiate_form(
name="___TEST_FORM_INSTANCE", model=self.form_model
)
self.assertIsInstance(self.test_form_instance, Form)
self.assertEqual(self.test_form_instance.category, FormCategory.INSTANCE)
self.assertTrue(self.test_form_instance.model_id, self.form_model.id)
def test_model_form_instantiation_from_wrong_scope(self):
with self.assertRaises(IllegalArgumentError):
self.test_form_instance = self.cross_scope_project.instantiate_form(
name="___TEST_FORM_INSTANCE", model=self.form_model
)
def test_model_clone_same_scope(self):
self.cloned_form_model = self.form_model.clone(
name="__TEST_FORM_MODEL_CLONE",
target_scope=self.project,
contexts=[self.asset_context, self.discipline_context],
)
self.assertTrue(self.cloned_form_model)
self.assertIsInstance(self.cloned_form_model, Form)
self.assertEqual(self.form_model.scope_id, self.cloned_form_model.scope_id)
self.assertIn(
self.asset_context.id,
[
context["id"]
for context in self.cloned_form_model._json_data["contexts"]
],
)
self.assertIn(
self.discipline_context.id,
[
context["id"]
for context in self.cloned_form_model._json_data["contexts"]
],
)
def test_model_clone_no_target_scope(self):
self.cloned_form_model = self.form_model.clone(
name="__TEST_FORM_MODEL_CLONE",
contexts=[self.asset_context, self.discipline_context],
)
self.assertTrue(self.cloned_form_model)
self.assertIsInstance(self.cloned_form_model, Form)
self.assertEqual(self.form_model.scope_id, self.cloned_form_model.scope_id)
self.assertIn(
self.asset_context.id,
[
context["id"]
for context in self.cloned_form_model._json_data["contexts"]
],
)
self.assertIn(
self.discipline_context.id,
[
context["id"]
for context in self.cloned_form_model._json_data["contexts"]
],
)
def test_model_clone_cross_scope(self):
self.cloned_form_model = self.form_model.clone(
name="__TEST_FORM_MODEL_CLONE_CROSS_SCOPE",
target_scope=self.cross_scope_project,
contexts=[self.asset_context, self.discipline_context],
)
self.assertTrue(self.cloned_form_model)
self.assertIsInstance(self.cloned_form_model, Form)
self.assertEqual(self.cross_scope_project.id, self.cloned_form_model.scope_id)
self.assertIn(
self.asset_context.name,
[
context["name"]
for context in self.cloned_form_model._json_data["contexts"]
],
)
self.assertIn(
self.discipline_context.name,
[
context["name"]
for context in self.cloned_form_model._json_data["contexts"]
],
)
def test_form_retrieve_by_name_from_scope(self):
form = self.project.form(name=self.form_model_name)
self.assertIsInstance(form, Form)
def test_forms_retrieve_by_context_from_scope(self):
forms = self.project.forms(context=[self.asset_context])
self.assertEqual(len(forms), 2)
for form in forms:
self.assertIsInstance(form, Form)
self.assertIn(self.form_model.id, [form.id for form in forms])
self.assertIn(self.form_model_2.id, [form.id for form in forms])
def test_forms_retrieve_instances_by_model_from_scope(self):
form_instances = self.project.forms(
model=self.form_model, category=FormCategory.INSTANCE
)
self.assertTrue(len(form_instances) == 1)
form_instance = form_instances[0]
self.assertTrue(form_instance.category, FormCategory.INSTANCE)
self.assertTrue(form_instance.model_id, self.form_model.id)
def test_form_model_edit(self):
new_name = "__TEST_EDITED_FORM_MODEL"
self.form_model_2.edit(name=new_name)
self.assertEqual(self.form_model_2.name, new_name)
def test_form_model_edit_with_instances(self):
new_name = "__TEST_EDITED_FORM_MODEL"
self.form_model.edit(name=new_name)
self.assertEqual(self.form_model.name, new_name)
def test_form_instance_edit(self):
new_name = "__TEST_INSTANCE_EDITED"
self.form_instance.edit(name=new_name)
self.assertEqual(self.form_instance.name, new_name)
def test_forms_delete(self):
form_model_name = "__TEST_FORM_MODEL_FOR_DELETION"
self.form_model_for_deletion = self.client.create_form_model(
name=form_model_name,
scope=self.project,
workflow=self.workflow,
category=FormCategory.MODEL,
contexts=[self.asset_context, self.discipline_context],
)
self.assertIsInstance(self.form_model_for_deletion, Form)
self.form_model_for_deletion.delete()
with self.assertRaises(APIError, msg="Cant delete the same Form twice!"):
self.form_model_for_deletion.delete()
with self.assertRaises(NotFoundError, msg="Deleted Form cannot be found!"):
self.project.form(name=form_model_name)
def test_form_has_part_is_true(self):
part_model = self.project.model(name=self.form_model.name)
has_part_check = self.form_model.has_part(part=part_model)
self.assertTrue(has_part_check)
part_instance = part_model.instance()
has_part_check = self.form_instance.has_part(part=part_instance)
self.assertTrue(has_part_check)
def test_form_has_part_is_false(self):
part_model = self.project.model(name="Bike")
has_part_check = self.form_model.has_part(part=part_model)
self.assertFalse(has_part_check)
def test_form_has_part_wrong_inputs(self):
with self.assertRaises(IllegalArgumentError):
self.form_model.has_part(part=self.discipline_context)
def test_form_workflow_compatible_within_scope(self):
workflows = self.form_model.workflows_compatible_with_scope(scope=self.project)
self.assertEqual(len(workflows), 1)
self.cloned_workflow = self.workflow.clone(
target_scope=self.project, name="CLONED WORKFLOW"
)
workflows = self.form_model.workflows_compatible_with_scope(scope=self.project)
self.assertEqual(len(workflows), 2)
def test_form_workflow_compatible_within_scope_wrong_inputs(self):
with self.assertRaises(IllegalArgumentError):
self.form_model.workflows_compatible_with_scope(
scope=self.discipline_context
)
|
class TestForms(TestBetamax):
'''
Test retrieval and forms attributes and methods.
'''
def setUp(self):
pass
def tearDown(self):
pass
def test_form_attributes(self):
pass
def test_create(self):
pass
def test_form_instances(self):
pass
def test_model_form_instantiation(self):
pass
def test_model_form_instantiation_from_client(self):
pass
def test_model_form_instantiation_from_scope(self):
pass
def test_model_form_instantiation_from_wrong_scope(self):
pass
def test_model_clone_same_scope(self):
pass
def test_model_clone_no_target_scope(self):
pass
def test_model_clone_cross_scope(self):
pass
def test_form_retrieve_by_name_from_scope(self):
pass
def test_forms_retrieve_by_context_from_scope(self):
pass
def test_forms_retrieve_instances_by_model_from_scope(self):
pass
def test_form_model_edit(self):
pass
def test_form_model_edit_with_instances(self):
pass
def test_form_instance_edit(self):
pass
def test_forms_delete(self):
pass
def test_form_has_part_is_true(self):
pass
def test_form_has_part_is_false(self):
pass
def test_form_has_part_wrong_inputs(self):
pass
def test_form_workflow_compatible_within_scope(self):
pass
def test_form_workflow_compatible_within_scope_wrong_inputs(self):
pass
| 25 | 1 | 12 | 1 | 11 | 0 | 2 | 0.01 | 1 | 7 | 6 | 0 | 24 | 14 | 24 | 99 | 314 | 37 | 274 | 58 | 249 | 3 | 173 | 57 | 148 | 15 | 3 | 2 | 40 |
140,814 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/base.py
|
pykechain.models.base.BaseInScope
|
class BaseInScope(Base):
"""
Base model for KE-chain objects coupled to a scope.
:ivar scope_id: UUID of the Scope
:type scope_id: str
"""
def __init__(self, json, *args, **kwargs):
"""Append the scope ID to the attributes of the base object."""
super().__init__(json, *args, **kwargs)
self.scope_id: Optional[ObjectID] = json.get(
"scope_id", json.get("scope", None)
)
self._scope: Optional["Scope"] = None
@property
def scope(self):
"""
Scope this object belongs to.
This property will return a `Scope` object. It will make an additional call to the KE-chain API.
:return: the scope
:type: :class:`pykechain.models.Scope`
:raises NotFoundError: if the scope could not be found
"""
if not self._scope and self.scope_id:
self._scope = self._client.scope(pk=self.scope_id, status=None)
return self._scope
|
class BaseInScope(Base):
'''
Base model for KE-chain objects coupled to a scope.
:ivar scope_id: UUID of the Scope
:type scope_id: str
'''
def __init__(self, json, *args, **kwargs):
'''Append the scope ID to the attributes of the base object.'''
pass
@property
def scope(self):
'''
Scope this object belongs to.
This property will return a `Scope` object. It will make an additional call to the KE-chain API.
:return: the scope
:type: :class:`pykechain.models.Scope`
:raises NotFoundError: if the scope could not be found
'''
pass
| 4 | 3 | 11 | 2 | 5 | 4 | 2 | 1.08 | 1 | 1 | 0 | 10 | 2 | 2 | 2 | 7 | 31 | 6 | 12 | 6 | 8 | 13 | 9 | 5 | 6 | 2 | 1 | 1 | 3 |
140,815 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/base.py
|
pykechain.models.base.Base
|
class Base:
"""Base model connecting retrieved data to a KE-chain client.
:ivar id: The UUID of the object (corresponds with the UUID in KE-chain).
:type id: str
:ivar name: The name of the object.
:type name: basestring
:ivar created_at: the datetime when the object was created if available (otherwise None)
:type created_at: datetime or None
:ivar updated_at: the datetime when the object was last updated if available (otherwise None)
:type updated_at: datetime or None
"""
def __init__(self, json: Dict, client: "Client"):
"""Construct a model from provided json data."""
self._json_data = json
self._client: "Client" = check_client(client)
self.id = json.get("id")
self.name = json.get("name")
self.ref = json.get("ref")
self.created_at = parse_datetime(json.get("created_at"))
self.updated_at = parse_datetime(json.get("updated_at"))
def __repr__(self): # pragma: no cover
return f"<pyke {self.__class__.__name__} '{self.name}' id {self.id[-8:]}>"
def __eq__(self, other): # pragma: no cover
if hasattr(self, "id") and hasattr(other, "id"):
return self.id == other.id
else:
return super().__eq__(other)
def __hash__(self):
return hash(self.id)
def refresh(
self,
json: Optional[Dict] = None,
url: Optional[str] = None,
extra_params: Optional[Dict] = None,
):
"""Refresh the object in place.
Can be called on the object without any arguments and should refresh the object inplace. If you want to
use it in an advance way, you may call it with a json response from the server or provide the url to
refetch the object from the server if the url cant be determined from the object itself.
It is using the `Client.reload()` function to re-retrieve the object in a backend API call.
:param json: (optional) json dictionary from a response from the server, will re-init object
:type json: None or dict
:param url: (optional) url to retrieve the object again, typically an identity url api/<service>/id
:type url: None or basestring
:param extra_params: (optional) additional paramenters (query params) for the request eg dict(fields='__all__')
:type extra_params: None or dict
"""
if json and isinstance(json, dict):
self.__init__(json=json, client=self._client)
else:
src = self._client.reload(self, url=url, extra_params=extra_params)
self.__dict__.update(src.__dict__)
|
class Base:
'''Base model connecting retrieved data to a KE-chain client.
:ivar id: The UUID of the object (corresponds with the UUID in KE-chain).
:type id: str
:ivar name: The name of the object.
:type name: basestring
:ivar created_at: the datetime when the object was created if available (otherwise None)
:type created_at: datetime or None
:ivar updated_at: the datetime when the object was last updated if available (otherwise None)
:type updated_at: datetime or None
'''
def __init__(self, json: Dict, client: "Client"):
'''Construct a model from provided json data.'''
pass
def __repr__(self):
pass
def __eq__(self, other):
pass
def __hash__(self):
pass
def refresh(
self,
json: Optional[Dict] = None,
url: Optional[str] = None,
extra_params: Optional[Dict] = None,
):
'''Refresh the object in place.
Can be called on the object without any arguments and should refresh the object inplace. If you want to
use it in an advance way, you may call it with a json response from the server or provide the url to
refetch the object from the server if the url cant be determined from the object itself.
It is using the `Client.reload()` function to re-retrieve the object in a backend API call.
:param json: (optional) json dictionary from a response from the server, will re-init object
:type json: None or dict
:param url: (optional) url to retrieve the object again, typically an identity url api/<service>/id
:type url: None or basestring
:param extra_params: (optional) additional paramenters (query params) for the request eg dict(fields='__all__')
:type extra_params: None or dict
'''
pass
| 6 | 3 | 9 | 1 | 6 | 3 | 1 | 0.86 | 0 | 3 | 0 | 6 | 5 | 7 | 5 | 5 | 62 | 10 | 29 | 19 | 18 | 25 | 22 | 14 | 16 | 2 | 0 | 1 | 7 |
140,816 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.WidgetNames
|
class WidgetNames(Enum):
"""The various Names of the Widget that can be configured.
:cvar SUPERGRIDWIDGET: superGridWidget
:cvar PROPERTYGRIDWIDGET: propertyGridWidget
:cvar HTMLWIDGET: htmlWidget
:cvar MARKDOWNWIDGET: markdownWidget
:cvar FILTEREDGRIDWIDGET: filteredGridWidget
:cvar SERVICEWIDGET: serviceWidget
:cvar NOTEBOOKWIDGET: notebookWidget
:cvar ATTACHMENTVIEWERWIDGET: attachmentViewerWidget
:cvar MULTIATTACHMENTVIEWERWIDGET: multiAttachmentViewerWidget
:cvar TASKNAVIGATIONBARWIDGET: taskNavigationBarWidget
:cvar JSONWIDGET: jsonWidget
# KE-chain 3 only
:cvar SIGNATUREWIDGET: signatureWidget
:cvar CARDWIDGET: cardWidget
:cvar METAPANELWIDGET: metaPanelWidget
:cvar FORMMETAPANEL: formMetaPanelWidget
:cvar MULTICOLUMNWIDGET: multiColumnWidget
:cvar PROGRESSWIDGET: progressWidget
:cvar TASKSWIDGET: tasksWidget
:cvar SERVICECARDWIDGET: serviceCardWidget
:cvar DASHBOARDWIDGET: 'dashboardWidget'
:cvar SCOPEMEMBERS: 'scopeMembersWidget'
"""
SUPERGRIDWIDGET = "superGridWidget"
PROPERTYGRIDWIDGET = "propertyGridWidget"
HTMLWIDGET = "htmlWidget"
MARKDOWNWIDGET = "markdownWidget"
FILTEREDGRIDWIDGET = "filteredGridWidget"
SERVICEWIDGET = "serviceWidget"
NOTEBOOKWIDGET = "notebookWidget"
ATTACHMENTVIEWERWIDGET = "attachmentViewerWidget"
MULTIATTACHMENTVIEWERWIDGET = "multiAttachmentViewerWidget"
TASKNAVIGATIONBARWIDGET = "taskNavigationBarWidget"
JSONWIDGET = "jsonWidget"
METAPANELWIDGET = "metaPanelWidget"
FORMMETAPANELWIDGET = "formMetaPanelWidget"
MULTICOLUMNWIDGET = "multiColumnWidget"
SIGNATUREWIDGET = "signatureWidget"
CARDWIDGET = "cardWidget"
PROGRESSWIDGET = "progressWidget"
TASKSWIDGET = "taskWidget"
SERVICECARDWIDGET = "serviceCardWidget"
DASHBOARDWIDGET = "dashboardWidget"
SCOPEMEMBERS = "scopeMembersWidget"
PROJECTINFO = "projectInfoWidget"
|
class WidgetNames(Enum):
'''The various Names of the Widget that can be configured.
:cvar SUPERGRIDWIDGET: superGridWidget
:cvar PROPERTYGRIDWIDGET: propertyGridWidget
:cvar HTMLWIDGET: htmlWidget
:cvar MARKDOWNWIDGET: markdownWidget
:cvar FILTEREDGRIDWIDGET: filteredGridWidget
:cvar SERVICEWIDGET: serviceWidget
:cvar NOTEBOOKWIDGET: notebookWidget
:cvar ATTACHMENTVIEWERWIDGET: attachmentViewerWidget
:cvar MULTIATTACHMENTVIEWERWIDGET: multiAttachmentViewerWidget
:cvar TASKNAVIGATIONBARWIDGET: taskNavigationBarWidget
:cvar JSONWIDGET: jsonWidget
# KE-chain 3 only
:cvar SIGNATUREWIDGET: signatureWidget
:cvar CARDWIDGET: cardWidget
:cvar METAPANELWIDGET: metaPanelWidget
:cvar FORMMETAPANEL: formMetaPanelWidget
:cvar MULTICOLUMNWIDGET: multiColumnWidget
:cvar PROGRESSWIDGET: progressWidget
:cvar TASKSWIDGET: tasksWidget
:cvar SERVICECARDWIDGET: serviceCardWidget
:cvar DASHBOARDWIDGET: 'dashboardWidget'
:cvar SCOPEMEMBERS: 'scopeMembersWidget'
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.04 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 50 | 3 | 23 | 23 | 22 | 24 | 23 | 23 | 22 | 0 | 1 | 0 | 0 |
140,817 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.WidgetTitleValue
|
class WidgetTitleValue(Enum):
"""
Options to configure the title of a widget.
:cvar DEFAULT: Use the default title of the widget type.
:cvar NO_TITLE: Show no title.
:cvar CUSTOM_TITLE: Show a custom title text.
"""
DEFAULT = "Default"
NO_TITLE = "No title"
CUSTOM_TITLE = "Custom title"
|
class WidgetTitleValue(Enum):
'''
Options to configure the title of a widget.
:cvar DEFAULT: Use the default title of the widget type.
:cvar NO_TITLE: Show no title.
:cvar CUSTOM_TITLE: Show a custom title text.
'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 12 | 2 | 4 | 4 | 3 | 6 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
140,818 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.WidgetTypes
|
class WidgetTypes(Enum):
"""The various widget types for the widget definitions available to the widget api.
.. versionchanged:: 3.14
Added FORMMETAPANEL for KE-chain versions >= v2021.10
:cvar UNDEFINED: Undefined Widget
:cvar PROPERTYGRID: Propertygrid widget
:cvar SUPERGRID: Supergrid widget
:cvar HTML: Html widget
:cvar MARKDOWN: Markdown widget
:cvar FILTEREDGRID: Filteredgrid widget
:cvar SERVICE: Service widget
:cvar NOTEBOOK: Notebook widget
:cvar ATTACHMENTVIEWER: Attachmentviewer widget
:cvar MULTIATTACHMENTVIEWER: MultiAttachmentviewer widget
:cvar TASKNAVIGATIONBAR: Tasknavigationbar widget
:cvar JSON: Json widget
:cvar METAPANEL: Metapanel widget
:cvar FORMMETAPANEL: The FormMetapanel widget
:cvar MULTICOLUMN: Multicolumn widget
:cvar SCOPE: Scope widget
:cvar THIRDPARTY: Thirdparty widget
:cvar PROGRESS: Progress widget
:cvar SIGNATURE: Signature widget
:cvar CARD: Card widget
:cvar TASKS: Tasks widget
:cvar WEATHER: Weather widget
:cvar SERVICECARD: Servicecard widget
:cvar DASHBOARD: Dashboard widget
:cvar SCOPEMEMBERS: Scopemembers widget
"""
UNDEFINED = "UNDEFINED"
PROPERTYGRID = "PROPERTYGRID"
SUPERGRID = "SUPERGRID"
HTML = "HTML"
MARKDOWN = "MARKDOWN"
FILTEREDGRID = "FILTEREDGRID"
SERVICE = "SERVICE"
NOTEBOOK = "NOTEBOOK"
ATTACHMENTVIEWER = "ATTACHMENTVIEWER"
MULTIATTACHMENTVIEWER = "MULTIATTACHMENTVIEWER"
TASKNAVIGATIONBAR = "TASKNAVIGATIONBAR"
JSON = "JSON"
METAPANEL = "METAPANEL"
FORMMETAPANEL = "FORMMETAPANEL"
MULTICOLUMN = "MULTICOLUMN"
SCOPE = "SCOPE"
THIRDPARTY = "THIRDPARTY"
PROGRESS = "PROGRESS"
SIGNATURE = "SIGNATURE"
CARD = "CARD"
TASKS = "TASKS"
WEATHER = "WEATHER"
SERVICECARD = "SERVICECARD"
DASHBOARD = "DASHBOARD"
SCOPEMEMBERS = "SCOPEMEMBERS"
PROJECTINFO = "PROJECTINFO"
|
class WidgetTypes(Enum):
'''The various widget types for the widget definitions available to the widget api.
.. versionchanged:: 3.14
Added FORMMETAPANEL for KE-chain versions >= v2021.10
:cvar UNDEFINED: Undefined Widget
:cvar PROPERTYGRID: Propertygrid widget
:cvar SUPERGRID: Supergrid widget
:cvar HTML: Html widget
:cvar MARKDOWN: Markdown widget
:cvar FILTEREDGRID: Filteredgrid widget
:cvar SERVICE: Service widget
:cvar NOTEBOOK: Notebook widget
:cvar ATTACHMENTVIEWER: Attachmentviewer widget
:cvar MULTIATTACHMENTVIEWER: MultiAttachmentviewer widget
:cvar TASKNAVIGATIONBAR: Tasknavigationbar widget
:cvar JSON: Json widget
:cvar METAPANEL: Metapanel widget
:cvar FORMMETAPANEL: The FormMetapanel widget
:cvar MULTICOLUMN: Multicolumn widget
:cvar SCOPE: Scope widget
:cvar THIRDPARTY: Thirdparty widget
:cvar PROGRESS: Progress widget
:cvar SIGNATURE: Signature widget
:cvar CARD: Card widget
:cvar TASKS: Tasks widget
:cvar WEATHER: Weather widget
:cvar SERVICECARD: Servicecard widget
:cvar DASHBOARD: Dashboard widget
:cvar SCOPEMEMBERS: Scopemembers widget
'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.07 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 59 | 3 | 27 | 27 | 26 | 29 | 27 | 27 | 26 | 0 | 1 | 0 | 0 |
140,819 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums.WorkflowCategory
|
class WorkflowCategory(Enum):
"""
Options for the Category of a Workflow.
:cvar CATALOG: Catalog Workflow (immutable)
:cvar DEFINED: Defined Workflow belonging to a scope
"""
CATALOG = "CATALOG"
DEFINED = "DEFINED"
|
class WorkflowCategory(Enum):
'''
Options for the Category of a Workflow.
:cvar CATALOG: Catalog Workflow (immutable)
:cvar DEFINED: Defined Workflow belonging to a scope
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 10 | 2 | 3 | 3 | 2 | 5 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
140,820 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/enums.py
|
pykechain.enums._AllRepresentations
|
class _AllRepresentations(PropertyRepresentation, OtherRepresentations):
pass
|
class _AllRepresentations(PropertyRepresentation, OtherRepresentations):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
140,821 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.APIError
|
class APIError(Exception):
"""A general KE-chain API Error occurred.
A end-user descriptive message is required.
:ivar response: response object
:ivar request: request object that precedes the response
:ivar msg: error message in the response
:ivar traceback: traceback in the response (from the KE-chain server)
:ivar detail: details of the error
"""
def __init__(self, *args, **kwargs):
"""Initialise the `APIError` with `response`, `request`, `msg`, `traceback` and `detail`.
:param response:
:param kwargs:
"""
self.response = kwargs.pop("response", None)
if hasattr(self.response, "request"):
self.request = self.response.request
else:
self.request = kwargs.pop("request", None)
self.msg, self.traceback, self.detail = None, None, None
if args:
arg = args[0]
context = [arg if isinstance(arg, str) else arg.__repr__()]
else:
context = [
"Error in request to the server."
] # Default message if `APIError()`, without inputs, is used.
import json
if self.response is not None and isinstance(self.response, Response):
try:
response_json = self.response.json()
except json.decoder.JSONDecodeError:
response_json = None
if response_json:
self.msg = response_json.get("msg")
self.traceback = response_json.get(
"traceback", "provided no traceback."
)
self.detail = response_json.get("detail")
self.results = response_json.get("results")
else:
self.traceback = self.response.text
self.msg = self.traceback.split(r"\n"[-1])
self.detail = None
self.results = None
context.extend(
[
f"Server {self.traceback}",
f"Results:\n{json.dumps(self.results, indent=4)}",
f"Detail: {self.detail}",
f"Elapsed: {self.response.elapsed}",
]
)
if self.request is not None and isinstance(self.request, PreparedRequest):
context.extend(
[
f"Request URL: {self.request.url}",
f"Request method: {self.request.method}",
]
)
if self.request.body:
try:
decoded_body = self.request.body.decode(
"UTF-8"
) # Convert byte-string to string
except AttributeError:
decoded_body = (
self.request.body
) # strings (e.g. from testing cassettes) cant be decoded
try:
body = json.loads(
decoded_body
) # Convert string to Python object(s)
except json.decoder.JSONDecodeError:
body = decoded_body.split("&") # parameters in URL
context.append(
f"Request data:\n{json.dumps(body, indent=4)}"
) # pretty printing of a json
message = "\n".join(context)
new_args = [message]
super().__init__(*new_args)
|
class APIError(Exception):
'''A general KE-chain API Error occurred.
A end-user descriptive message is required.
:ivar response: response object
:ivar request: request object that precedes the response
:ivar msg: error message in the response
:ivar traceback: traceback in the response (from the KE-chain server)
:ivar detail: details of the error
'''
def __init__(self, *args, **kwargs):
'''Initialise the `APIError` with `response`, `request`, `msg`, `traceback` and `detail`.
:param response:
:param kwargs:
'''
pass
| 2 | 2 | 83 | 11 | 68 | 10 | 11 | 0.26 | 1 | 5 | 0 | 5 | 1 | 6 | 1 | 11 | 95 | 14 | 69 | 14 | 66 | 18 | 42 | 14 | 39 | 11 | 3 | 3 | 11 |
140,822 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.ClientError
|
class ClientError(APIError):
"""When instantiating the Client an Error occurred."""
pass
|
class ClientError(APIError):
'''When instantiating the Client an Error occurred.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
140,823 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.ForbiddenError
|
class ForbiddenError(APIError):
"""A login is required."""
pass
|
class ForbiddenError(APIError):
'''A login is required.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
140,824 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_activities.py
|
tests.test_activities.TestActivityConstruction
|
class TestActivityConstruction(TestBetamax):
def setUp(self):
super().setUp()
self.process = self.project.create_activity(
name="__Test process",
activity_type=ActivityType.PROCESS,
)
self.task = None
def tearDown(self):
for activity in [self.task, self.process]:
if activity:
try:
activity.delete()
except APIError:
pass
super().tearDown()
def test_create_with_inputs(self):
name = "Testing task"
ref = slugify_ref(name)
description = "My new task"
status = ActivityStatus.OPEN
activity_type = ActivityType.TASK
classification = ActivityClassification.WORKFLOW
# setUp
self.task = self.client.create_activity(
name=name,
ref=ref,
parent=self.process,
status=status,
description=description,
start_date=self.time,
due_date=self.time,
activity_type=activity_type,
classification=classification,
activity_options=dict(
representations=[
CustomIconRepresentation(value="pennant").as_json(),
],
),
)
# testing
self.assertIsInstance(self.task, Activity)
self.assertEqual(name, self.task.name)
self.assertEqual(ref, self.task.ref)
self.assertEqual(status, self.task.status)
self.assertTrue(description, self.task.description)
self.assertIsInstance(self.task.start_date, datetime)
self.assertIsInstance(self.task.due_date, datetime)
self.assertEqual(activity_type, self.task.activity_type)
self.assertEqual(classification, self.task.classification)
def test_create_on_scope(self):
self.task = self.project.create_activity("__Test task")
self.assertIsInstance(self.task, Activity)
self.assertEqual(ActivityType.TASK, self.task.activity_type)
self.assertEqual(ActivityClassification.WORKFLOW, self.task.classification)
def test_create_below_parent(self):
self.process.children() # populate `_cached_children`.
self.assertIsNotNone(
self.process._cached_children, "Cached children should be an (empty) list."
)
new_task = self.process.create(
name="__Testing task",
activity_type=ActivityType.TASK,
)
current_children = self.process.children()
self.assertTrue(current_children)
self.assertIn(
new_task,
current_children,
msg="New child task should be among the children.",
)
def test_create_with_classification(self):
for classification in ActivityClassification.values():
with self.subTest(msg=f"Classification: {classification}"):
# setUp 1
root_name = activity_root_name_by_classification[classification]
root = self.project.activity(name=root_name)
# testing 1
self.assertEqual(classification, root.classification)
self.assertEqual(ActivityType.PROCESS, root.activity_type)
# setUp 2
task = self.client.create_activity(
parent=root,
name=f"{classification}",
classification=classification,
)
# testing 2
self.assertEqual(classification, task.classification)
# tearDown
task.delete()
def test_create_with_incorrect_classification(self):
with self.assertRaises(IllegalArgumentError):
self.project.create_activity(
name="Impossible classification",
classification="Gummy bears",
)
def test_create_with_incorrect_parent(self):
with self.assertRaises(IllegalArgumentError):
self.client.create_activity(
name="Impossible parent",
parent="Darth vader",
)
def test_create_with_task_as_parent(self):
task = self.process.create(name="__Test task")
with self.assertRaises(
IllegalArgumentError, msg="Tasks cannot be created below other tasks!"
):
task.create("This cannot happen")
def test_create_with_incorrect_inputs(self):
with self.assertRaises(IllegalArgumentError):
self.project.create_activity("__test_task", status="COMPLETE")
with self.assertRaises(IllegalArgumentError):
self.project.create_activity("__test_task", start_date=4)
with self.assertRaises(IllegalArgumentError):
self.project.create_activity("__test_task", description=1234)
with self.assertRaises(IllegalArgumentError):
self.project.create_activity("__test_task", classification="PRODUCT")
def test_delete(self):
# setUp
sub_process_name = "__Test subprocess"
sub_task_name = "__Test subtask"
subprocess = self.process.create(
name=sub_process_name, activity_type=ActivityType.PROCESS
)
self.task = subprocess.create(name=sub_task_name)
subprocess.delete()
# testing
with self.assertRaises(APIError, msg="Cant delete the same Activity twice!"):
subprocess.delete()
with self.assertRaises(NotFoundError, msg="Deleted Activity cant be found!"):
self.project.activity(name=sub_process_name)
with self.assertRaises(
NotFoundError, msg="Children of deleted Activities cant be found!"
):
self.project.activity(name=sub_task_name)
|
class TestActivityConstruction(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test_create_with_inputs(self):
pass
def test_create_on_scope(self):
pass
def test_create_below_parent(self):
pass
def test_create_with_classification(self):
pass
def test_create_with_incorrect_classification(self):
pass
def test_create_with_incorrect_parent(self):
pass
def test_create_with_task_as_parent(self):
pass
def test_create_with_incorrect_inputs(self):
pass
def test_delete(self):
pass
| 12 | 0 | 14 | 1 | 11 | 1 | 1 | 0.08 | 1 | 10 | 7 | 0 | 11 | 3 | 11 | 86 | 161 | 26 | 126 | 32 | 114 | 10 | 83 | 31 | 71 | 4 | 3 | 3 | 15 |
140,825 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.IllegalArgumentError
|
class IllegalArgumentError(ValueError):
"""Illegal arguments where provided."""
pass
|
class IllegalArgumentError(ValueError):
'''Illegal arguments where provided.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
140,826 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.MultipleFoundError
|
class MultipleFoundError(APIError):
"""Multiple objects are found, while a single object is requested."""
pass
|
class MultipleFoundError(APIError):
'''Multiple objects are found, while a single object is requested.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
140,827 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.NotFoundError
|
class NotFoundError(APIError):
"""No object is found."""
pass
|
class NotFoundError(APIError):
'''No object is found.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
140,828 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.PDFDownloadTimeoutError
|
class PDFDownloadTimeoutError(APIError):
"""Error downloading the PDF because of a timeouterror."""
pass
|
class PDFDownloadTimeoutError(APIError):
'''Error downloading the PDF because of a timeouterror.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
140,829 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions._DeprecationMixin
|
class _DeprecationMixin:
__notified = False
def __new__(cls, *args, **kwargs):
if not cls.__notified:
warnings.warn(
f"`{cls.__name__}` is a wrapping class for `{str(cls.__name__)[:-1]}`. "
f"`{cls.__name__}` will be deprecated in July 2022.",
PendingDeprecationWarning,
)
cls.__notified = True
return super().__new__(cls)
|
class _DeprecationMixin:
def __new__(cls, *args, **kwargs):
pass
| 2 | 0 | 10 | 1 | 9 | 0 | 2 | 0 | 0 | 3 | 0 | 10 | 1 | 0 | 1 | 1 | 13 | 2 | 11 | 3 | 9 | 0 | 7 | 3 | 5 | 2 | 0 | 1 | 2 |
140,830 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/activity.py
|
pykechain.models.activity.Activity
|
class Activity(TreeObject, TagsMixin):
"""A virtual object representing a KE-chain activity.
.. versionadded:: 2.0
:ivar id: id of the activity
:type id: uuid
:ivar name: name of the activity
:type name: basestring
:ivar created_at: created datetime of the activity
:type created_at: datetime
:ivar updated_at: updated datetime of the activity
:type updated_at: datetime
:ivar description: description of the activity
:type description: basestring
:ivar status: status of the activity. One of :class:`pykechain.enums.ActivityStatus`
:type status: basestring
:ivar classification: classification of the activity. One of :class:
`pykechain.enums.ActivityClassification`
:type classification: basestring
:ivar activity_type: Type of the activity. One of :class:`pykechain.enums.ActivityType`
for WIM version 2
:type activity_type: basestring
"""
def __init__(self, json, **kwargs):
"""Construct an Activity from a json object."""
super().__init__(json, **kwargs)
self._scope_id = json.get("scope_id")
self.ref: str = json.get("ref")
self.description: str = json.get("description", "")
self.status: ActivityStatus = json.get("status")
self.classification: ActivityClassification = json.get("classification")
self.activity_type: ActivityType = json.get("activity_type")
self.start_date = parse_datetime(json.get("start_date"))
self.due_date = parse_datetime(json.get("due_date"))
self.assignees_ids: List[str] = json.get("assignees_ids", [])
self._options = json.get("activity_options", {})
self._form_collection = json.get("form_collection")
self._tags: List[str] = json.get("tags", [])
self._representations_container = RepresentationsComponent(
self,
self._options.get("representations", {}),
self._save_representations,
)
self._widgets_manager: Optional[WidgetsManager] = None
def __call__(self, *args, **kwargs) -> "Activity":
"""Short-hand version of the `child` method."""
return self.child(*args, **kwargs)
def refresh(self, *args, **kwargs):
"""Refresh the object in place."""
super().refresh(
url=self._client._build_url("activity", activity_id=self.id),
extra_params=API_EXTRA_PARAMS["activity"],
*args,
**kwargs,
)
#
# additional properties
#
@property
def assignees(self) -> List["User"]:
"""List of assignees to the activity.
Provides a list of `User` objects or an empty list.
:return: a list of `User` objects or an empty list.
:rtype: list
"""
return (
self._client.users(id__in=self.assignees_ids, is_hidden=False)
if self.assignees_ids
else []
)
@property
def scope_id(self):
"""
Id of the scope this Activity belongs to.
This property will always produce a scope_id, even when the scope object was not included
in an earlier response.
When the :class:`Scope` is not included in this task, it will make an additional call to
the KE-chain API.
:return: the scope id
:type: uuid
:raises NotFoundError: if the scope could not be found
"""
if self._scope_id is None:
self.refresh()
if self._scope_id is None:
raise NotFoundError(f"Activity '{self}' has no related scope!")
return self._scope_id
@scope_id.setter
def scope_id(self, value):
self._scope_id = value
@property
def representations(self):
"""Get and set the activity representations."""
return self._representations_container.get_representations()
@representations.setter
def representations(self, value):
self._representations_container.set_representations(value)
def _save_representations(self, representation_options):
self._options.update({"representations": representation_options})
self.edit(activity_options=self._options)
#
# predicates
#
def is_rootlevel(self) -> bool:
"""
Activity is at the toplevel of a project, i.e. below the root itself.
It will look for the name of the parent which should be either
ActivityRootNames.WORKFLOW_ROOT or ActivityRootNames.CATALOG_ROOT. If the name of the
parent cannot be found an additional API call is made to retrieve the parent object (
based on the `parent_id` in the json_data).
:return: Return True if it is a root level activity, otherwise return False
"""
# when the activity itself is a root, than return False immediately
if self.is_root():
return False
parent_name = None
parent_dict = self._json_data.get("parent_id_name")
if parent_dict and "name" in parent_dict:
parent_name = parent_dict.get("name")
if not parent_dict:
parent_name = self._client.activity(id=self.parent_id).name
return parent_name in ActivityRootNames.values()
def is_task(self) -> bool:
"""
Activity is of ActivityType.TASK.
:return: Return True if it is a task, otherwise return False
"""
return self.activity_type == ActivityType.TASK
def is_subprocess(self) -> bool:
"""
Activity is of ActivityType.PROCESS.
:return: Return True if it is a subprocess, otherwise return False
"""
return self.is_process()
def is_process(self) -> bool:
"""
Activity is of ActivityType.PROCESS.
:return: Return True if it is a process, otherwise return False
"""
return self.activity_type == ActivityType.PROCESS
def is_workflow(self) -> bool:
"""
Classification of the Activity is of ActivityClassification.WORKFLOW.
:return: Return True if it is a workflow classification activity, otherwise return False
"""
return self.classification == ActivityClassification.WORKFLOW
def is_app(self) -> bool:
"""
Classification of the Activity is of ActivityClassification.APP.
:return: Return True if it is a App classification activity, otherwise return False
"""
return self.classification == ActivityClassification.APP
def is_catalog(self) -> bool:
"""
Classification of the Activity is of ActivityClassification.CATALOG.
:return: Return True if it is a catalog classification activity, otherwise return False
"""
return self.classification == ActivityClassification.CATALOG
def is_workflow_root(self) -> bool:
"""
Classification of the Activity is of ActivityClassification.WORKFLOW and a ROOT object.
:return: Return True if it is a root workflow classification activity, otherwise False
"""
return self.is_root() and self.is_workflow()
def is_catalog_root(self) -> bool:
"""
Classification of the Activity is of ActivityClassification.CATALOG and a ROOT object.
:return: Return True if it is a root catalog classification activity, otherwise False
"""
return self.is_root() and self.is_catalog()
def is_root(self) -> bool:
"""
Activity is a ROOT object.
If you want to determine if it is also a workflow or a catalog root,
use :func:`Activity.is_workflow_root()` or :func:`Activity.is_catalog_root()` methods.
:return: Return True if it is a root object, otherwise return False
"""
return self.name in ActivityRootNames.values() and self.parent_id is None
def is_configured(self) -> bool:
"""
Activity is configured with input and output properties.
Makes an additional lightweight call to the API to determine if any associated models
are there.
:return: Return True if it is configured, otherwise return False
"""
# check configured based on if we get at least 1 part back
return bool(self.parts(category=Category.MODEL, limit=1))
def is_customized(self) -> bool:
"""
Activity is customized.
In other words if it has a customization. Use can use the :func:`Activity.customization()`
to retrieve the customization object and configure the task.
:return: Return True if it is customized, otherwise return False
"""
return bool(self._json_data.get("customization", False))
#
# methods
#
def create(self, *args, **kwargs) -> "Activity":
"""Create a new activity belonging to this subprocess.
See :func:`pykechain.Client.create_activity` for available parameters.
:raises IllegalArgumentError: if the `Activity` is not a `PROCESS`.
:raises APIError: if an Error occurs.
"""
if self.activity_type != ActivityType.PROCESS:
raise IllegalArgumentError("One can only create a task under a subprocess.")
return self._client.create_activity(self, *args, **kwargs)
def parent(self) -> "Activity":
"""Retrieve the parent in which this activity is defined.
If this is a task on top level, it raises NotFounderror.
:return: a :class:`Activity`
:raises NotFoundError: when it is a task in the top level of a project
:raises APIError: when other error occurs
Example
-------
>>> task = project.activity('Subtask')
>>> parent_of_task = task.parent()
"""
if self.parent_id is None:
raise NotFoundError(
f"Cannot find parent for task '{self}', as this task exist on top level."
)
elif self._parent is None:
self._parent = self._client.activity(pk=self.parent_id, scope=self.scope_id)
return self._parent
def children(self, **kwargs) -> List["Activity"]:
"""Retrieve the direct activities of this subprocess.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the direct
descending level. Only when the activity is a Subprocess, otherwise it raises a
NotFoundError
:param kwargs: Additional search arguments, check :func:`pykechain.Client.activities`
for additional info
:return: a list of :class:`Activity`
:raises NotFoundError: when this task is not of type `ActivityType.PROCESS`
Example
-------
>>> task = project.activity('Subprocess')
>>> children = task.children()
Example searching for children of a subprocess which contains a name (icontains searches
case insensitive)
>>> task = project.activity('Subprocess')
>>> children = task.children(name__icontains='more work')
"""
if self.activity_type != ActivityType.PROCESS:
raise NotFoundError(
"Only subprocesses can have children, please choose a subprocess instead of a '{}'"
" (activity '{}')".format(self.activity_type, self.name)
)
if not kwargs:
if self._cached_children is None:
self._cached_children = self._client.activities(
parent_id=self.id, scope=self.scope_id, **kwargs
)
for child in self._cached_children:
child._parent = self
return self._cached_children
else:
return self._client.activities(
parent_id=self.id, scope=self.scope_id, **kwargs
)
def child(
self, name: Optional[str] = None, pk: Optional[str] = None, **kwargs
) -> "Activity":
"""
Retrieve a child object.
:param name: optional, name of the child
:type name: str
:param pk: optional, UUID of the child
:type: pk: str
:return: Child object
:raises MultipleFoundError: whenever multiple children fit match inputs.
:raises NotFoundError: whenever no child matching the inputs could be found.
"""
if not (name or pk):
raise IllegalArgumentError('You need to provide either "name" or "pk".')
if self._cached_children:
# First try to find the child without calling KE-chain.
if name:
activity_list = [c for c in self.children() if c.name == name]
else:
activity_list = [c for c in self.children() if c.id == pk]
else:
activity_list = []
if not activity_list:
if name:
activity_list = self.children(name=name)
else:
activity_list = self.children(pk=pk)
criteria = f"\nname: {name}\npk: {pk}\nkwargs: {kwargs}"
if len(activity_list) == 1:
child = activity_list[0]
elif len(activity_list) > 1:
raise MultipleFoundError(
f"{self} has more than one matching child.{criteria}"
)
else:
raise NotFoundError(f"{self} has no matching child.{criteria}")
return child
def siblings(self, **kwargs) -> List["Activity"]:
"""Retrieve the other activities that also belong to the parent.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the level of the
current task, including itself. This also works if the activity is of type
`ActivityType.PROCESS`.
:param kwargs: Additional search arguments, check :func:`pykechain.Client.activities`
for additional info
:return: list of :class:`Activity`
:raises NotFoundError: when it is a task in the top level of a project
Example
-------
>>> task = project.activity('Some Task')
>>> siblings = task.siblings()
Example for siblings containing certain words in the task name
>>> task = project.activity('Some Task')
>>> siblings = task.siblings(name__contains='Another Task')
"""
if self.parent_id is None:
raise NotFoundError(
f"Cannot find siblings for task '{self}', as this task exist on top level."
)
return self._client.activities(
parent_id=self.parent_id, scope=self.scope_id, **kwargs
)
def all_children(self) -> List["Activity"]:
"""
Retrieve a flat list of all descendants, sorted depth-first.
Returns an empty list for Activities of type TASK.
:returns list of child objects
:rtype List
"""
if self.activity_type == ActivityType.TASK:
return []
return super().all_children()
def count_children(self, **kwargs) -> int:
"""
Retrieve the number of child activities using a light-weight request.
:return: number of Activities
:rtype int
"""
if self.activity_type != ActivityType.PROCESS:
raise IllegalArgumentError(
"You can only count the number of children of an Activity of type"
f" {ActivityType.PROCESS}"
)
return super().count_children(method="activities", **kwargs)
def clone(
self,
parent: Optional[Union["Activity", str]] = None,
update_dict: Optional[Dict] = None,
**kwargs,
) -> Optional["Activity"]:
"""
Create a copy of this activity.
:param parent: (O) parent Activity object or UUID
:type parent: Activity
:param update_dict: (O) dictionary of new values to set on the cloned activities,
e.g. `{"name": "New name"}`
:type update_dict: dict
:param kwargs: additional arguments, see the `Client.clone_activities()` method
:return: clone of this activity
:rtype Activity
"""
update_dict = check_type(update_dict, dict, "update_dict")
if update_dict:
validated_dict = self._validate_edit_arguments({}, **update_dict)
else:
validated_dict = None
cloned_activities = self._client.clone_activities(
activity_parent=check_base(parent, Activity, "parent") or self.parent_id,
activities=[self],
activity_update_dicts={self.id: validated_dict} if validated_dict else None,
**kwargs,
)
return cloned_activities[0] if cloned_activities else None
def edit_cascade_down(
self,
start_date: Optional[Union[datetime.datetime, Empty]] = empty,
due_date: Optional[Union[datetime.datetime, Empty]] = empty,
assignees: Optional[Union[List[str], Empty]] = empty,
assignees_ids: Optional[Union[List[str], Empty]] = empty,
status: Optional[Union[ActivityStatus, str, Empty]] = empty,
overwrite: Optional[bool] = False,
**kwargs,
) -> None:
"""
Edit the activity and all its descendants with a single operation.
:param start_date: (optionally) edit the start date of the activity as a datetime object
(UTC time/timezone aware preferred)
:type start_date: datetime or None
:param due_date: (optionally) edit the due_date of the activity as a datetime object
(UTC time/timzeone aware preferred)
:type due_date: datetime or None
:param assignees: (optionally) edit the assignees (usernames) of the activity as a list
:type assignees: list(basestring) or None
:param assignees_ids: (optionally) edit the assignees (user id's) of the activity as a list
:type assignees_ids: list(basestring) or None
:param status: (optionally) edit the status of the activity as a string based
on :class:`~pykechain.enums.ActivityStatus`
:type status: ActivityStatus, basestring or None
:param overwrite: (optionally) whether to overwrite existing assignees (True) or
merge with existing assignees (False, default)
:type overwrite: bool
:return: flat list of the current task all descendants that have been edited
:rtype list[Activity]
"""
update_dict = {"id": self.id}
self._validate_edit_arguments(
update_dict=update_dict,
start_date=start_date,
due_date=due_date,
assignees=assignees,
assignees_ids=assignees_ids,
status=status,
**kwargs,
)
all_tasks = [self] + self.all_children()
new_assignees = update_dict.get("assignees_ids", list())
# Create update-json
data = list()
update_dict = clean_empty_values(update_dict=update_dict)
for task in all_tasks:
task_specific_update_dict = dict(update_dict)
if not overwrite:
# Append the existing assignees of the task to the new assignees
existing_assignees = [u.id for u in task.assignees]
task_specific_update_dict["assignees_ids"] = list(
set(existing_assignees + new_assignees)
)
task_specific_update_dict.update({"id": task.id})
data.append(task_specific_update_dict)
# Perform bulk update
self._client.update_activities(activities=data)
def edit(
self,
name: Optional[Union[str, Empty]] = empty,
description: Optional[Union[str, Empty]] = empty,
start_date: Optional[Union[datetime.datetime, Empty]] = empty,
due_date: Optional[Union[datetime.datetime, Empty]] = empty,
assignees: Optional[Union[List[str], Empty]] = empty,
assignees_ids: Optional[Union[List[str], Empty]] = empty,
status: Optional[Union[ActivityStatus, str, Empty]] = empty,
tags: Optional[Union[List[str], Empty]] = empty,
**kwargs,
) -> None:
"""Edit the details of an activity.
Setting an input to None will clear out the value (exception being name and status).
:param name: (optionally) edit the name of the activity. Name cannot be cleared.
:type name: basestring or None or Empty
:param description: (optionally) edit the description of the activity or clear it
:type description: basestring or None or Empty
:param start_date: (optionally) edit the start date of the activity as a datetime object
(UTC time/timezone aware preferred) or clear it
:type start_date: datetime or None or Empty
:param due_date: (optionally) edit the due_date of the activity as a datetime object
(UTC time/timzeone aware preferred) or clear it
:type due_date: datetime or None or Empty
:param assignees: (optionally) edit the assignees (usernames) of the activity as a list,
will overwrite all assignees or clear them
:type assignees: list(basestring) or None or Empty
:param assignees_ids: (optionally) edit the assignees (user id's) of the activity as a
list, will overwrite all assignees or clear them
:type assignees_ids: list(basestring) or None or Empty
:param status: (optionally) edit the status of the activity as a string based. Status
cannot be cleared on :class:`~pykechain.enums.ActivityStatus`
:type status: ActivityStatus or None or Empty
:param tags: (optionally) replace the tags on an activity, which is a list of strings
["one","two","three"] or clear them
:type tags: list of basestring or None or Empty
:raises NotFoundError: if a `username` in the list of assignees is not in the list
of scope members
:raises IllegalArgumentError: if the type of the inputs is not correct
:raises APIError: if another Error occurs
:warns: UserWarning - When a naive datetime is provided. Defaults to UTC.
Example
-------
>>> from datetime import datetime
>>> my_task = project.activity('Specify the wheel diameter')
>>> my_task.edit(name='Specify wheel diameter and circumference',
... description='The diameter and circumference are specified in inches',
... start_date=datetime.utcnow(),
... assignee='testuser')
If we want to provide timezone aware datetime objects we can use the 3rd party
convenience library :mod:`pytz`. Mind that we need to fetch the timezone first and use
`<timezone>.localize(<your datetime>)` to make it work correctly.
Using `datetime(2017,6,1,23,59,0 tzinfo=<tz>)` does NOT work for most timezones with a
daylight saving time. Check the `pytz
<http://pythonhosted.org/pytz/#localized-times-and-date-arithmetic>`_ documentation.
To make it work using :mod:`pytz` and timezone aware :mod:`datetime` see the following
example::
>>> import pytz
>>> start_date_tzaware = datetime.now(pytz.utc)
>>> mytimezone = pytz.timezone('Europe/Amsterdam')
>>> due_date_tzaware = mytimezone.localize(datetime(2019, 10, 27, 23, 59, 0))
>>> my_task.edit(start_date=start_date_tzaware,due_date=due_date_tzaware)
Not mentioning an input parameter in the function will leave it unchanged. Setting a
parameter as None will clear its value (where that is possible). The example below will
clear the due_date, but leave everything else unchanged.
>>> my_task.edit(due_date=None)
"""
update_dict = {
"id": self.id,
"name": check_text(text=name, key="name") or self.name,
"description": check_text(text=description, key="description") or "",
"tags": check_list_of_text(tags, "tags", True) or list(),
}
self._validate_edit_arguments(
update_dict=update_dict,
start_date=start_date,
due_date=due_date,
assignees=assignees,
assignees_ids=assignees_ids,
status=status,
**kwargs,
)
update_dict = clean_empty_values(update_dict=update_dict)
url = self._client._build_url("activity", activity_id=self.id)
response = self._client._request(
"PUT", url, json=update_dict, params=API_EXTRA_PARAMS["activity"]
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Activity {self}", response=response)
self.refresh(json=response.json().get("results")[0])
def _validate_edit_arguments(
self,
update_dict,
start_date=None,
due_date=None,
assignees=None,
assignees_ids=None,
status=None,
**kwargs,
) -> Dict:
"""Verify inputs provided in both the `clone`, `edit` and `edit_cascade_down` methods."""
update_dict.update(
{
"start_date": check_datetime(dt=start_date, key="start_date"),
"due_date": check_datetime(dt=due_date, key="due_date"),
"status": check_enum(status, ActivityStatus, "status") or self.status,
}
)
# If both are empty that means the user is not interested in changing them
if isinstance(assignees_ids, Empty) and isinstance(assignees, Empty):
pass
# If one of them is None, then the assignees will be cleared from the Activity
elif assignees is None or assignees_ids is None:
update_dict["assignees_ids"] = list()
# In case both of them have values specified, then an Error is raised
elif (
assignees
and assignees_ids
and not isinstance(assignees, Empty)
and not isinstance(assignees_ids, Empty)
):
raise IllegalArgumentError(
"Provide either assignee names or their ids, but not both."
)
# Otherwise, pick the one that has a value specified which is not Empty
else:
assignees = (
assignees
if assignees is not None and not isinstance(assignees, Empty)
else assignees_ids
)
if assignees:
if not isinstance(assignees, (list, tuple, set)) or not all(
isinstance(a, (str, int)) for a in assignees
):
raise IllegalArgumentError(
"All assignees must be provided as list, tuple or set of names or IDs."
)
update_assignees_ids = [
m.get("id")
for m in self.scope.members()
if m.get("id") in assignees or m.get("username") in set(assignees)
]
if len(update_assignees_ids) != len(assignees):
raise NotFoundError(
"All assignees should be a member of the project."
)
else:
update_assignees_ids = list()
update_dict["assignees_ids"] = update_assignees_ids
if kwargs:
update_dict.update(kwargs)
return update_dict
def delete(self) -> bool:
"""Delete this activity.
:return: True when successful
:raises APIError: when unable to delete the activity
"""
response = self._client._request(
"DELETE", self._client._build_url("activity", activity_id=self.id)
)
if response.status_code != requests.codes.no_content:
raise APIError(f"Could not delete Activity {self}.", response=response)
return True
#
# Searchers and retrievers
#
def parts(self, *args, **kwargs):
"""Retrieve parts belonging to this activity.
Without any arguments it retrieves the Instances related to this task only.
This call only returns the configured properties in an activity. So properties that are
not configured are not in the returned parts.
See :class:`pykechain.Client.parts` for additional available parameters.
Example
-------
>>> task = project.activity('Specify Wheel Diameter')
>>> parts = task.parts()
To retrieve the models only.
>>> parts = task.parts(category=Category.MODEL)
"""
return [p for w in self.widgets() for p in w.parts(*args, **kwargs)]
def associated_parts(self, *args, **kwargs):
"""Retrieve models and instances belonging to this activity.
This is a convenience method for the :func:`Activity.parts()` method, which is used to
retrieve both the `Category.MODEL` as well as the `Category.INSTANCE` in a tuple.
This call only returns the configured properties in an activity. So properties that are
not configured are not in the returned parts.
If you want to retrieve only the models associated to this task it is better to use:
`task.parts(category=Category.MODEL)`.
See :func:`pykechain.Client.parts` for additional available parameters.
:returns: a tuple(models of :class:`PartSet`, instances of :class:`PartSet`)
Example
-------
>>> task = project.activity('Specify Wheel Diameter')
>>> all_models, all_instances = task.associated_parts()
"""
associated_models = list()
associated_instances = list()
for widget in self.widgets():
associated_models.extend(
widget.parts(category=Category.MODEL, *args, **kwargs)
)
associated_instances.extend(
widget.parts(category=Category.INSTANCE, *args, **kwargs)
)
return (associated_models, associated_instances)
def associated_object_ids(self) -> List[Dict]:
"""Retrieve object ids associated to this activity.
This represents a more in-depth retrieval of objects associated to the activity. Each
element in the list represents a `Property` of `Category.INSTANCE`. Each element
contains the following fields:
'id': The ID of the association
'widget': The ID of the widget to which the Property instance is associated
'activity': The ID of the activity
'model_property': The ID of the Property model
'model_part': The ID of the model of the Part containing said Property
'instance_property': The ID of the Property instance
'instance_part': The ID of the Part instance containing said Property
'writable': True if the Property is writable, False if is not
See :func:`pykechain.Client.parts` for additional available parameters.
:returns: a list of dictonaries with association objects associated to the activity
:raises NotFoundError: When the response from the server was invalid.
Example
-------
>>> task = project.activity('Specify Wheel Diameter')
>>> associated_object_ids = task.associated_object_ids()
"""
request_params = dict(
activity=self.id,
)
url = self._client._build_url("associations")
response = self._client._request("GET", url, params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError(
f"Could not retrieve Associations on Activity {self}", response=response
)
data = response.json()
return data["results"]
#
# Customizations
#
def widgets(self, **kwargs) -> "WidgetsManager":
"""
Widgets of the activity.
Works with KE-chain version 3.
:param kwargs: additional keyword arguments
:return: A :class:`WidgetManager` list, containing the widgets
:rtype: WidgetManager
:raises NotFoundError: when the widgets could not be found
:raises APIError: when the API does not support the widgets, or when API gives an error.
"""
if self._widgets_manager is None:
widgets = self._client.widgets(activity=self.id, **kwargs)
self._widgets_manager = WidgetsManager(widgets=widgets, activity=self)
return self._widgets_manager
def download_as_pdf(
self,
target_dir: str = None,
pdf_filename: str = None,
paper_size: PaperSize = PaperSize.A4,
paper_orientation: PaperOrientation = PaperOrientation.PORTRAIT,
include_appendices: bool = False,
as_zip: bool = False,
include_qr_code: bool = False,
user: Optional[User] = None,
timeout: int = ASYNC_TIMEOUT_LIMIT,
) -> str:
"""
Retrieve the PDF of the Activity.
.. versionadded:: 2.1
:param target_dir: (optional) directory path name where the store the log.txt to.
:param pdf_filename: (optional) log filename to write the log to, defaults to `log.txt`.
:param paper_size: The size of the paper to which the PDF is downloaded:
- a4paper (default): A4 paper size
- a3paper: A3 paper size
- a2paper: A2 paper size
- a1paper: A1 paper size
- a0paper: A0 paper size
:param paper_orientation: The orientation of the paper to which the PDF is downloaded:
- portrait (default): portrait orientation
- landscape: landscape orientation
:param include_appendices: True if the PDF should contain appendices, False (default)
if otherwise.
:param as_zip: The PDF appendices, if appendices are enabled are
rendered inline inside the PDF. If this is set to True, then a ZIP will be returned
where all attachments that cannot be rendered, including the PDF attachments are
included in that zip in a subdirectory 'attachments'. (defaults to False)
:param include_qr_code: True if the PDF should include a QR-code, False (default)
if otherwise.
:param user: (optional) used to calculate the offset needed to interpret Datetime
Properties. Not having a user will simply use the default UTC.
:param timeout: (optional) number of seconds to wait for the PDF to be created, defaults
to ASYNC_TIMEOUT_LIMIT
:raises APIError: if the pdf file could not be found.
:raises OSError: if the file could not be written.
:returns Path to the saved pdf file
:rtype str
"""
if not pdf_filename:
pdf_filename = self.name + ".pdf"
if not pdf_filename.endswith(".pdf"):
pdf_filename += ".pdf"
full_path = os.path.join(target_dir or os.getcwd(), pdf_filename)
request_params = dict(
papersize=check_enum(paper_size, PaperSize, "paper_size"),
orientation=check_enum(
paper_orientation, PaperOrientation, "paper_orientation"
),
appendices=check_type(include_appendices, bool, "include_appendices"),
as_zip=check_type(as_zip, bool, "as_zip"),
includeqr=check_type(include_qr_code, bool, "include_qr_code"),
)
if user:
user_object = check_type(user, User, "user")
request_params.update(
offset=get_offset_from_user_timezone(user=user_object),
timezone=str(get_timezone_from_user(user=user_object)),
)
url = self._client._build_url("activity_export", activity_id=self.id)
response = self._client._request("GET", url, params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(
f"Could not download PDF of Activity {self}", response=response
)
# If appendices are included, the request becomes asynchronous
if include_appendices: # pragma: no cover
data = response.json()
# Download the pdf async
url = urljoin(self._client.api_root, data["download_url"])
count = 0
while count <= timeout:
response = self._client._request("GET", url=url)
if response.status_code == requests.codes.ok: # pragma: no cover
with open(full_path, "wb") as f:
for chunk in response.iter_content(1024):
f.write(chunk)
return full_path
count += ASYNC_REFRESH_INTERVAL
time.sleep(ASYNC_REFRESH_INTERVAL)
raise PDFDownloadTimeoutError(
f"Could not download PDF of Activity {self} within the time-out limit "
f"of {timeout} seconds",
response=response,
)
with open(full_path, "wb") as f:
for chunk in response.iter_content(1024):
f.write(chunk)
return full_path
def move(self, parent, classification=None):
"""
Move the `Activity` to a new parent.
See :func:`pykechain.Client.move_activity` for available parameters.
If you want to move an Activity from one classification to another, you need to provide
the target classification. The classification of the parent should match the one
provided in the function. This is to ensure that you really want this to happen.
:param parent: parent object to move activity to
:type parent: Union[Activity, Text]
:param classification: (optional) classification of the target parent if you want to
change the classification.
:type classification: ActivityClassification or None
:raises IllegalArgumentError: if the 'parent' activity_type is not
:class:`enums.ActivityType.SUBPROCESS`
:raises IllegalArgumentError: if the 'parent' type is not :class:`Activity` or UUID
:raises APIError: if an Error occurs.
"""
return self._client.move_activity(self, parent, classification=classification)
def share_link(
self,
subject: str,
message: str,
recipient_users: List[Union[User, str]],
from_user: Optional[User] = None,
) -> None:
"""
Share the link of the `Activity` through email.
:param subject: subject of email
:type subject: basestring
:param message: message of email
:type message: basestring
:param recipient_users: users that will receive the email
:type recipient_users: list(Union(User, Id))
:param from_user: User that shared the link (optional)
:type from_user: User object
:raises APIError: if an internal server error occurred.
"""
params = dict(
message=check_text(message, "message"),
subject=check_text(subject, "subject"),
recipient_users=[
check_user(recipient, User, "recipient")
for recipient in recipient_users
],
activity_id=self.id,
)
if from_user:
check_user(from_user, User, "from_user")
params.update(
from_user=from_user.id,
offset=get_offset_from_user_timezone(user=from_user),
timezone=str(get_timezone_from_user(user=from_user)),
)
url = self._client._build_url("notification_share_activity_link")
response = self._client._request("POST", url, data=params)
if response.status_code not in (
requests.codes.created,
requests.codes.accepted,
): # pragma: no cover
raise APIError(
f"Could not share the link to Activity {self}", response=response
)
def share_pdf(
self,
subject: str,
message: str,
recipient_users: List[Union[User, str]],
paper_size: Optional[PaperSize] = PaperSize.A3,
paper_orientation: Optional[PaperOrientation] = PaperOrientation.PORTRAIT,
from_user: Optional[User] = None,
include_appendices: Optional[bool] = False,
as_zip: bool = False,
include_qr_code: Optional[bool] = False,
**kwargs,
) -> None:
"""
Share the PDF of the `Activity` through email.
:param subject: subject of email
:type subject: basestring
:param message: message of email
:type message: basestring
:param recipient_users: users that will receive the email
:type recipient_users: list(Union(User, Id))
:param paper_size: The size of the paper to which the PDF is downloaded:
- a4paper: A4 paper size
- a3paper: A3 paper size (default)
- a2paper: A2 paper size
- a1paper: A1 paper size
- a0paper: A0 paper size
:type paper_size: basestring (see :class:`enums.PaperSize`)
:param paper_orientation: The orientation of the paper to which the PDF is downloaded:
- portrait (default): portrait orientation
- landscape: landscape orientation
:type paper_size: basestring (see :class:`enums.PaperOrientation`)
:param from_user: User that shared the PDF (optional)
:type from_user: User object
:param include_appendices: True if the PDF should contain appendices, False (default)
if otherwise.
:type include_appendices: bool
:param as_zip: The PDF appendices, if appendices are enabled are
rendered inline inside the PDF. If this is set to True, then a ZIP will be returned
where all attachments that cannot be rendered, including the PDF attachments are
included in that zip in a subdirectory 'attachments'. (Defaults to False)
:type as_zip: bool
:param include_qr_code: True if the PDF should include a QR-code, False (default)
if otherwise.
:type include_qr_code: bool
:raises APIError: if an internal server error occurred.
"""
recipient_emails = list()
recipient_users_ids = list()
if isinstance(recipient_users, list) and all(
isinstance(r, (str, int, User)) for r in recipient_users
):
for user in recipient_users:
if is_valid_email(user):
recipient_emails.append(user)
else:
recipient_users_ids.append(check_user(user, User, "recipient"))
else:
raise IllegalArgumentError(
"`recipients` must be a list of User objects, IDs or email addresses, "
'"{}" ({}) is not.'.format(recipient_users, type(recipient_users))
)
params = dict(
message=check_text(message, "message"),
subject=check_text(subject, "subject"),
recipient_users=recipient_users_ids,
recipient_emails=recipient_emails,
activity_id=self.id,
papersize=check_enum(paper_size, PaperSize, "paper_size"),
orientation=check_enum(
paper_orientation, PaperOrientation, "paper_orientation"
),
appendices=check_type(include_appendices, bool, "include_appendices"),
as_zip=check_type(as_zip, bool, "as_zip"),
includeqr=check_type(include_qr_code, bool, "include_qr_code"),
)
if from_user:
check_user(from_user, User, "from_user")
params.update(
from_user=from_user.id,
offset=get_offset_from_user_timezone(user=from_user),
timezone=str(get_timezone_from_user(user=from_user)),
)
url = self._client._build_url("notification_share_activity_pdf")
response = self._client._request("POST", url, data=params)
if response.status_code not in (
requests.codes.created,
requests.codes.accepted,
): # pragma: no cover
raise APIError(
f"Could not share the link to Activity {self}", response=response
)
#
# Context Methods
#
def context(self, *args, **kwargs) -> "Context":
"""
Retrieve a context object associated to this activity and scope.
See :class:`pykechain.Client.context` for available parameters.
.. versionadded:: 3.12
:return: a Context object
"""
return self._client.context(*args, scope=self.scope, activity=self, **kwargs)
def contexts(self, *args, **kwargs) -> List["Context"]:
"""
Retrieve context objects t associated to this activity and scope.
See :class:`pykechain.Client.contexts` for available parameters.
.. versionadded:: 3.12
:return: a list of Context objects
"""
return self._client.contexts(scope=self.scope, activity=self, **kwargs)
def create_context(self, *args, **kwargs) -> "Context":
"""
Create a new Context object of a ContextType in a scope and associated it to this activity.
See :class:`pykechain.Client.create_context` for available parameters.
.. versionadded:: 3.12
:return: a Context object
"""
return self._client.create_context(
scope=self.scope, actitivities=[self], **kwargs
)
def link_context(self, context: "Context") -> None:
"""
Link the current activity to an existing Context.
If you want to link multiple activities at once,
use the `Context.link_activities()` method.
:param context: A Context object to link the current activity to.
:raises IllegalArgumentError: When the context is not a Context object.
"""
if not context.__class__.__name__ == "Context":
raise IllegalArgumentError(
f"`context` should be a proper Context object. Got: {context}"
)
context.link_activities(activities=[self])
self.refresh()
def unlink_context(self, context: "Context") -> None:
"""
Link the current activity to an existing Context.
If you want to unlink multiple activities at once,
use the `Context.unlink_activities()` method.
:param context: A Context object to unlink the current activity from.
:raises IllegalArgumentError: When the context is not a Context object.
"""
if not context.__class__.__name__ == "Context":
raise IllegalArgumentError(
f"`context` should be a proper Context object. Got: {context}"
)
context.unlink_activities(activities=[self])
self.refresh()
def clone_widgets(self, from_activity: "Activity") -> None:
"""
Clone widgets from another Activity to the current one.
The two activities must be related to the same Form.
:param from_activity: An Activity object that contains the widgets that are wanted in the
current one
:raises APIError: When the call is unsuccessful, for example when cloning cross-forms
"""
url = self._client._build_url(
"clone_widgets", activity_from_id=self.id, activity_to_id=from_activity.id
)
response = self._client._request(
"POST",
url,
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Activity {self}", response=response)
|
class Activity(TreeObject, TagsMixin):
'''A virtual object representing a KE-chain activity.
.. versionadded:: 2.0
:ivar id: id of the activity
:type id: uuid
:ivar name: name of the activity
:type name: basestring
:ivar created_at: created datetime of the activity
:type created_at: datetime
:ivar updated_at: updated datetime of the activity
:type updated_at: datetime
:ivar description: description of the activity
:type description: basestring
:ivar status: status of the activity. One of :class:`pykechain.enums.ActivityStatus`
:type status: basestring
:ivar classification: classification of the activity. One of :class:
`pykechain.enums.ActivityClassification`
:type classification: basestring
:ivar activity_type: Type of the activity. One of :class:`pykechain.enums.ActivityType`
for WIM version 2
:type activity_type: basestring
'''
def __init__(self, json, **kwargs):
'''Construct an Activity from a json object.'''
pass
def __call__(self, *args, **kwargs) -> "Activity":
'''Short-hand version of the `child` method.'''
pass
def refresh(self, *args, **kwargs):
'''Refresh the object in place.'''
pass
@property
def assignees(self) -> List["User"]:
'''List of assignees to the activity.
Provides a list of `User` objects or an empty list.
:return: a list of `User` objects or an empty list.
:rtype: list
'''
pass
@property
def scope_id(self):
'''
Id of the scope this Activity belongs to.
This property will always produce a scope_id, even when the scope object was not included
in an earlier response.
When the :class:`Scope` is not included in this task, it will make an additional call to
the KE-chain API.
:return: the scope id
:type: uuid
:raises NotFoundError: if the scope could not be found
'''
pass
@scope_id.setter
def scope_id(self):
pass
@property
def representations(self):
'''Get and set the activity representations.'''
pass
@representations.setter
def representations(self):
pass
def _save_representations(self, representation_options):
pass
def is_rootlevel(self) -> bool:
'''
Activity is at the toplevel of a project, i.e. below the root itself.
It will look for the name of the parent which should be either
ActivityRootNames.WORKFLOW_ROOT or ActivityRootNames.CATALOG_ROOT. If the name of the
parent cannot be found an additional API call is made to retrieve the parent object (
based on the `parent_id` in the json_data).
:return: Return True if it is a root level activity, otherwise return False
'''
pass
def is_task(self) -> bool:
'''
Activity is of ActivityType.TASK.
:return: Return True if it is a task, otherwise return False
'''
pass
def is_subprocess(self) -> bool:
'''
Activity is of ActivityType.PROCESS.
:return: Return True if it is a subprocess, otherwise return False
'''
pass
def is_process(self) -> bool:
'''
Activity is of ActivityType.PROCESS.
:return: Return True if it is a process, otherwise return False
'''
pass
def is_workflow(self) -> bool:
'''
Classification of the Activity is of ActivityClassification.WORKFLOW.
:return: Return True if it is a workflow classification activity, otherwise return False
'''
pass
def is_app(self) -> bool:
'''
Classification of the Activity is of ActivityClassification.APP.
:return: Return True if it is a App classification activity, otherwise return False
'''
pass
def is_catalog(self) -> bool:
'''
Classification of the Activity is of ActivityClassification.CATALOG.
:return: Return True if it is a catalog classification activity, otherwise return False
'''
pass
def is_workflow_root(self) -> bool:
'''
Classification of the Activity is of ActivityClassification.WORKFLOW and a ROOT object.
:return: Return True if it is a root workflow classification activity, otherwise False
'''
pass
def is_catalog_root(self) -> bool:
'''
Classification of the Activity is of ActivityClassification.CATALOG and a ROOT object.
:return: Return True if it is a root catalog classification activity, otherwise False
'''
pass
def is_rootlevel(self) -> bool:
'''
Activity is a ROOT object.
If you want to determine if it is also a workflow or a catalog root,
use :func:`Activity.is_workflow_root()` or :func:`Activity.is_catalog_root()` methods.
:return: Return True if it is a root object, otherwise return False
'''
pass
def is_configured(self) -> bool:
'''
Activity is configured with input and output properties.
Makes an additional lightweight call to the API to determine if any associated models
are there.
:return: Return True if it is configured, otherwise return False
'''
pass
def is_customized(self) -> bool:
'''
Activity is customized.
In other words if it has a customization. Use can use the :func:`Activity.customization()`
to retrieve the customization object and configure the task.
:return: Return True if it is customized, otherwise return False
'''
pass
def create(self, *args, **kwargs) -> "Activity":
'''Create a new activity belonging to this subprocess.
See :func:`pykechain.Client.create_activity` for available parameters.
:raises IllegalArgumentError: if the `Activity` is not a `PROCESS`.
:raises APIError: if an Error occurs.
'''
pass
def parent(self) -> "Activity":
'''Retrieve the parent in which this activity is defined.
If this is a task on top level, it raises NotFounderror.
:return: a :class:`Activity`
:raises NotFoundError: when it is a task in the top level of a project
:raises APIError: when other error occurs
Example
-------
>>> task = project.activity('Subtask')
>>> parent_of_task = task.parent()
'''
pass
def children(self, **kwargs) -> List["Activity"]:
'''Retrieve the direct activities of this subprocess.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the direct
descending level. Only when the activity is a Subprocess, otherwise it raises a
NotFoundError
:param kwargs: Additional search arguments, check :func:`pykechain.Client.activities`
for additional info
:return: a list of :class:`Activity`
:raises NotFoundError: when this task is not of type `ActivityType.PROCESS`
Example
-------
>>> task = project.activity('Subprocess')
>>> children = task.children()
Example searching for children of a subprocess which contains a name (icontains searches
case insensitive)
>>> task = project.activity('Subprocess')
>>> children = task.children(name__icontains='more work')
'''
pass
def children(self, **kwargs) -> List["Activity"]:
'''
Retrieve a child object.
:param name: optional, name of the child
:type name: str
:param pk: optional, UUID of the child
:type: pk: str
:return: Child object
:raises MultipleFoundError: whenever multiple children fit match inputs.
:raises NotFoundError: whenever no child matching the inputs could be found.
'''
pass
def siblings(self, **kwargs) -> List["Activity"]:
'''Retrieve the other activities that also belong to the parent.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the level of the
current task, including itself. This also works if the activity is of type
`ActivityType.PROCESS`.
:param kwargs: Additional search arguments, check :func:`pykechain.Client.activities`
for additional info
:return: list of :class:`Activity`
:raises NotFoundError: when it is a task in the top level of a project
Example
-------
>>> task = project.activity('Some Task')
>>> siblings = task.siblings()
Example for siblings containing certain words in the task name
>>> task = project.activity('Some Task')
>>> siblings = task.siblings(name__contains='Another Task')
'''
pass
def all_children(self) -> List["Activity"]:
'''
Retrieve a flat list of all descendants, sorted depth-first.
Returns an empty list for Activities of type TASK.
:returns list of child objects
:rtype List
'''
pass
def count_children(self, **kwargs) -> int:
'''
Retrieve the number of child activities using a light-weight request.
:return: number of Activities
:rtype int
'''
pass
def clone(
self,
parent: Optional[Union["Activity", str]] = None,
update_dict: Optional[Dict] = None,
**kwargs,
) -> Optional["Activity"]:
'''
Create a copy of this activity.
:param parent: (O) parent Activity object or UUID
:type parent: Activity
:param update_dict: (O) dictionary of new values to set on the cloned activities,
e.g. `{"name": "New name"}`
:type update_dict: dict
:param kwargs: additional arguments, see the `Client.clone_activities()` method
:return: clone of this activity
:rtype Activity
'''
pass
def edit_cascade_down(
self,
start_date: Optional[Union[datetime.datetime, Empty]] = empty,
due_date: Optional[Union[datetime.datetime, Empty]] = empty,
assignees: Optional[Union[List[str], Empty]] = empty,
assignees_ids: Optional[Union[List[str], Empty]] = empty,
status: Optional[Union[ActivityStatus, str, Empty]] = empty,
overwrite: Optional[bool] = False,
**kwargs,
) -> None:
'''
Edit the activity and all its descendants with a single operation.
:param start_date: (optionally) edit the start date of the activity as a datetime object
(UTC time/timezone aware preferred)
:type start_date: datetime or None
:param due_date: (optionally) edit the due_date of the activity as a datetime object
(UTC time/timzeone aware preferred)
:type due_date: datetime or None
:param assignees: (optionally) edit the assignees (usernames) of the activity as a list
:type assignees: list(basestring) or None
:param assignees_ids: (optionally) edit the assignees (user id's) of the activity as a list
:type assignees_ids: list(basestring) or None
:param status: (optionally) edit the status of the activity as a string based
on :class:`~pykechain.enums.ActivityStatus`
:type status: ActivityStatus, basestring or None
:param overwrite: (optionally) whether to overwrite existing assignees (True) or
merge with existing assignees (False, default)
:type overwrite: bool
:return: flat list of the current task all descendants that have been edited
:rtype list[Activity]
'''
pass
def edit_cascade_down(
self,
start_date: Optional[Union[datetime.datetime, Empty]] = empty,
due_date: Optional[Union[datetime.datetime, Empty]] = empty,
assignees: Optional[Union[List[str], Empty]] = empty,
assignees_ids: Optional[Union[List[str], Empty]] = empty,
status: Optional[Union[ActivityStatus, str, Empty]] = empty,
overwrite: Optional[bool] = False,
**kwargs,
) -> None:
'''Edit the details of an activity.
Setting an input to None will clear out the value (exception being name and status).
:param name: (optionally) edit the name of the activity. Name cannot be cleared.
:type name: basestring or None or Empty
:param description: (optionally) edit the description of the activity or clear it
:type description: basestring or None or Empty
:param start_date: (optionally) edit the start date of the activity as a datetime object
(UTC time/timezone aware preferred) or clear it
:type start_date: datetime or None or Empty
:param due_date: (optionally) edit the due_date of the activity as a datetime object
(UTC time/timzeone aware preferred) or clear it
:type due_date: datetime or None or Empty
:param assignees: (optionally) edit the assignees (usernames) of the activity as a list,
will overwrite all assignees or clear them
:type assignees: list(basestring) or None or Empty
:param assignees_ids: (optionally) edit the assignees (user id's) of the activity as a
list, will overwrite all assignees or clear them
:type assignees_ids: list(basestring) or None or Empty
:param status: (optionally) edit the status of the activity as a string based. Status
cannot be cleared on :class:`~pykechain.enums.ActivityStatus`
:type status: ActivityStatus or None or Empty
:param tags: (optionally) replace the tags on an activity, which is a list of strings
["one","two","three"] or clear them
:type tags: list of basestring or None or Empty
:raises NotFoundError: if a `username` in the list of assignees is not in the list
of scope members
:raises IllegalArgumentError: if the type of the inputs is not correct
:raises APIError: if another Error occurs
:warns: UserWarning - When a naive datetime is provided. Defaults to UTC.
Example
-------
>>> from datetime import datetime
>>> my_task = project.activity('Specify the wheel diameter')
>>> my_task.edit(name='Specify wheel diameter and circumference',
... description='The diameter and circumference are specified in inches',
... start_date=datetime.utcnow(),
... assignee='testuser')
If we want to provide timezone aware datetime objects we can use the 3rd party
convenience library :mod:`pytz`. Mind that we need to fetch the timezone first and use
`<timezone>.localize(<your datetime>)` to make it work correctly.
Using `datetime(2017,6,1,23,59,0 tzinfo=<tz>)` does NOT work for most timezones with a
daylight saving time. Check the `pytz
<http://pythonhosted.org/pytz/#localized-times-and-date-arithmetic>`_ documentation.
To make it work using :mod:`pytz` and timezone aware :mod:`datetime` see the following
example::
>>> import pytz
>>> start_date_tzaware = datetime.now(pytz.utc)
>>> mytimezone = pytz.timezone('Europe/Amsterdam')
>>> due_date_tzaware = mytimezone.localize(datetime(2019, 10, 27, 23, 59, 0))
>>> my_task.edit(start_date=start_date_tzaware,due_date=due_date_tzaware)
Not mentioning an input parameter in the function will leave it unchanged. Setting a
parameter as None will clear its value (where that is possible). The example below will
clear the due_date, but leave everything else unchanged.
>>> my_task.edit(due_date=None)
'''
pass
def _validate_edit_arguments(
self,
update_dict,
start_date=None,
due_date=None,
assignees=None,
assignees_ids=None,
status=None,
**kwargs,
) -> Dict:
'''Verify inputs provided in both the `clone`, `edit` and `edit_cascade_down` methods.'''
pass
def delete(self) -> bool:
'''Delete this activity.
:return: True when successful
:raises APIError: when unable to delete the activity
'''
pass
def parts(self, *args, **kwargs):
'''Retrieve parts belonging to this activity.
Without any arguments it retrieves the Instances related to this task only.
This call only returns the configured properties in an activity. So properties that are
not configured are not in the returned parts.
See :class:`pykechain.Client.parts` for additional available parameters.
Example
-------
>>> task = project.activity('Specify Wheel Diameter')
>>> parts = task.parts()
To retrieve the models only.
>>> parts = task.parts(category=Category.MODEL)
'''
pass
def associated_parts(self, *args, **kwargs):
'''Retrieve models and instances belonging to this activity.
This is a convenience method for the :func:`Activity.parts()` method, which is used to
retrieve both the `Category.MODEL` as well as the `Category.INSTANCE` in a tuple.
This call only returns the configured properties in an activity. So properties that are
not configured are not in the returned parts.
If you want to retrieve only the models associated to this task it is better to use:
`task.parts(category=Category.MODEL)`.
See :func:`pykechain.Client.parts` for additional available parameters.
:returns: a tuple(models of :class:`PartSet`, instances of :class:`PartSet`)
Example
-------
>>> task = project.activity('Specify Wheel Diameter')
>>> all_models, all_instances = task.associated_parts()
'''
pass
def associated_object_ids(self) -> List[Dict]:
'''Retrieve object ids associated to this activity.
This represents a more in-depth retrieval of objects associated to the activity. Each
element in the list represents a `Property` of `Category.INSTANCE`. Each element
contains the following fields:
'id': The ID of the association
'widget': The ID of the widget to which the Property instance is associated
'activity': The ID of the activity
'model_property': The ID of the Property model
'model_part': The ID of the model of the Part containing said Property
'instance_property': The ID of the Property instance
'instance_part': The ID of the Part instance containing said Property
'writable': True if the Property is writable, False if is not
See :func:`pykechain.Client.parts` for additional available parameters.
:returns: a list of dictonaries with association objects associated to the activity
:raises NotFoundError: When the response from the server was invalid.
Example
-------
>>> task = project.activity('Specify Wheel Diameter')
>>> associated_object_ids = task.associated_object_ids()
'''
pass
def widgets(self, **kwargs) -> "WidgetsManager":
'''
Widgets of the activity.
Works with KE-chain version 3.
:param kwargs: additional keyword arguments
:return: A :class:`WidgetManager` list, containing the widgets
:rtype: WidgetManager
:raises NotFoundError: when the widgets could not be found
:raises APIError: when the API does not support the widgets, or when API gives an error.
'''
pass
def download_as_pdf(
self,
target_dir: str = None,
pdf_filename: str = None,
paper_size: PaperSize = PaperSize.A4,
paper_orientation: PaperOrientation = PaperOrientation.PORTRAIT,
include_appendices: bool = False,
as_zip: bool = False,
include_qr_code: bool = False,
user: Optional[User] = None,
timeout: int = ASYNC_TIMEOUT_LIMIT,
) -> str:
'''
Retrieve the PDF of the Activity.
.. versionadded:: 2.1
:param target_dir: (optional) directory path name where the store the log.txt to.
:param pdf_filename: (optional) log filename to write the log to, defaults to `log.txt`.
:param paper_size: The size of the paper to which the PDF is downloaded:
- a4paper (default): A4 paper size
- a3paper: A3 paper size
- a2paper: A2 paper size
- a1paper: A1 paper size
- a0paper: A0 paper size
:param paper_orientation: The orientation of the paper to which the PDF is downloaded:
- portrait (default): portrait orientation
- landscape: landscape orientation
:param include_appendices: True if the PDF should contain appendices, False (default)
if otherwise.
:param as_zip: The PDF appendices, if appendices are enabled are
rendered inline inside the PDF. If this is set to True, then a ZIP will be returned
where all attachments that cannot be rendered, including the PDF attachments are
included in that zip in a subdirectory 'attachments'. (defaults to False)
:param include_qr_code: True if the PDF should include a QR-code, False (default)
if otherwise.
:param user: (optional) used to calculate the offset needed to interpret Datetime
Properties. Not having a user will simply use the default UTC.
:param timeout: (optional) number of seconds to wait for the PDF to be created, defaults
to ASYNC_TIMEOUT_LIMIT
:raises APIError: if the pdf file could not be found.
:raises OSError: if the file could not be written.
:returns Path to the saved pdf file
:rtype str
'''
pass
def move(self, parent, classification=None):
'''
Move the `Activity` to a new parent.
See :func:`pykechain.Client.move_activity` for available parameters.
If you want to move an Activity from one classification to another, you need to provide
the target classification. The classification of the parent should match the one
provided in the function. This is to ensure that you really want this to happen.
:param parent: parent object to move activity to
:type parent: Union[Activity, Text]
:param classification: (optional) classification of the target parent if you want to
change the classification.
:type classification: ActivityClassification or None
:raises IllegalArgumentError: if the 'parent' activity_type is not
:class:`enums.ActivityType.SUBPROCESS`
:raises IllegalArgumentError: if the 'parent' type is not :class:`Activity` or UUID
:raises APIError: if an Error occurs.
'''
pass
def share_link(
self,
subject: str,
message: str,
recipient_users: List[Union[User, str]],
from_user: Optional[User] = None,
) -> None:
'''
Share the link of the `Activity` through email.
:param subject: subject of email
:type subject: basestring
:param message: message of email
:type message: basestring
:param recipient_users: users that will receive the email
:type recipient_users: list(Union(User, Id))
:param from_user: User that shared the link (optional)
:type from_user: User object
:raises APIError: if an internal server error occurred.
'''
pass
def share_pdf(
self,
subject: str,
message: str,
recipient_users: List[Union[User, str]],
paper_size: Optional[PaperSize] = PaperSize.A3,
paper_orientation: Optional[PaperOrientation] = PaperOrientation.PORTRAIT,
from_user: Optional[User] = None,
include_appendices: Optional[bool] = False,
as_zip: bool = False,
include_qr_code: Optional[bool] = False,
**kwargs,
) -> None:
'''
Share the PDF of the `Activity` through email.
:param subject: subject of email
:type subject: basestring
:param message: message of email
:type message: basestring
:param recipient_users: users that will receive the email
:type recipient_users: list(Union(User, Id))
:param paper_size: The size of the paper to which the PDF is downloaded:
- a4paper: A4 paper size
- a3paper: A3 paper size (default)
- a2paper: A2 paper size
- a1paper: A1 paper size
- a0paper: A0 paper size
:type paper_size: basestring (see :class:`enums.PaperSize`)
:param paper_orientation: The orientation of the paper to which the PDF is downloaded:
- portrait (default): portrait orientation
- landscape: landscape orientation
:type paper_size: basestring (see :class:`enums.PaperOrientation`)
:param from_user: User that shared the PDF (optional)
:type from_user: User object
:param include_appendices: True if the PDF should contain appendices, False (default)
if otherwise.
:type include_appendices: bool
:param as_zip: The PDF appendices, if appendices are enabled are
rendered inline inside the PDF. If this is set to True, then a ZIP will be returned
where all attachments that cannot be rendered, including the PDF attachments are
included in that zip in a subdirectory 'attachments'. (Defaults to False)
:type as_zip: bool
:param include_qr_code: True if the PDF should include a QR-code, False (default)
if otherwise.
:type include_qr_code: bool
:raises APIError: if an internal server error occurred.
'''
pass
def context(self, *args, **kwargs) -> "Context":
'''
Retrieve a context object associated to this activity and scope.
See :class:`pykechain.Client.context` for available parameters.
.. versionadded:: 3.12
:return: a Context object
'''
pass
def contexts(self, *args, **kwargs) -> List["Context"]:
'''
Retrieve context objects t associated to this activity and scope.
See :class:`pykechain.Client.contexts` for available parameters.
.. versionadded:: 3.12
:return: a list of Context objects
'''
pass
def create_context(self, *args, **kwargs) -> "Context":
'''
Create a new Context object of a ContextType in a scope and associated it to this activity.
See :class:`pykechain.Client.create_context` for available parameters.
.. versionadded:: 3.12
:return: a Context object
'''
pass
def link_context(self, context: "Context") -> None:
'''
Link the current activity to an existing Context.
If you want to link multiple activities at once,
use the `Context.link_activities()` method.
:param context: A Context object to link the current activity to.
:raises IllegalArgumentError: When the context is not a Context object.
'''
pass
def unlink_context(self, context: "Context") -> None:
'''
Link the current activity to an existing Context.
If you want to unlink multiple activities at once,
use the `Context.unlink_activities()` method.
:param context: A Context object to unlink the current activity from.
:raises IllegalArgumentError: When the context is not a Context object.
'''
pass
def clone_widgets(self, from_activity: "Activity") -> None:
'''
Clone widgets from another Activity to the current one.
The two activities must be related to the same Form.
:param from_activity: An Activity object that contains the widgets that are wanted in the
current one
:raises APIError: When the call is unsuccessful, for example when cloning cross-forms
'''
pass
| 53 | 45 | 24 | 4 | 11 | 9 | 2 | 0.91 | 2 | 25 | 16 | 0 | 47 | 20 | 47 | 89 | 1,225 | 219 | 530 | 186 | 412 | 484 | 276 | 111 | 228 | 10 | 5 | 5 | 107 |
140,831 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/activity2.py
|
pykechain.models.activity2.Activity2
|
class Activity2(Activity, _DeprecationMixin):
"""A virtual object representing a KE-chain activity.
.. versionadded:: 2.0
:ivar id: id of the activity
:type id: uuid
:ivar name: name of the activity
:type name: basestring
:ivar created_at: created datetime of the activity
:type created_at: datetime
:ivar updated_at: updated datetime of the activity
:type updated_at: datetime
:ivar description: description of the activity
:type description: basestring
:ivar status: status of the activity. One of :class:`pykechain.enums.ActivityStatus`
:type status: basestring
:ivar classification: classification of the activity. One of :class:`pykechain.enums.ActivityClassification`
:type classification: basestring
:ivar activity_type: Type of the activity. One of :class:`pykechain.enums.ActivityType` for WIM version 2
:type activity_type: basestring
"""
pass
|
class Activity2(Activity, _DeprecationMixin):
'''A virtual object representing a KE-chain activity.
.. versionadded:: 2.0
:ivar id: id of the activity
:type id: uuid
:ivar name: name of the activity
:type name: basestring
:ivar created_at: created datetime of the activity
:type created_at: datetime
:ivar updated_at: updated datetime of the activity
:type updated_at: datetime
:ivar description: description of the activity
:type description: basestring
:ivar status: status of the activity. One of :class:`pykechain.enums.ActivityStatus`
:type status: basestring
:ivar classification: classification of the activity. One of :class:`pykechain.enums.ActivityClassification`
:type classification: basestring
:ivar activity_type: Type of the activity. One of :class:`pykechain.enums.ActivityType` for WIM version 2
:type activity_type: basestring
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 9.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 24 | 3 | 2 | 1 | 1 | 19 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
140,832 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/association.py
|
pykechain.models.association.Association
|
class Association(BaseInScope):
"""
A virtual object representing a KE-chain association.
:ivar property_instance_id
:ivar property_model_id
:ivar part_instance_id
:ivar part_model_id
:ivar widget_id
:ivar activity_id
:ivar writable
"""
def __init__(self, json, client):
"""Construct an association from provided json data."""
super().__init__(json=json, client=client)
self.property_instance_id = json.get("instance_property")
self.property_model_id = json.get("model_property")
self.part_instance_id = json.get("instance_part")
self.part_model_id = json.get("model_part")
self.widget_id = json.get("widget")
self.activity_id = json.get("activity")
self.writable = json.get("writable")
self.permissions = json.get("permissions")
def __repr__(self): # pragma: no cover
return f"<pyke {self.__class__.__name__} id {self.id}>"
|
class Association(BaseInScope):
'''
A virtual object representing a KE-chain association.
:ivar property_instance_id
:ivar property_model_id
:ivar part_instance_id
:ivar part_model_id
:ivar widget_id
:ivar activity_id
:ivar writable
'''
def __init__(self, json, client):
'''Construct an association from provided json data.'''
pass
def __repr__(self):
pass
| 3 | 2 | 7 | 1 | 6 | 1 | 1 | 0.92 | 1 | 1 | 0 | 0 | 2 | 8 | 2 | 9 | 28 | 4 | 13 | 11 | 10 | 12 | 13 | 11 | 10 | 1 | 2 | 0 | 2 |
140,833 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/banner.py
|
pykechain.models.banner.Banner
|
class Banner(Base):
"""
A virtual object representing a KE-chain Banner.
.. versionadded:: 3.6
"""
def __init__(self, json, client):
"""Construct a banner from the provided json data."""
super().__init__(json=json, client=client)
self.text = json.get("text")
self.icon = json.get("icon")
self.is_active = json.get("is_active")
self.active_from = parse_datetime(json.get("active_from"))
self.active_until = parse_datetime(json.get("active_until"))
self.url = json.get("url")
def __repr__(self): # pragma: no cover
return f"<pyke Banner '{self.name}' id {self.id[-8:]}>"
def edit(
self,
text: Optional[Union[str, Empty]] = empty,
icon: Optional[Union[str, Empty]] = empty,
active_from: Optional[Union[datetime.datetime, Empty]] = empty,
active_until: Optional[Union[datetime.datetime, Empty]] = empty,
is_active: Optional[Union[bool, Empty]] = empty,
url: Optional[Union[str, Empty]] = empty,
**kwargs,
) -> None:
"""
Update the banner properties.
Setting an input to None will clear out the value (exception being text, active_from, active_until and
is_active).
:param text: Text to display in the banner. May use HTML. Text cannot be cleared.
:type text: basestring or Empty
:param icon: Font-awesome icon to stylize the banner. Can be cleared.
:type icon: basestring or None or Empty
:param active_from: Datetime from when the banner will become active. Cannot be cleared.
:type active_from: datetime.datetime or None or Empty
:param active_until: Datetime from when the banner will no longer be active. Cannot be cleared.
:type active_until: datetime.datetime or None or Empty
:param is_active: Boolean whether to set the banner as active, defaults to False. Cannot be cleared.
:type is_active: bool or Empty
:param url: target for the "more info" button within the banner. Can be cleared.
:param url: basestring or None or Empty
:return: None
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (when that is possible). The example below will clear the url and edit the text, but leave
everything else unchanged.
>>> banner.edit(text='New text here',url=None)
"""
active = check_type(is_active, bool, "is_active")
update_dict = {
"text": check_text(text, "text"),
"icon": check_text(icon, "icon") or "",
"active_from": check_datetime(active_from, "active_from")
or check_datetime(self.active_from, "active_from"),
"active_until": check_datetime(active_until, "active_until")
or check_datetime(self.active_until, "active_until"),
"is_active": empty if active is None else active,
"url": check_url(url) or "",
}
if kwargs: # pragma: no cover
update_dict.update(kwargs)
update_dict = clean_empty_values(update_dict=update_dict)
if "text" not in update_dict or update_dict["text"] is None:
update_dict["text"] = self.text
url = self._client._build_url("banner", banner_id=self.id)
response = self._client._request("PUT", url, json=update_dict)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError(f"Could not update Banner {self}", response=response)
self.refresh(json=response.json().get("results")[0])
def delete(self) -> bool:
"""Delete this banner."""
response = self._client._request(
"DELETE", self._client._build_url("banner", banner_id=self.id)
)
if response.status_code != requests.codes.no_content:
raise APIError(f"Could not delete Banner: {self}", response=response)
return True
|
class Banner(Base):
'''
A virtual object representing a KE-chain Banner.
.. versionadded:: 3.6
'''
def __init__(self, json, client):
'''Construct a banner from the provided json data.'''
pass
def __repr__(self):
pass
def edit(
self,
text: Optional[Union[str, Empty]] = empty,
icon: Optional[Union[str, Empty]] = empty,
active_from: Optional[Union[datetime.datetime, Empty]] = empty,
active_until: Optional[Union[datetime.datetime, Empty]] = empty,
is_active: Optional[Union[bool, Empty]] = empty,
url: Optional[Union[str, Empty]] = empty,
**kwargs,
) -> None:
'''
Update the banner properties.
Setting an input to None will clear out the value (exception being text, active_from, active_until and
is_active).
:param text: Text to display in the banner. May use HTML. Text cannot be cleared.
:type text: basestring or Empty
:param icon: Font-awesome icon to stylize the banner. Can be cleared.
:type icon: basestring or None or Empty
:param active_from: Datetime from when the banner will become active. Cannot be cleared.
:type active_from: datetime.datetime or None or Empty
:param active_until: Datetime from when the banner will no longer be active. Cannot be cleared.
:type active_until: datetime.datetime or None or Empty
:param is_active: Boolean whether to set the banner as active, defaults to False. Cannot be cleared.
:type is_active: bool or Empty
:param url: target for the "more info" button within the banner. Can be cleared.
:param url: basestring or None or Empty
:return: None
Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will
clear its value (when that is possible). The example below will clear the url and edit the text, but leave
everything else unchanged.
>>> banner.edit(text='New text here',url=None)
'''
pass
def delete(self) -> bool:
'''Delete this banner.'''
pass
| 5 | 4 | 22 | 4 | 12 | 7 | 2 | 0.63 | 1 | 6 | 2 | 0 | 4 | 6 | 4 | 4 | 96 | 19 | 49 | 24 | 35 | 31 | 29 | 15 | 24 | 5 | 1 | 1 | 9 |
140,834 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/exceptions.py
|
pykechain.exceptions.InspectorComponentError
|
class InspectorComponentError(Exception):
"""Error in the InspectorComponent."""
pass
|
class InspectorComponentError(Exception):
'''Error in the InspectorComponent.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
140,835 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_activities.py
|
tests.test_activities.TestActivityDownloadAsPDF
|
class TestActivityDownloadAsPDF(TestBetamax):
def setUp(self):
super().setUp()
self.activity_name = "Task - Form"
self.activity = self.project.activity(name=self.activity_name)
self.user = self.client.user(id=3) # testmanager
def test_activity_download_as_pdf(self):
# testing
with temp_chdir() as target_dir:
pdf_file = self.activity.download_as_pdf(
target_dir=target_dir, pdf_filename="pdf_file", user=self.user
)
self.assertTrue(os.path.exists(pdf_file))
self.assertTrue(pdf_file.endswith(".pdf"))
pdf_file_called_after_activity = self.activity.download_as_pdf(
target_dir=target_dir,
)
self.assertTrue(os.path.exists(pdf_file_called_after_activity))
self.assertTrue(pdf_file_called_after_activity.endswith(".pdf"))
def test_activity_download_as_pdf_async(self):
# testing
with temp_chdir() as target_dir:
pdf_file = self.activity.download_as_pdf(
target_dir=target_dir,
pdf_filename="pdf_file",
include_appendices=True,
include_qr_code=True,
)
self.assertTrue(os.path.exists(pdf_file))
self.assertTrue(pdf_file.endswith(".pdf"))
def test_activity_download_as_pdf_without_inline_pdfs(self):
# testing
with temp_chdir() as target_dir:
zip_file = self.activity.download_as_pdf(
target_dir=target_dir,
pdf_filename="pdf_file",
user=self.user,
as_zip=True,
)
self.assertTrue(os.path.exists(zip_file))
self.assertTrue(zip_file.endswith(".zip"))
def test_activity_share_link(self):
# setUp
test_user = self.client.user(username="testuser")
message = "EXAMPLE_MESSAGE"
subject = "EXAMPLE_SUBJECT"
recipient_users = [test_user]
self.activity.share_link(
subject=subject,
message=message,
recipient_users=recipient_users,
)
# testing
notifications = self.client.notifications(
subject=subject,
message=message,
event=NotificationEvent.SHARE_ACTIVITY_LINK,
)
self.assertEqual(self.client.last_response.status_code, requests.codes.ok)
self.assertTrue(len(notifications), 1)
# tearDown
notifications[0].delete()
def test_activity_share_pdf(self):
# setUp
test_user = self.client.user(username="testuser")
message = "EXAMPLE_MESSAGE"
subject = "EXAMPLE_SUBJECT"
paper_size = PaperSize.A2
paper_orientation = PaperOrientation.PORTRAIT
recipient_users = [test_user]
self.activity.share_pdf(
subject=subject,
message=message,
recipient_users=recipient_users,
paper_size=paper_size,
paper_orientation=paper_orientation,
include_appendices=False,
include_qr_code=True,
)
# testing
notifications = self.client.notifications(
subject=subject, message=message, event=NotificationEvent.SHARE_ACTIVITY_PDF
)
self.assertEqual(self.client.last_response.status_code, requests.codes.ok)
self.assertTrue(len(notifications), 1)
# tearDown
notifications[0].delete()
def test_activity_share_pdf_with_from_user(self):
# setUp
test_user = self.client.user(username="anotheruser")
from_user = self.client.user(username="testuser")
message = "EXAMPLE_MESSAGE"
subject = "EXAMPLE_SUBJECT"
paper_size = PaperSize.A2
paper_orientation = PaperOrientation.PORTRAIT
recipient_users = [test_user]
self.activity.share_pdf(
from_user=from_user,
subject=subject,
message=message,
recipient_users=recipient_users,
paper_size=paper_size,
paper_orientation=paper_orientation,
include_appendices=False,
include_qr_code=True,
)
# testing
notifications = self.client.notifications(
subject=subject, message=message, event=NotificationEvent.SHARE_ACTIVITY_PDF
)
self.assertEqual(self.client.last_response.status_code, requests.codes.ok)
self.assertTrue(len(notifications), 1)
# tearDown
notifications[0].delete()
def test_activity_share_link_with_from_user(self):
# setUp
test_user = self.client.user(username="anotheruser")
from_user = self.client.user(username="testuser")
message = "EXAMPLE_MESSAGE"
subject = "EXAMPLE_SUBJECT"
recipient_users = [test_user]
self.activity.share_link(
from_user=from_user,
subject=subject,
message=message,
recipient_users=recipient_users,
)
# testing
notifications = self.client.notifications(
subject=subject,
message=message,
event=NotificationEvent.SHARE_ACTIVITY_LINK,
)
self.assertEqual(self.client.last_response.status_code, requests.codes.ok)
self.assertTrue(len(notifications), 1)
# tearDown
notifications[0].delete()
|
class TestActivityDownloadAsPDF(TestBetamax):
def setUp(self):
pass
def test_activity_download_as_pdf(self):
pass
def test_activity_download_as_pdf_async(self):
pass
def test_activity_download_as_pdf_without_inline_pdfs(self):
pass
def test_activity_share_link(self):
pass
def test_activity_share_pdf(self):
pass
def test_activity_share_pdf_with_from_user(self):
pass
def test_activity_share_link_with_from_user(self):
pass
| 9 | 0 | 19 | 2 | 15 | 2 | 1 | 0.13 | 1 | 4 | 3 | 0 | 8 | 3 | 8 | 83 | 158 | 21 | 122 | 45 | 113 | 16 | 70 | 42 | 61 | 1 | 3 | 1 | 8 |
140,836 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_associations.py
|
tests.test_associations.TestAssociations
|
class TestAssociations(TestBetamax):
def setUp(self):
super().setUp()
self.task = self.project.create_activity(name="widget_test_task") # type: Activity
# Exactly 1 model
self.frame = self.project.part(name="Frame") # type: Part
self.frame_model = self.project.model(name="Frame")
# Zero or more model
self.wheel_parent = self.project.model(name="Bike") # type: Part
self.wheel_model = self.project.model(name="Wheel")
widgets_manager = self.task.widgets()
self.form_widget = widgets_manager.add_propertygrid_widget(
part_instance=self.frame,
readable_models=self.frame_model.properties[:2],
writable_models=[],
)
self.table_widget = widgets_manager.add_supergrid_widget(
part_model=self.wheel_model,
parent_instance=self.wheel_parent.instance(),
readable_models=[],
writable_models=self.wheel_model.properties[:2],
)
def tearDown(self):
if self.task:
self.task.delete()
super().tearDown()
def test_retrieve_associations_interface(self):
limit = 3
associations = self.client.associations(limit=limit)
self.assertIsInstance(associations, list)
self.assertEqual(limit, len(associations))
self.assertTrue(all(isinstance(a, Association) for a in associations))
def test_association_attributes(self):
attributes = ["_client", "_json_data", "id"]
association = self.client.associations(limit=1)[0]
for attribute in attributes:
with self.subTest(msg=attribute):
self.assertTrue(
hasattr(association, attribute),
"Could not find '{}' in the association: '{}'".format(
attribute, association.__dict__.keys()
),
)
def test_retrieve_associations(self):
for inputs, nr in [
(dict(widget=self.form_widget), 4),
(dict(activity=self.task), 10),
(dict(part=self.frame_model), 13),
(dict(part=self.frame), 11),
(dict(property=self.frame_model.properties[0]), 5),
(dict(property=self.frame.properties[0]), 4),
(dict(scope=self.project), 58),
]:
with self.subTest(msg=f"{inputs} should be len={nr}"):
# setUp
associations = self.client.associations(limit=100, **inputs)
# testing
self.assertEqual(nr, len(associations))
def test_retrieve_association_incorrect_inputs(self):
for keyword, value in dict(
widget="not a widget",
activity="not a task",
part="not a part",
scope="not a scope",
property="not a property",
).items():
with self.subTest(msg=f'{keyword}: "{value}"'):
with self.assertRaises(IllegalArgumentError):
self.client.associations(limit=1, **{keyword: value})
for limit in [-5, "3"]:
with self.subTest(f"limit: {type(limit)} {limit}"):
with self.assertRaises(IllegalArgumentError):
self.client.associations(limit=limit)
def test_update_widget_associations(self):
original_associations = self.client.associations(widget=self.form_widget)
self.assertEqual(4, len(original_associations))
self.form_widget.update_associations(
readable_models=[],
writable_models=self.frame_model.properties[2:3],
)
associations = self.client.associations(widget=self.form_widget)
self.assertEqual(6, len(associations))
def test_update_associations_empty(self):
self.client.update_widgets_associations(
widgets=[self.form_widget],
associations=[([], [])],
)
def test_set_associations(self):
self.form_widget.set_associations(
readable_models=[],
writable_models=self.frame_model.properties,
)
def test_set_associations_empty(self):
self.client.set_widgets_associations(
widgets=[self.form_widget],
associations=[([], [])],
)
def test_clear_associations(self):
original_associations = self.client.associations(widget=self.form_widget)
self.assertEqual(4, len(original_associations))
self.client.clear_widget_associations(widget=self.form_widget)
associations = self.client.associations(widget=self.form_widget)
self.assertEqual(0, len(associations))
def test_remove_associations(self):
original_associations = self.client.associations(widget=self.form_widget)
self.assertEqual(4, len(original_associations))
self.form_widget.remove_associations(
models=self.frame_model.properties[0:1],
)
associations = self.client.associations(widget=self.form_widget)
self.assertEqual(2, len(associations))
def test_validate_widgets_input(self):
with self.assertRaises(IllegalArgumentError, msg="Widget must be a list!"):
self.client._validate_associations(widgets="Not a list", associations=[])
with self.assertRaises(IllegalArgumentError, msg="Not every widget is a widget!"):
self.client._validate_associations(
widgets=[self.task.widgets()[0], "Not a widget"], associations=[]
)
with self.assertRaises(
IllegalArgumentError, msg="Second set of associations is not of length 2!"
):
self.client._validate_associations(
widgets=list(self.task.widgets()), associations=[([], []), ()]
)
with self.assertRaises(IllegalArgumentError, msg="Inputs are not of equal length!"):
self.client._validate_associations(
widgets=list(self.task.widgets()),
associations=[([], [])],
)
# noinspection PyTypeChecker
def test_validate_model_input(self):
model_ids = check_list_of_base(self.frame_model.properties, Property)
self.assertIsInstance(model_ids, list)
self.assertTrue(all(is_uuid(model_id) for model_id in model_ids))
self.assertEqual(len(self.frame_model.properties), len(model_ids))
with self.assertRaises(IllegalArgumentError):
check_list_of_base(objects="not a list")
with self.assertRaises(IllegalArgumentError):
check_list_of_base(
objects=[self.frame_model.properties[0], "Not a property"], cls=Property
)
def test_validate_widget_input(self):
for method in [
self.client.update_widget_associations,
self.client.set_widget_associations,
self.client.clear_widget_associations,
self.client.remove_widget_associations,
]:
with self.assertRaises(IllegalArgumentError):
method(widget="Not a widget")
def test_readable_models(self):
self.client.update_widget_associations(
widget=self.form_widget,
readable_models=self.frame_model.properties,
)
self.client.update_widget_associations(
widget=self.table_widget,
readable_models=self.wheel_model.properties,
)
with self.assertRaises(APIError):
self.client.update_widget_associations(
widget=self.table_widget,
readable_models=[self.project.id],
)
def test_writable_models(self):
self.client.update_widget_associations(
widget=self.form_widget,
writable_models=self.frame_model.properties,
)
self.client.update_widget_associations(
widget=self.table_widget,
writable_models=self.wheel_model.properties,
)
with self.assertRaises(APIError):
self.client.update_widget_associations(
widget=self.table_widget,
writable_models=[self.project.id],
)
|
class TestAssociations(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test_retrieve_associations_interface(self):
pass
def test_association_attributes(self):
pass
def test_retrieve_associations_interface(self):
pass
def test_retrieve_association_incorrect_inputs(self):
pass
def test_update_widget_associations(self):
pass
def test_update_associations_empty(self):
pass
def test_set_associations(self):
pass
def test_set_associations_empty(self):
pass
def test_clear_associations(self):
pass
def test_remove_associations(self):
pass
def test_validate_widgets_input(self):
pass
def test_validate_model_input(self):
pass
def test_validate_widget_input(self):
pass
def test_readable_models(self):
pass
def test_writable_models(self):
pass
| 18 | 0 | 12 | 1 | 10 | 0 | 1 | 0.05 | 1 | 7 | 3 | 0 | 17 | 7 | 17 | 92 | 218 | 40 | 173 | 43 | 155 | 8 | 97 | 43 | 79 | 3 | 3 | 3 | 23 |
140,837 |
KE-works/pykechain
|
KE-works_pykechain/tests/test_banners.py
|
tests.test_banners.TestBanners
|
class TestBanners(TestBetamax):
TEXT = "__This is a test banner__"
URL = "https://www.ke-chain.nl/"
ICON = "poo-storm"
KWARGS = dict(
text=TEXT,
icon=ICON,
active_from=NEW_YEAR_2020,
)
def setUp(self):
super().setUp()
self.banner = self.client.create_banner(
url=self.URL, is_active=True, **self.KWARGS
) # type: Banner
def tearDown(self):
if self.banner:
try:
self.banner.delete()
except APIError:
pass
super().tearDown()
def test_create(self):
self.assertIsInstance(self.banner, Banner)
self.assertEqual(self.TEXT, self.banner.text)
self.assertEqual(self.URL, self.banner.url)
self.assertEqual(self.ICON, self.banner.icon)
self.assertTrue(self.banner.is_active)
def test_create_empty(self):
self.banner.delete()
self.banner = self.client.create_banner(**self.KWARGS)
def test_create_invalid_inputs(self):
self.banner.delete()
with self.assertRaises(IllegalArgumentError):
self.banner = self.client.create_banner(
text=3, icon=self.ICON, active_from=NEW_YEAR_2020
)
with self.assertRaises(IllegalArgumentError):
self.banner = self.client.create_banner(
text="some text", icon=True, active_from=NEW_YEAR_2020
)
with self.assertRaises(IllegalArgumentError):
self.banner = self.client.create_banner(
text="some text", icon=self.ICON, active_from=2
)
with self.assertRaises(IllegalArgumentError):
self.banner = self.client.create_banner(active_until="later", **self.KWARGS)
with self.assertRaises(IllegalArgumentError):
self.banner = self.client.create_banner(is_active=1, **self.KWARGS)
with self.assertRaises(IllegalArgumentError):
self.banner = self.client.create_banner(url="www.ke-chain/scopes/", **self.KWARGS)
def test_delete(self):
banner_id = self.banner.id
self.banner.delete()
with self.assertRaises(APIError, msg="Cant delete the same banner twice."):
self.banner.delete()
with self.assertRaises(NotFoundError, msg="Banner is still found!"):
self.client.banner(pk=banner_id)
def test_get_banners(self):
all_banners = self.client.banners()
self.assertIsInstance(all_banners, list)
self.assertTrue(all_banners)
first_banner = all_banners[0]
self.assertIsInstance(first_banner, Banner)
def test_get_banners_invalid_inputs(self):
with self.assertRaises(IllegalArgumentError):
self.client.banners(pk=1)
with self.assertRaises(IllegalArgumentError):
self.client.banners(text=False)
with self.assertRaises(IllegalArgumentError):
self.client.banners(is_active="")
def test_get_banner(self):
banner = self.client.banner(text=self.TEXT)
self.assertTrue(banner)
self.assertIsInstance(banner, Banner)
with self.assertRaises(MultipleFoundError):
self.client.banner()
def test_get_active_banner(self):
active_banner = self.client.active_banner()
self.assertIsNotNone(active_banner)
self.assertIsInstance(active_banner, Banner)
self.assertEqual(self.banner, active_banner)
def test_edit(self):
text = "__RENAMED BANNER"
icon = "site-map"
url = "https://www.google.com/"
later = NEW_YEAR_2020 + datetime.timedelta(hours=1)
self.banner.edit(
text=text,
icon=icon,
active_from=NEW_YEAR_2020,
active_until=later,
is_active=False,
url=url,
)
self.assertEqual(text, self.banner.text)
self.assertEqual(icon, self.banner.icon)
self.assertEqual(NEW_YEAR_2020, self.banner.active_from)
self.assertEqual(later, self.banner.active_until)
self.assertFalse(self.banner.is_active)
self.assertEqual(url, self.banner.url)
def test_edit_single_inputs(self):
for kwarg in [
dict(text="New text"),
dict(icon="gifts"),
dict(active_from=NEW_YEAR_2020 - datetime.timedelta(days=1)),
dict(active_until=NEW_YEAR_2020 + datetime.timedelta(weeks=1)),
dict(is_active=False),
dict(url="https://www.google.com"),
]:
with self.subTest(msg=kwarg):
self.banner.edit(**kwarg)
# noinspection PyTypeChecker
def test_edit_invalid_inputs(self):
with self.assertRaises(IllegalArgumentError):
self.banner.edit(text=True)
with self.assertRaises(IllegalArgumentError):
self.banner.edit(icon=50)
with self.assertRaises(IllegalArgumentError):
self.banner.edit(active_from="now")
with self.assertRaises(IllegalArgumentError):
self.banner.edit(active_until="later")
with self.assertRaises(IllegalArgumentError):
self.banner.edit(url="ke-chain,com")
with self.assertRaises(IllegalArgumentError):
self.banner.edit(is_active="Yes")
# test added due to #847 - providing no inputs overwrites values
def test_edit_banner_clear_values(self):
# setup
initial_text = "Happy new Year"
initial_icon = "gifts"
initial_active_from = NEW_YEAR_2020 - datetime.timedelta(days=1)
initial_active_until = NEW_YEAR_2020 + datetime.timedelta(days=1)
initial_is_active = False
initial_url = "https://www.google.com"
self.banner.edit(
text=initial_text,
icon=initial_icon,
active_from=NEW_YEAR_2020 - datetime.timedelta(days=1),
active_until=NEW_YEAR_2020 + datetime.timedelta(days=1),
is_active=initial_is_active,
url=initial_url,
)
# Edit without mentioning values, everything should stay the same
new_text = "2021!!!"
new_is_active = True
self.banner.edit(text=new_text, is_active=new_is_active)
# testing
self.assertEqual(self.banner.text, new_text)
self.assertEqual(self.banner.icon, initial_icon)
self.assertEqual(self.banner.active_from, initial_active_from)
self.assertEqual(self.banner.active_until, initial_active_until)
self.assertEqual(self.banner.is_active, new_is_active)
self.assertEqual(self.banner.url, initial_url)
# Edit with clearing the values, name and status cannot be cleared
self.banner.edit(
text=None, icon=None, active_from=None, active_until=None, is_active=None, url=None
)
self.assertEqual(self.banner.text, new_text)
self.assertEqual(self.banner.icon, "")
self.assertEqual(self.banner.active_from, initial_active_from)
self.assertEqual(self.banner.active_until, initial_active_until)
self.assertEqual(self.banner.is_active, new_is_active)
self.assertEqual(self.banner.url, "")
|
class TestBanners(TestBetamax):
def setUp(self):
pass
def tearDown(self):
pass
def test_create(self):
pass
def test_create_empty(self):
pass
def test_create_invalid_inputs(self):
pass
def test_delete(self):
pass
def test_get_banners(self):
pass
def test_get_banners_invalid_inputs(self):
pass
def test_get_banners(self):
pass
def test_get_active_banner(self):
pass
def test_edit(self):
pass
def test_edit_single_inputs(self):
pass
def test_edit_invalid_inputs(self):
pass
def test_edit_banner_clear_values(self):
pass
| 15 | 0 | 12 | 1 | 11 | 0 | 1 | 0.04 | 1 | 9 | 5 | 0 | 14 | 1 | 14 | 89 | 193 | 30 | 157 | 38 | 142 | 7 | 122 | 38 | 107 | 3 | 3 | 2 | 17 |
140,838 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_datetime.py
|
pykechain.models.property_datetime.DatetimeProperty
|
class DatetimeProperty(Property):
"""A virtual object representing a KE-chain datetime property."""
def to_datetime(self) -> Union[type(None), datetime.datetime]:
"""Retrieve the datetime as a datetime.datetime value.
:returns: the value
"""
return parse_datetime(self._value)
@staticmethod
def to_iso_format(date_time: datetime.datetime) -> str:
"""Convert a datetime object to isoformat."""
return date_time.isoformat()
def serialize_value(self, value) -> str:
"""
Serialize the value to be set on the property by checking for formatted strings or datetime objects.
:param value: non-serialized value
:type value: Any
:return: serialized value
"""
return check_datetime(dt=value, key="value")
|
class DatetimeProperty(Property):
'''A virtual object representing a KE-chain datetime property.'''
def to_datetime(self) -> Union[type(None), datetime.datetime]:
'''Retrieve the datetime as a datetime.datetime value.
:returns: the value
'''
pass
@staticmethod
def to_iso_format(date_time: datetime.datetime) -> str:
'''Convert a datetime object to isoformat.'''
pass
def serialize_value(self, value) -> str:
'''
Serialize the value to be set on the property by checking for formatted strings or datetime objects.
:param value: non-serialized value
:type value: Any
:return: serialized value
'''
pass
| 5 | 4 | 6 | 1 | 2 | 3 | 1 | 1.38 | 1 | 3 | 0 | 1 | 2 | 0 | 3 | 3 | 24 | 5 | 8 | 5 | 3 | 11 | 7 | 4 | 3 | 1 | 1 | 0 | 3 |
140,839 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_multi_reference.py
|
pykechain.models.property_multi_reference.MultiReferenceProperty
|
class MultiReferenceProperty(_ReferencePropertyInScope):
"""A virtual object representing a KE-chain multi-references property.
.. versionadded:: 1.14
"""
REFERENCED_CLASS = Part
def _retrieve_objects(self, **kwargs) -> List[Part]:
"""
Retrieve a list of Parts.
:param kwargs: optional inputs
:return: list of Part objects
"""
part_ids = self._validate_values()
parts = []
if part_ids:
if self.category == Category.MODEL:
parts = [self._client.part(pk=part_ids[0], category=None)]
elif self.category == Category.INSTANCE:
# Retrieve the referenced model for low-permissions scripts to enable use of the `id__in` key
if (
False
): # TODO Check for script permissions in order to skip the model() retrieval
models = [None]
else:
models = self.model().value
if models:
parts = list()
for chunk in get_in_chunks(part_ids, PARTS_BATCH_LIMIT):
parts.extend(
list(
self._client.parts(
id__in=",".join(chunk),
model=models[0],
category=None,
)
)
)
return parts
def choices(self) -> List[Part]:
"""Retrieve the parts that you can reference for this `MultiReferenceProperty`.
This method makes 2 API calls: 1) to retrieve the referenced model, and 2) to retrieve the instances of
that model.
:return: the :class:`Part`'s that can be referenced as a :class:`~pykechain.model.PartSet`.
:raises APIError: When unable to load and provide the choices
Example
-------
>>> reference_property = project.part('Bike').property('a_multi_reference_property')
>>> referenced_part_choices = reference_property.choices()
"""
possible_choices = list()
# Check whether the model of this reference property (possible itself) has a configured value
if self.model().has_value():
# If a model is configured, retrieve its ID
choices_model_id = self.model()._value[0].get("id")
# Determine which parts are filtered out
prefilter: Optional[str] = self._options.get(MetaWidget.PREFILTERS, {}).get(
MetaWidget.PROPERTY_VALUE_PREFILTER
)
# Retrieve all part instances with this model ID
possible_choices = self._client.parts(
model_id=choices_model_id,
property_value=prefilter,
)
return possible_choices
def set_prefilters(
self,
property_models: List[Union[str, "AnyProperty"]] = None,
values: List[Any] = None,
filters_type: List[FilterType] = None,
prefilters: List[PropertyValueFilter] = None,
overwrite: Optional[bool] = False,
clear: Optional[bool] = False,
validate: Optional[Union[bool, Part]] = True,
) -> None:
"""
Set the pre-filters on a `MultiReferenceProperty`.
:param property_models: `list` of `Property` models (or their IDs) to set pre-filters on
:type property_models: list
:param values: `list` of values to pre-filter on, value has to match the property type.
:type values: list
:param filters_type: `list` of filter types per pre-filter, one of :class:`enums.FilterType`,
defaults to `FilterType.CONTAINS`
:type filters_type: list
:param prefilters: `list` of PropertyValueFilter objects
:type prefilters: list
:param overwrite: whether existing pre-filters should be overwritten, if new filters to the same property
are provided as input. Does not remove non-conflicting prefilters. (default = False)
:type overwrite: bool
:param clear: whether all existing pre-filters should be cleared. (default = False)
:type clear: bool
:param validate: whether the pre-filters are validated to the referenced model, which can be provided as well
:type validate: bool
:raises IllegalArgumentError: when the type of the input is provided incorrect.
"""
if not clear:
list_of_prefilters = PropertyValueFilter.parse_options(
options=self._options
)
else:
list_of_prefilters = list()
if prefilters is None:
new_prefilters = {
PropertyReferenceOptions.PREFILTER_PROPERTY_MODELS: property_models,
PropertyReferenceOptions.PREFILTER_VALUES: values,
PropertyReferenceOptions.PREFILTER_FILTER_TYPES: filters_type,
}
else:
new_prefilters = prefilters
if not validate:
part_model = None
elif isinstance(validate, Part):
part_model = validate
else:
part_model = self.value[0]
verified_prefilters = _check_prefilters(
part_model=part_model,
prefilters=new_prefilters,
)
if (
overwrite
): # Remove pre-filters from the existing prefilters if they match the property model UUID
provided_filter_ids = {pf.id for pf in verified_prefilters}
list_of_prefilters = [
pf for pf in list_of_prefilters if pf.id not in provided_filter_ids
]
list_of_prefilters += verified_prefilters
# Only update the options if there are any prefilters to be set, or if the original filters have to overwritten
if list_of_prefilters or clear:
self._options.update(
PropertyValueFilter.write_options(filters=list_of_prefilters)
)
self.edit(options=self._options)
def get_prefilters(
self,
as_lists: Optional[bool] = False,
) -> Union[List[PropertyValueFilter], Tuple[List[str]]]:
"""
Retrieve the pre-filters applied to the reference property.
:param as_lists: (O) (default = False)
If True, the pre-filters are returned as three lists of property model UUIDs, values and filter types.
:return: prefilters
"""
check_type(as_lists, bool, "as_lists")
prefilters = PropertyValueFilter.parse_options(options=self._options)
if as_lists:
property_model_ids = [pf.id for pf in prefilters]
values = [pf.value for pf in prefilters]
filter_types = [pf.type for pf in prefilters]
prefilters = tuple([property_model_ids, values, filter_types])
warnings.warn(
"Prefilters will be provided as list of `PropertyValueFilter` objects. "
"Separate lists will be deprecated in January 2021.", # TODO Deprecate January 2021
PendingDeprecationWarning,
)
return prefilters
def set_excluded_propmodels(
self,
property_models: List[Union[str, "AnyProperty"]],
overwrite: Optional[bool] = False,
validate: Optional[Union[bool, Part]] = True,
) -> None:
"""
Exclude a list of properties from being visible in the part-shop and modal (pop-up) of the reference property.
:param property_models: `list` of Property models (or their IDs) to exclude.
:type property_models: list
:param overwrite: flag whether to overwrite existing (True) or append (False, default) to existing filter(s).
:type overwrite bool
:param validate: whether the pre-filters are validated to the referenced model, which can be provided as well
:type validate: bool
:raises IllegalArgumentError
"""
if not overwrite:
list_of_propmodels_excl = self._options.get(
PropertyReferenceOptions.PROPMODELS_EXCLUDED, []
)
else:
list_of_propmodels_excl = list()
if not validate:
part_model = None
elif isinstance(validate, Part):
part_model = validate
else:
part_model = self.value[0]
list_of_propmodels_excl.extend(
_check_excluded_propmodels(
part_model=part_model,
property_models=property_models,
)
)
options_to_set = self._options
options_to_set[PropertyReferenceOptions.PROPMODELS_EXCLUDED] = list(
set(list_of_propmodels_excl)
)
self.edit(options=options_to_set)
def get_excluded_propmodel_ids(self) -> List[str]:
"""
Retrieve a list of property model UUIDs which are not visible.
:return: list of UUIDs
:rtype list
"""
return self._options.get(PropertyReferenceOptions.PROPMODELS_EXCLUDED, [])
def set_sorting(
self,
sort_property: Optional[Union["AnyProperty", str]] = None,
sort_name: Optional[Union[bool, str]] = False,
sort_direction: Optional[Union[SortTable, str]] = SortTable.ASCENDING,
clear: Optional[bool] = False,
) -> None:
"""
Set sorting on a specific property (or name) of the referenced part model.
:param sort_property: The property model on which the part instances are being sorted on
:type sort_property: :class:`Property` or UUID
:param sort_name: If set to True it will sort on name of the part. It is ignored if sort_property is None
:type sort_name: bool
:param sort_direction: The direction on which the values of property instances are being sorted on:
* ASC (default): Sort in ascending order
* DESC: Sort in descending order
:type sort_direction: basestring (see :class:`enums.SortTable`)
:param clear: whether all existing sorting should be cleared. If set to True, it will ignore all
the other parameters
:type clear: bool
:raises IllegalArgumentError
"""
if clear:
options_to_set = self._options
options_to_set.pop(PropertyReferenceOptions.SORTED_COLUMN)
options_to_set.pop(PropertyReferenceOptions.SORTED_DIRECTION)
self.edit(options=options_to_set)
return
sort_property_id: str = _retrieve_object_id(obj=sort_property)
if not sort_property_id and sort_name:
sort_property_id = PropertyReferenceOptions.NAME
options_to_set = self._options
options_to_set[PropertyReferenceOptions.SORTED_COLUMN] = sort_property_id
options_to_set[PropertyReferenceOptions.SORTED_DIRECTION] = sort_direction
self.edit(options=options_to_set)
def get_sorting(self) -> Dict:
"""
Retrieve the sorted column and sorted direction, if applicable.
:return: dict of sorting keys and values
:rtype dict
"""
sorting_options = {
PropertyReferenceOptions.SORTED_COLUMN: self._options.get(
PropertyReferenceOptions.SORTED_COLUMN
),
PropertyReferenceOptions.SORTED_DIRECTION: self._options.get(
PropertyReferenceOptions.SORTED_DIRECTION
),
}
return sorting_options
|
class MultiReferenceProperty(_ReferencePropertyInScope):
'''A virtual object representing a KE-chain multi-references property.
.. versionadded:: 1.14
'''
def _retrieve_objects(self, **kwargs) -> List[Part]:
'''
Retrieve a list of Parts.
:param kwargs: optional inputs
:return: list of Part objects
'''
pass
def choices(self) -> List[Part]:
'''Retrieve the parts that you can reference for this `MultiReferenceProperty`.
This method makes 2 API calls: 1) to retrieve the referenced model, and 2) to retrieve the instances of
that model.
:return: the :class:`Part`'s that can be referenced as a :class:`~pykechain.model.PartSet`.
:raises APIError: When unable to load and provide the choices
Example
-------
>>> reference_property = project.part('Bike').property('a_multi_reference_property')
>>> referenced_part_choices = reference_property.choices()
'''
pass
def set_prefilters(
self,
property_models: List[Union[str, "AnyProperty"]] = None,
values: List[Any] = None,
filters_type: List[FilterType] = None,
prefilters: List[PropertyValueFilter] = None,
overwrite: Optional[bool] = False,
clear: Optional[bool] = False,
validate: Optional[Union[bool, Part]] = True,
) -> None:
'''
Set the pre-filters on a `MultiReferenceProperty`.
:param property_models: `list` of `Property` models (or their IDs) to set pre-filters on
:type property_models: list
:param values: `list` of values to pre-filter on, value has to match the property type.
:type values: list
:param filters_type: `list` of filter types per pre-filter, one of :class:`enums.FilterType`,
defaults to `FilterType.CONTAINS`
:type filters_type: list
:param prefilters: `list` of PropertyValueFilter objects
:type prefilters: list
:param overwrite: whether existing pre-filters should be overwritten, if new filters to the same property
are provided as input. Does not remove non-conflicting prefilters. (default = False)
:type overwrite: bool
:param clear: whether all existing pre-filters should be cleared. (default = False)
:type clear: bool
:param validate: whether the pre-filters are validated to the referenced model, which can be provided as well
:type validate: bool
:raises IllegalArgumentError: when the type of the input is provided incorrect.
'''
pass
def get_prefilters(
self,
as_lists: Optional[bool] = False,
) -> Union[List[PropertyValueFilter], Tuple[List[str]]]:
'''
Retrieve the pre-filters applied to the reference property.
:param as_lists: (O) (default = False)
If True, the pre-filters are returned as three lists of property model UUIDs, values and filter types.
:return: prefilters
'''
pass
def set_excluded_propmodels(
self,
property_models: List[Union[str, "AnyProperty"]],
overwrite: Optional[bool] = False,
validate: Optional[Union[bool, Part]] = True,
) -> None:
'''
Exclude a list of properties from being visible in the part-shop and modal (pop-up) of the reference property.
:param property_models: `list` of Property models (or their IDs) to exclude.
:type property_models: list
:param overwrite: flag whether to overwrite existing (True) or append (False, default) to existing filter(s).
:type overwrite bool
:param validate: whether the pre-filters are validated to the referenced model, which can be provided as well
:type validate: bool
:raises IllegalArgumentError
'''
pass
def get_excluded_propmodel_ids(self) -> List[str]:
'''
Retrieve a list of property model UUIDs which are not visible.
:return: list of UUIDs
:rtype list
'''
pass
def set_sorting(
self,
sort_property: Optional[Union["AnyProperty", str]] = None,
sort_name: Optional[Union[bool, str]] = False,
sort_direction: Optional[Union[SortTable, str]] = SortTable.ASCENDING,
clear: Optional[bool] = False,
) -> None:
'''
Set sorting on a specific property (or name) of the referenced part model.
:param sort_property: The property model on which the part instances are being sorted on
:type sort_property: :class:`Property` or UUID
:param sort_name: If set to True it will sort on name of the part. It is ignored if sort_property is None
:type sort_name: bool
:param sort_direction: The direction on which the values of property instances are being sorted on:
* ASC (default): Sort in ascending order
* DESC: Sort in descending order
:type sort_direction: basestring (see :class:`enums.SortTable`)
:param clear: whether all existing sorting should be cleared. If set to True, it will ignore all
the other parameters
:type clear: bool
:raises IllegalArgumentError
'''
pass
def get_sorting(self) -> Dict:
'''
Retrieve the sorted column and sorted direction, if applicable.
:return: dict of sorting keys and values
:rtype dict
'''
pass
| 9 | 9 | 35 | 5 | 20 | 11 | 3 | 0.53 | 1 | 14 | 7 | 1 | 8 | 0 | 8 | 39 | 296 | 46 | 165 | 55 | 133 | 88 | 83 | 32 | 74 | 7 | 5 | 4 | 27 |
140,840 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.ActivityReferencesProperty
|
class ActivityReferencesProperty(_ReferencePropertyInScope):
"""A virtual object representing a KE-chain Activity References property.
.. versionadded:: 3.7
"""
REFERENCED_CLASS = Activity
def _retrieve_objects(self, **kwargs) -> List[Activity]:
"""
Retrieve a list of Activities.
:param kwargs: optional inputs
:return: list of Activity2 objects
"""
activities = []
for activity_json in self._value:
activity = Activity(client=self._client, json=activity_json)
activity.refresh() # To populate the object with all expected data
activities.append(activity)
return activities
|
class ActivityReferencesProperty(_ReferencePropertyInScope):
'''A virtual object representing a KE-chain Activity References property.
.. versionadded:: 3.7
'''
def _retrieve_objects(self, **kwargs) -> List[Activity]:
'''
Retrieve a list of Activities.
:param kwargs: optional inputs
:return: list of Activity2 objects
'''
pass
| 2 | 2 | 13 | 1 | 7 | 6 | 2 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 32 | 21 | 4 | 9 | 6 | 7 | 9 | 9 | 6 | 7 | 2 | 5 | 1 | 2 |
140,841 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.ContextReferencesProperty
|
class ContextReferencesProperty(_ReferencePropertyInScope):
"""A virtual object representing a KE-chain Context References property.
.. versionadded:: 3.7
"""
REFERENCED_CLASS = Context
def set_prefilters(
self,
prefilters: Optional = None,
clear: Optional[bool] = False,
context_group: Optional[ContextGroup] = None,
) -> None:
"""
Set pre-filters on the Context reference property.
On the Context only a context_group prefilter can be set to a single ContextGroup.
:param prefilters: Not used
:param clear: whether all existing pre-filters should be cleared. (default = False)
:param context_group: An optional ContextGroup to prefilter on. One single prefilter is
allowed.
:return: None
"""
prefilters_dict = self._options.get("prefilters", dict())
if prefilters:
raise IllegalArgumentError(
"`prefilters` argument is unused. Use `context_group` instead."
)
if clear:
prefilters_dict = dict()
if context_group:
context_group = check_enum(context_group, ContextGroup, "context_group")
prefilters_dict = {"context_group": context_group}
if context_group or clear:
self._options.update({"prefilters": prefilters_dict})
def _retrieve_objects(self, **kwargs) -> List[Context]:
"""
Retrieve a list of Contexts.
:param kwargs: optional inputs
:return: list of Context objects
"""
contexts = []
for contexts_json in self._value:
context = Context(client=self._client, json=contexts_json)
context.refresh() # To populate the object with all expected data
contexts.append(context)
return contexts
|
class ContextReferencesProperty(_ReferencePropertyInScope):
'''A virtual object representing a KE-chain Context References property.
.. versionadded:: 3.7
'''
def set_prefilters(
self,
prefilters: Optional = None,
clear: Optional[bool] = False,
context_group: Optional[ContextGroup] = None,
) -> None:
'''
Set pre-filters on the Context reference property.
On the Context only a context_group prefilter can be set to a single ContextGroup.
:param prefilters: Not used
:param clear: whether all existing pre-filters should be cleared. (default = False)
:param context_group: An optional ContextGroup to prefilter on. One single prefilter is
allowed.
:return: None
'''
pass
def _retrieve_objects(self, **kwargs) -> List[Context]:
'''
Retrieve a list of Contexts.
:param kwargs: optional inputs
:return: list of Context objects
'''
pass
| 3 | 3 | 22 | 3 | 13 | 8 | 4 | 0.67 | 1 | 5 | 3 | 0 | 2 | 1 | 2 | 33 | 53 | 9 | 27 | 13 | 19 | 18 | 20 | 8 | 17 | 5 | 5 | 1 | 7 |
140,842 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.FormReferencesProperty
|
class FormReferencesProperty(_ReferencePropertyInScope):
"""A virtual object representing a KE-chain Form References property.
.. versionadded:: 3.7
"""
REFERENCED_CLASS = Form
def _retrieve_objects(self, **kwargs) -> List[Form]:
"""
Retrieve a list of Forms.
:param kwargs: optional inputs
:return: list of Form objects
"""
forms = []
for forms_json in self._value:
form = Form(client=self._client, json=forms_json)
form.refresh() # To populate the object with all expected data
forms.append(form)
return forms
|
class FormReferencesProperty(_ReferencePropertyInScope):
'''A virtual object representing a KE-chain Form References property.
.. versionadded:: 3.7
'''
def _retrieve_objects(self, **kwargs) -> List[Form]:
'''
Retrieve a list of Forms.
:param kwargs: optional inputs
:return: list of Form objects
'''
pass
| 2 | 2 | 13 | 1 | 7 | 6 | 2 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 32 | 21 | 4 | 9 | 6 | 7 | 9 | 9 | 6 | 7 | 2 | 5 | 1 | 2 |
140,843 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.ScopeReferencesProperty
|
class ScopeReferencesProperty(_ReferenceProperty):
"""A virtual object representing a KE-chain Scope References property.
.. versionadded: 3.9
"""
REFERENCED_CLASS = Scope
def _retrieve_objects(self, **kwargs) -> List[Scope]:
"""
Retrieve a list of Scopes.
:param kwargs: optional inputs
:return: list of Scope2 objects
"""
scope_ids = self._validate_values()
scopes = []
if scope_ids:
scopes = list()
for chunk in get_in_chunks(scope_ids, PARTS_BATCH_LIMIT):
scopes.extend(
list(self._client.scopes(id__in=",".join(chunk), status=None))
)
return scopes
def set_prefilters(
self,
prefilters: List[ScopeFilter] = None,
clear: Optional[bool] = False,
) -> None:
"""
Set pre-filters on the scope reference property.
:param prefilters: list of Scope Filter objects
:type prefilters: list
:param clear: whether all existing pre-filters should be cleared. (default = False)
:type clear: bool
:return: None
"""
if prefilters is not None:
if not isinstance(prefilters, list) or not all(
isinstance(pf, ScopeFilter) for pf in prefilters
):
raise IllegalArgumentError(
f"`prefilters` must be a list of ScopeFilter objects, `{prefilters}` is not."
)
else:
prefilters = []
if not clear:
list_of_prefilters = ScopeFilter.parse_options(options=self._options)
else:
list_of_prefilters = list()
list_of_prefilters += prefilters
# Only update the options if there are any prefilters to be set, or if the original filters have to overwritten
if list_of_prefilters or clear:
self._options.update(ScopeFilter.write_options(filters=list_of_prefilters))
self.edit(options=self._options)
def get_prefilters(self) -> List[ScopeFilter]:
"""
Return a list of ScopeFilter objects currently configured on the property.
:return: list of ScopeFilter objects
:rtype list
"""
return ScopeFilter.parse_options(self._options)
def set_active_filter_switch(self, switch_visible: bool):
"""
Set the switch between active and inactive scopes on the scope reference property.
:param switch_visible: trigger the switch of showing active or inactive scopes
:type switch_visible: bool
"""
self._options.update({"show_active_status_filter": switch_visible})
self.edit(options=self._options)
def set_columns(self, list_of_columns: List[ScopeReferenceColumns] = None):
"""
Set the columns visible inside the Scope selection dialog.
:param list_of_columns: all the columns possible of a Scope
:type list_of_columns: List of columns
"""
self._options.update({"columns": list_of_columns})
self.edit(options=self._options)
|
class ScopeReferencesProperty(_ReferenceProperty):
'''A virtual object representing a KE-chain Scope References property.
.. versionadded: 3.9
'''
def _retrieve_objects(self, **kwargs) -> List[Scope]:
'''
Retrieve a list of Scopes.
:param kwargs: optional inputs
:return: list of Scope2 objects
'''
pass
def set_prefilters(
self,
prefilters: List[ScopeFilter] = None,
clear: Optional[bool] = False,
) -> None:
'''
Set pre-filters on the scope reference property.
:param prefilters: list of Scope Filter objects
:type prefilters: list
:param clear: whether all existing pre-filters should be cleared. (default = False)
:type clear: bool
:return: None
'''
pass
def get_prefilters(self) -> List[ScopeFilter]:
'''
Return a list of ScopeFilter objects currently configured on the property.
:return: list of ScopeFilter objects
:rtype list
'''
pass
def set_active_filter_switch(self, switch_visible: bool):
'''
Set the switch between active and inactive scopes on the scope reference property.
:param switch_visible: trigger the switch of showing active or inactive scopes
:type switch_visible: bool
'''
pass
def set_columns(self, list_of_columns: List[ScopeReferenceColumns] = None):
'''
Set the columns visible inside the Scope selection dialog.
:param list_of_columns: all the columns possible of a Scope
:type list_of_columns: List of columns
'''
pass
| 6 | 6 | 16 | 2 | 8 | 6 | 2 | 0.76 | 1 | 5 | 3 | 0 | 5 | 0 | 5 | 14 | 91 | 17 | 42 | 15 | 32 | 32 | 30 | 11 | 24 | 5 | 2 | 2 | 11 |
140,844 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.SignatureProperty
|
class SignatureProperty(_ReferenceProperty):
"""A virtual object representing a KE-chain StoredFile References property."""
REFERENCED_CLASS = StoredFile
@property
def value(self) -> Optional[StoredFile]:
"""
Retrieve the signature of this signature property.
:return: an optional `StoredFile` object containing the signature.
:rtype StoredFile
"""
if not self._value:
return None
elif not self._cached_values:
self._cached_values = self._retrieve_object()
return self._cached_values
@value.setter
def value(self, value: Any) -> None:
# This serialize_value helper function returns a list of value
value: List[Any] = self.serialize_value(value)
if value and isinstance(value, list):
value = value[0] # de-list this temp_value
if self.use_bulk_update:
self._pend_update(dict(value=value))
self._value = dict(id=value) if isinstance(value, str) else None
self._cached_values = None
else:
self._put_value(value)
def _retrieve_object(self, **kwargs) -> StoredFile:
return self._retrieve_objects(**kwargs)
def _retrieve_objects(self, **kwargs) -> StoredFile:
"""
Retrieve a StoredFile which contains the signature.
:param kwargs: optional inputs
:return: list of StoredFile objects
"""
if self._value:
stored_files_id = self._value.get("id")
return self._client.stored_file(id=stored_files_id)
def clear(self) -> None:
"""
Clear the signature from the value of the property.
Introduced in order to minimize the effect on custom scripts when converting
from `AttachmentProperty` to `StoredFileReferenceProperty`.
"""
if self.value:
self.value = None
@property
def filename(self) -> Optional[Union[str, list]]:
"""Filename of the file stored in the signature property."""
if self.value:
return self.value.filename
else:
return None
def download(self, directory: str, **kwargs):
"""Download stored files from the SignatureProperty.
Downloads multiple files in the provided directory and names them according to the
filename. If multiple files have the same name, it makes them unique.
:param directory: Directory path
:type directory: basestring
"""
stored_file = self.value
filename = uniquify(os.path.join(directory, stored_file.filename))
stored_file.save_as(filename=filename, **kwargs)
def upload(self, data: Any) -> None:
"""Upload a stored file to the SignatureProperty.
:param data: File path
:type data: basestring
:raises APIError: When unable to upload the file to KE-chain
:raises OSError: When the path to the file is incorrect or file could not be found
"""
filename = os.path.basename(data)
stored_file = self._client.create_stored_file(
name=filename,
scope=self.scope,
classification=StoredFileClassification.SCOPED,
category=StoredFileCategory.REFERENCED,
filepath=data,
)
self.value = stored_file
|
class SignatureProperty(_ReferenceProperty):
'''A virtual object representing a KE-chain StoredFile References property.'''
@property
def value(self) -> Optional[StoredFile]:
'''
Retrieve the signature of this signature property.
:return: an optional `StoredFile` object containing the signature.
:rtype StoredFile
'''
pass
@value.setter
def value(self) -> Optional[StoredFile]:
pass
def _retrieve_object(self, **kwargs) -> StoredFile:
pass
def _retrieve_objects(self, **kwargs) -> StoredFile:
'''
Retrieve a StoredFile which contains the signature.
:param kwargs: optional inputs
:return: list of StoredFile objects
'''
pass
def clear(self) -> None:
'''
Clear the signature from the value of the property.
Introduced in order to minimize the effect on custom scripts when converting
from `AttachmentProperty` to `StoredFileReferenceProperty`.
'''
pass
@property
def filename(self) -> Optional[Union[str, list]]:
'''Filename of the file stored in the signature property.'''
pass
def download(self, directory: str, **kwargs):
'''Download stored files from the SignatureProperty.
Downloads multiple files in the provided directory and names them according to the
filename. If multiple files have the same name, it makes them unique.
:param directory: Directory path
:type directory: basestring
'''
pass
def upload(self, data: Any) -> None:
'''Upload a stored file to the SignatureProperty.
:param data: File path
:type data: basestring
:raises APIError: When unable to upload the file to KE-chain
:raises OSError: When the path to the file is incorrect or file could not be found
'''
pass
| 12 | 7 | 10 | 1 | 6 | 4 | 2 | 0.63 | 1 | 7 | 3 | 0 | 8 | 3 | 8 | 17 | 94 | 15 | 49 | 21 | 37 | 31 | 37 | 17 | 28 | 4 | 2 | 1 | 16 |
140,845 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.StatusReferencesProperty
|
class StatusReferencesProperty(_ReferenceProperty):
"""A virtual object representing a KE-chain Status References property.
.. versionadded:: 3.19
"""
REFERENCED_CLASS = Status
def _retrieve_objects(self, **kwargs) -> List[Status]:
"""
Retrieve a list of Statuses.
:param kwargs: optional inputs
:return: list of Status objects
"""
statuses = []
for status_json in self._value:
status = Status(client=self._client, json=status_json)
status.refresh() # To populate the object with all expected data
statuses.append(status)
return statuses
|
class StatusReferencesProperty(_ReferenceProperty):
'''A virtual object representing a KE-chain Status References property.
.. versionadded:: 3.19
'''
def _retrieve_objects(self, **kwargs) -> List[Status]:
'''
Retrieve a list of Statuses.
:param kwargs: optional inputs
:return: list of Status objects
'''
pass
| 2 | 2 | 13 | 1 | 7 | 6 | 2 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 10 | 21 | 4 | 9 | 6 | 7 | 9 | 9 | 6 | 7 | 2 | 2 | 1 | 2 |
140,846 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_attachment.py
|
pykechain.models.property_attachment.AttachmentProperty
|
class AttachmentProperty(Property):
"""A virtual object representing a KE-chain attachment property."""
@property
def value(self):
"""Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').property('file_attachment')
>>> if file_attachment_property.value:
... file_attachment_property.save_as('file.ext')
... else:
... print('file attachment not set, its value is None')
"""
if self.has_value():
return f"[Attachment: {self.filename}]"
else:
return None
@value.setter
def value(self, value):
if value is None:
self.clear()
else:
self.upload(data=value)
def clear(self) -> None:
"""Clear the attachment from the attachment field.
:raises APIError: if unable to remove the attachment
"""
if self._put_value(None) is None:
self._value = None
self._json_data["value"] = None
@property
def filename(self) -> Optional[str]:
"""Filename of the attachment, without the full 'attachment' path."""
return self._value.split("/")[-1] if self.has_value() else None
def json_load(self):
"""Download the data from the attachment and deserialise the contained json.
:return: deserialised json data as :class:`dict`
:raises APIError: When unable to retrieve the json from KE-chain
:raises JSONDecodeError: When there was a problem in deserialising the json
Example
-------
Ensure that the attachment is valid json data
>>> json_attachment = project.part('Bike').property('json_attachment')
>>> deserialised_json = json_attachment.json_load()
"""
return self._download().json()
def upload(self, data: Any, **kwargs: Any) -> None:
"""Upload a file to the attachment property.
When providing a :class:`matplotlib.figure.Figure` object as data, the figure is uploaded as PNG.
For this, `matplotlib`_ should be installed.
:param data: File path
:type data: basestring
:raises APIError: When unable to upload the file to KE-chain
:raises OSError: When the path to the file is incorrect or file could not be found
.. _matplotlib: https://matplotlib.org/
"""
try:
import matplotlib.figure
if isinstance(data, matplotlib.figure.Figure):
self._upload_plot(data, **kwargs)
return
except ImportError:
pass
if isinstance(data, str):
with open(data, "rb") as fp:
self._upload(fp)
else:
self._upload_json(data, **kwargs)
self._value = data
def save_as(self, filename: Optional[str] = None, **kwargs) -> None:
"""Download the attachment to a file.
:param filename: (optional) File path. If not provided, will be saved to current working dir
with `self.filename`.
:type filename: basestring or None
One can pass the `size` parameter as kwargs. See more in Enum:ImageSize or alternatively
customize the desired image size like this (width_value, height_value)
:raises APIError: When unable to download the data
:raises OSError: When unable to save the data to disk
"""
filename = filename or os.path.join(os.getcwd(), self.filename)
with open(filename, "w+b") as f:
for chunk in self._download(**kwargs):
f.write(chunk)
def _upload_json(self, content, name="data.json"):
data = (name, json.dumps(content), "application/json")
self._upload(data)
def _upload_plot(self, figure, name="plot.png"):
buffer = io.BytesIO()
figure.savefig(buffer, format="png")
data = (name, buffer.getvalue(), "image/png")
self._upload(data)
self._value = name
def _download(self, **kwargs):
url = self._client._build_url("property_download", property_id=self.id)
request_params = dict()
if kwargs:
request_params.update(**kwargs)
response = self._client._request("GET", url, params=request_params)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not download property value.", response=response)
return response
def _upload(self, data):
url = self._client._build_url("property_upload", property_id=self.id)
response = self._client._request(
"POST",
url,
data={"part": self._json_data["part_id"]},
files={"attachment": data},
)
if response.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not upload attachment", response=response)
|
class AttachmentProperty(Property):
'''A virtual object representing a KE-chain attachment property.'''
@property
def value(self):
'''Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').property('file_attachment')
>>> if file_attachment_property.value:
... file_attachment_property.save_as('file.ext')
... else:
... print('file attachment not set, its value is None')
'''
pass
@value.setter
def value(self):
pass
def clear(self) -> None:
'''Clear the attachment from the attachment field.
:raises APIError: if unable to remove the attachment
'''
pass
@property
def filename(self) -> Optional[str]:
'''Filename of the attachment, without the full 'attachment' path.'''
pass
def json_load(self):
'''Download the data from the attachment and deserialise the contained json.
:return: deserialised json data as :class:`dict`
:raises APIError: When unable to retrieve the json from KE-chain
:raises JSONDecodeError: When there was a problem in deserialising the json
Example
-------
Ensure that the attachment is valid json data
>>> json_attachment = project.part('Bike').property('json_attachment')
>>> deserialised_json = json_attachment.json_load()
'''
pass
def upload(self, data: Any, **kwargs: Any) -> None:
'''Upload a file to the attachment property.
When providing a :class:`matplotlib.figure.Figure` object as data, the figure is uploaded as PNG.
For this, `matplotlib`_ should be installed.
:param data: File path
:type data: basestring
:raises APIError: When unable to upload the file to KE-chain
:raises OSError: When the path to the file is incorrect or file could not be found
.. _matplotlib: https://matplotlib.org/
'''
pass
def save_as(self, filename: Optional[str] = None, **kwargs) -> None:
'''Download the attachment to a file.
:param filename: (optional) File path. If not provided, will be saved to current working dir
with `self.filename`.
:type filename: basestring or None
One can pass the `size` parameter as kwargs. See more in Enum:ImageSize or alternatively
customize the desired image size like this (width_value, height_value)
:raises APIError: When unable to download the data
:raises OSError: When unable to save the data to disk
'''
pass
def _upload_json(self, content, name="data.json"):
pass
def _upload_plot(self, figure, name="plot.png"):
pass
def _download(self, **kwargs):
pass
def _upload_json(self, content, name="data.json"):
pass
| 15 | 7 | 12 | 2 | 6 | 4 | 2 | 0.67 | 1 | 5 | 1 | 1 | 11 | 1 | 11 | 49 | 150 | 37 | 69 | 28 | 53 | 46 | 58 | 23 | 45 | 4 | 3 | 2 | 22 |
140,847 |
KE-works/pykechain
|
KE-works_pykechain/pykechain/models/property_reference.py
|
pykechain.models.property_reference.StoredFilesReferencesProperty
|
class StoredFilesReferencesProperty(_ReferenceProperty):
"""A virtual object representing a KE-chain StoredFile References property."""
REFERENCED_CLASS = StoredFile
def _retrieve_objects(self, **kwargs) -> List[StoredFile]:
"""
Retrieve a list of StoredFile.
:param kwargs: optional inputs
:return: list of StoredFile objects
"""
if self._value:
stored_files_ids = [sf.get("id") for sf in self._value]
return self._client.stored_files(id__in=",".join(stored_files_ids))
def clear(self) -> None:
"""
Clear the stored files from the value of the property.
Introduced in order to minimize the effect on custom scripts when converting
from `AttachmentProperty` to `StoredFileReferenceProperty`.
"""
if self.value:
self.value = []
@property
def filename(self) -> Optional[Union[str, list]]:
"""Filename or list of filenames of the file(s) stored in the property."""
if self.value:
if len(self.value) == 1:
return self.value[0].filename
else:
return [stored_file.filename for stored_file in self.value]
else:
return None
def download(self, directory: str, **kwargs):
"""Download stored files from the StoredFileReferenceProperty.
Downloads multiple files in the provided directory and names them according to the
filename. If multiple files have the same name, it makes them unique.
:param directory: Directory path
:type directory: basestring
"""
for stored_file in self.value:
filename = uniquify(os.path.join(directory, stored_file.filename))
stored_file.save_as(filename=filename, **kwargs)
def upload(self, data: Any) -> None:
"""Upload a stored file to the StoredFileReferenceProperty.
:param data: File path
:type data: basestring
:raises APIError: When unable to upload the file to KE-chain
:raises OSError: When the path to the file is incorrect or file could not be found
"""
filename = os.path.basename(data)
new_stored_file = self._client.create_stored_file(
name=filename,
scope=self.scope,
classification=StoredFileClassification.SCOPED,
category=StoredFileCategory.REFERENCED,
filepath=data,
)
if self.has_validator(SingleReferenceValidator):
# we want to replace value
self.value = [new_stored_file]
else:
if self.value:
self.value.append(new_stored_file)
else:
self.value = [new_stored_file]
|
class StoredFilesReferencesProperty(_ReferenceProperty):
'''A virtual object representing a KE-chain StoredFile References property.'''
def _retrieve_objects(self, **kwargs) -> List[StoredFile]:
'''
Retrieve a list of StoredFile.
:param kwargs: optional inputs
:return: list of StoredFile objects
'''
pass
def clear(self) -> None:
'''
Clear the stored files from the value of the property.
Introduced in order to minimize the effect on custom scripts when converting
from `AttachmentProperty` to `StoredFileReferenceProperty`.
'''
pass
@property
def filename(self) -> Optional[Union[str, list]]:
'''Filename or list of filenames of the file(s) stored in the property.'''
pass
def download(self, directory: str, **kwargs):
'''Download stored files from the StoredFileReferenceProperty.
Downloads multiple files in the provided directory and names them according to the
filename. If multiple files have the same name, it makes them unique.
:param directory: Directory path
:type directory: basestring
'''
pass
def upload(self, data: Any) -> None:
'''Upload a stored file to the StoredFileReferenceProperty.
:param data: File path
:type data: basestring
:raises APIError: When unable to upload the file to KE-chain
:raises OSError: When the path to the file is incorrect or file could not be found
'''
pass
| 7 | 6 | 13 | 1 | 7 | 5 | 2 | 0.66 | 1 | 7 | 4 | 0 | 5 | 2 | 5 | 14 | 74 | 11 | 38 | 15 | 31 | 25 | 27 | 13 | 21 | 3 | 2 | 2 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.