Skip to content

Commit c4da514

Browse files
committed
Add more functional tests
1 parent 4081ac9 commit c4da514

File tree

10 files changed

+273
-31
lines changed

10 files changed

+273
-31
lines changed

backend/infrahub/core/constants/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ class EventType(InfrahubStringEnum):
6363

6464
REPOSITORY_UPDATE_COMMIT = f"{EVENT_NAMESPACE}.repository.update_commit"
6565

66+
ARTIFACT_CREATED = f"{EVENT_NAMESPACE}.artifact.created"
67+
ARTIFACT_UPDATED = f"{EVENT_NAMESPACE}.artifact.updated"
68+
6669

6770
class PermissionLevel(enum.Flag):
6871
READ = 1

backend/infrahub/git/integrator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1150,7 +1150,7 @@ async def execute_python_check(
11501150

11511151
@task(name="python-transform-execute", task_run_name="Execute Python Transform", cache_policy=NONE) # type: ignore[arg-type]
11521152
async def execute_python_transform(
1153-
self, branch_name: str, commit: str, location: str, client: InfrahubClient, data: Optional[dict] = None
1153+
self, branch_name: str, commit: str, location: str, client: InfrahubClient, data: dict | None = None
11541154
) -> Any:
11551155
"""Execute A Python Transform stored in the repository."""
11561156
log = get_run_logger()

backend/infrahub/message_bus/operations/event/worker.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,3 @@
77
@flow(name="event-worker-newprimary-api")
88
async def new_primary_api(message: messages.EventWorkerNewPrimaryAPI, service: InfrahubServices) -> None:
99
service.log.info("api_worker promoted to primary", worker_id=message.worker_id)
10-
11-
# NOTE Should we remove this message ?

backend/infrahub/webhook/models.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,19 @@
66
from typing import TYPE_CHECKING, Any, Optional, Union
77
from uuid import UUID, uuid4
88

9-
from infrahub_sdk.protocols import CoreCustomWebhook, CoreStandardWebhook, CoreTransformPython, CoreWebhook
109
from pydantic import BaseModel, ConfigDict, Field, computed_field
1110
from typing_extensions import Self
1211

1312
from infrahub.core import registry
1413
from infrahub.core.constants import InfrahubKind
1514
from infrahub.core.timestamp import Timestamp
1615
from infrahub.git.repository import InfrahubReadOnlyRepository, InfrahubRepository
17-
from infrahub.transformations.constants import DEFAULT_TRANSFORM_TIMEOUT
1816
from infrahub.trigger.models import EventTrigger, ExecuteWorkflow, TriggerDefinition, TriggerType
1917
from infrahub.workflows.catalogue import WEBHOOK_PROCESS
2018

2119
if TYPE_CHECKING:
2220
from httpx import Response
21+
from infrahub_sdk.protocols import CoreCustomWebhook, CoreStandardWebhook, CoreTransformPython, CoreWebhook
2322

2423
from infrahub.services import InfrahubServices
2524

@@ -79,15 +78,17 @@ class EventContext(BaseModel):
7978

8079
@classmethod
8180
def from_event(cls, event_id: str, event_type: str, event_occured_at: str, event_payload: dict[str, Any]) -> Self:
82-
"""Extract the context from the raw eventwe are getting from Prefect."""
81+
"""Extract the context from the raw event we are getting from Prefect."""
8382

8483
infrahub_context: dict[str, Any] = event_payload.get("context", {})
8584
account_info: dict[str, Any] = infrahub_context.get("account", {})
8685
branch_info: dict[str, Any] = infrahub_context.get("branch", {})
8786

8887
return cls(
8988
id=event_id,
90-
branch=branch_info.get("name") if branch_info else None,
89+
branch=branch_info.get("name")
90+
if branch_info and branch_info.get("name") != registry.get_global_branch().name
91+
else None,
9192
account_id=account_info.get("account_id"),
9293
occured_at=event_occured_at,
9394
event=event_type,
@@ -114,10 +115,16 @@ def _assign_headers(self) -> None:
114115
def webhook_type(self) -> str:
115116
return self.__class__.__name__
116117

117-
async def send(self, data: dict[str, Any], context: EventContext, service: InfrahubServices) -> Response:
118+
async def prepare(self, data: dict[str, Any], context: EventContext, service: InfrahubServices) -> None:
118119
await self._prepare_payload(data=data, context=context, service=service)
119120
self._assign_headers()
120-
return await service.http.post(url=self.url, json=self._payload, headers=self._headers)
121+
122+
async def send(self, data: dict[str, Any], context: EventContext, service: InfrahubServices) -> Response:
123+
await self.prepare(data=data, context=context, service=service)
124+
return await service.http.post(url=self.url, json=self.get_payload(), headers=self._headers)
125+
126+
def get_payload(self) -> dict[str, Any]:
127+
return self._payload
121128

122129
def to_cache(self) -> dict[str, Any]:
123130
return self.model_dump()
@@ -179,6 +186,7 @@ class TransformWebhook(Webhook):
179186
transform_name: str = Field(...)
180187
transform_class: str = Field(...)
181188
transform_file: str = Field(...)
189+
transform_timeout: int = Field(...)
182190

183191
async def _prepare_payload(self, data: dict[str, Any], context: EventContext, service: InfrahubServices) -> None:
184192
repo: Union[InfrahubReadOnlyRepository, InfrahubRepository]
@@ -197,17 +205,11 @@ async def _prepare_payload(self, data: dict[str, Any], context: EventContext, se
197205
service=service,
198206
)
199207

200-
default_branch = repo.default_branch
201-
commit = repo.get_commit_value(branch_name=default_branch)
202-
203-
timeout = DEFAULT_TRANSFORM_TIMEOUT
204-
if transform := await service.client.get(
205-
kind=CoreTransformPython, name__value=self.transform_name, raise_when_missing=False
206-
):
207-
timeout = transform.timeout.value
208+
branch = context.branch or repo.default_branch
209+
commit = repo.get_commit_value(branch_name=branch)
208210

209-
self._payload = await repo.execute_python_transform.with_options(timeout_seconds=timeout)(
210-
branch_name=default_branch,
211+
self._payload = await repo.execute_python_transform.with_options(timeout_seconds=self.transform_timeout)(
212+
branch_name=branch,
211213
commit=commit,
212214
location=f"{self.transform_file}::{self.transform_class}",
213215
data={"data": data, **context.model_dump()},
@@ -227,4 +229,5 @@ def from_object(cls, obj: CoreCustomWebhook, transform: CoreTransformPython) ->
227229
transform_name=transform.name.value,
228230
transform_class=transform.class_name.value,
229231
transform_file=transform.file_path.value,
232+
transform_timeout=transform.timeout.value,
230233
)

backend/infrahub/webhook/tasks.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -120,13 +120,13 @@ async def configure_webhook_all(service: InfrahubServices) -> None:
120120

121121

122122
@flow(name="webhook-setup-automation-one", flow_run_name="Configuration webhook automation for one webhook")
123-
async def configure_webhook_one(event_data: dict, service: InfrahubServices) -> None:
123+
async def configure_webhook_one(event_type: str, event_data: dict, service: InfrahubServices) -> None:
124124
log = get_run_logger()
125125

126126
webhook = await service.client.get(kind=CoreWebhook, id=event_data["node_id"])
127127
trigger = WebhookTriggerDefinition.from_object(webhook)
128128

129-
# TODO: Need to check in the event if the node was created, updated or deleted
129+
delete_automation: bool = "infrahub.node.deleted" in event_type
130130

131131
async with get_client(sync_client=False) as prefect_client:
132132
# Query the deployment associated with the trigger to have its ID
@@ -143,10 +143,14 @@ async def configure_webhook_one(event_data: dict, service: InfrahubServices) ->
143143

144144
existing_automations = await prefect_client.read_automations_by_name(trigger.generate_name())
145145

146-
if existing_automations:
147-
automation = existing_automations[0]
148-
await prefect_client.update_automation(automation_id=automation.id, automation=automation)
146+
if existing_automations and not delete_automation:
147+
existing_automation = existing_automations[0]
148+
await prefect_client.update_automation(automation_id=existing_automation.id, automation=automation)
149149
log.info(f"Automation {trigger.generate_name()} updated")
150+
elif existing_automations and delete_automation:
151+
existing_automation = existing_automations[0]
152+
await prefect_client.delete_automation(automation_id=existing_automation.id)
153+
log.info(f"Automation {trigger.generate_name()} deleted")
150154
else:
151155
await prefect_client.create_automation(automation=automation)
152156
log.info(f"Automation {trigger.generate_name()} created")

backend/infrahub/webhook/triggers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@
1616
ExecuteWorkflow(
1717
workflow=WEBHOOK_CONFIGURE_ONE,
1818
parameters={
19+
"event_type": "{{ event.event }}",
1920
"event_data": {
2021
"__prefect_kind": "json",
2122
"value": {"__prefect_kind": "jinja", "template": "{{ event.payload['data'] | tojson }}"},
22-
}
23+
},
2324
},
2425
),
2526
],

backend/tests/fixtures/repos/car-dealership/initial__main/.infrahub.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ python_transforms:
2929
- name: CarSpecMarkdown
3030
class_name: CarSpecMarkdown
3131
file_path: "transforms/car_spec_markdown.py"
32+
- name: WebhookTransformer
33+
class_name: WebhookTransformer
34+
file_path: "transforms/webhook_transformer.py"
3235

3336
artifact_definitions:
3437
- name: "Ownership report"
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from typing import Any
2+
3+
from infrahub_sdk.transforms import InfrahubTransform
4+
5+
6+
class WebhookTransformer(InfrahubTransform):
7+
query = "person_with_cars"
8+
timeout = 5
9+
10+
async def transform(self, data: dict[str, Any]) -> dict[str, Any]:
11+
return {key.upper(): value for key, value in data.items()}

backend/tests/functional/webhook/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)