|
| 1 | +# |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 3 | +# not use this file except in compliance with the License. You may obtain |
| 4 | +# a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 10 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 11 | +# License for the specific language governing permissions and limitations |
| 12 | +# under the License. |
| 13 | + |
| 14 | +from http.client import HTTPException |
| 15 | +from typing import Optional |
| 16 | +from urllib.error import URLError |
| 17 | +from urllib.request import urlopen |
| 18 | + |
| 19 | +from testcontainers.core.container import DockerContainer |
| 20 | +from testcontainers.core.waiting_utils import wait_container_is_ready |
| 21 | + |
| 22 | + |
| 23 | +class N8nContainer(DockerContainer): |
| 24 | + """ |
| 25 | + n8n workflow automation container. |
| 26 | +
|
| 27 | + Example: |
| 28 | +
|
| 29 | + .. doctest:: |
| 30 | +
|
| 31 | + >>> from testcontainers.n8n import N8nContainer |
| 32 | +
|
| 33 | + >>> with N8nContainer() as n8n: |
| 34 | + ... url = n8n.get_url() |
| 35 | + ... assert url.startswith("http") |
| 36 | + """ |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + image: str = "docker.n8n.io/n8nio/n8n:latest", |
| 41 | + port: int = 5678, |
| 42 | + encryption_key: Optional[str] = None, |
| 43 | + **kwargs, |
| 44 | + ) -> None: |
| 45 | + super().__init__(image, **kwargs) |
| 46 | + self.port = port |
| 47 | + self.encryption_key = encryption_key |
| 48 | + self.with_exposed_ports(self.port) |
| 49 | + |
| 50 | + def _configure(self) -> None: |
| 51 | + self.with_env("N8N_PORT", str(self.port)) |
| 52 | + self.with_env("N8N_DIAGNOSTICS_ENABLED", "false") |
| 53 | + if self.encryption_key: |
| 54 | + self.with_env("N8N_ENCRYPTION_KEY", self.encryption_key) |
| 55 | + |
| 56 | + def get_url(self) -> str: |
| 57 | + host = self.get_container_host_ip() |
| 58 | + port = self.get_exposed_port(self.port) |
| 59 | + return f"http://{host}:{port}" |
| 60 | + |
| 61 | + def get_webhook_url(self) -> str: |
| 62 | + return f"{self.get_url()}/webhook-test" |
| 63 | + |
| 64 | + @wait_container_is_ready(HTTPException, URLError, ConnectionError) |
| 65 | + def _healthcheck(self) -> None: |
| 66 | + url = f"{self.get_url()}/healthz" |
| 67 | + with urlopen(url, timeout=5) as res: |
| 68 | + if res.status > 299: |
| 69 | + raise HTTPException() |
| 70 | + |
| 71 | + def start(self) -> "N8nContainer": |
| 72 | + super().start() |
| 73 | + self._healthcheck() |
| 74 | + return self |
0 commit comments