infrahub-testcontainers 1.5.0b1__tar.gz → 1.5.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (16) hide show
  1. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/PKG-INFO +1 -1
  2. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/container.py +144 -6
  3. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/docker-compose-cluster.test.yml +5 -0
  4. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/docker-compose.test.yml +5 -0
  5. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/helpers.py +19 -4
  6. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/models.py +8 -6
  7. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/performance_test.py +6 -4
  8. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/pyproject.toml +8 -2
  9. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/README.md +0 -0
  10. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/__init__.py +0 -0
  11. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/constants.py +0 -0
  12. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/haproxy.cfg +0 -0
  13. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/host.py +0 -0
  14. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/measurements.py +0 -0
  15. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/plugin.py +0 -0
  16. {infrahub_testcontainers-1.5.0b1 → infrahub_testcontainers-1.5.1}/infrahub_testcontainers/prometheus.yml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: infrahub-testcontainers
3
- Version: 1.5.0b1
3
+ Version: 1.5.1
4
4
  Summary: Testcontainers instance for Infrahub to easily build integration tests
5
5
  License: Apache-2.0
6
6
  Author: OpsMill
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  import os
2
4
  import shutil
3
5
  import time
@@ -72,7 +74,10 @@ class InfrahubDockerCompose(DockerCompose):
72
74
 
73
75
  @classmethod
74
76
  def init(
75
- cls, directory: Path | None = None, version: str | None = None, deployment_type: str | None = None
77
+ cls,
78
+ directory: Path | None = None,
79
+ version: str | None = None,
80
+ deployment_type: str | None = None,
76
81
  ) -> Self:
77
82
  if not directory:
78
83
  directory = Path.cwd()
@@ -84,7 +89,11 @@ class InfrahubDockerCompose(DockerCompose):
84
89
  if version == "local" and infrahub_image_version:
85
90
  version = infrahub_image_version
86
91
 
87
- compose = cls(project_name=cls.generate_project_name(), context=directory, deployment_type=deployment_type)
92
+ compose = cls(
93
+ project_name=cls.generate_project_name(),
94
+ context=directory,
95
+ deployment_type=deployment_type,
96
+ )
88
97
  compose.create_docker_file(directory=directory)
89
98
  compose.create_env_file(directory=directory, version=version)
90
99
 
@@ -152,6 +161,8 @@ class InfrahubDockerCompose(DockerCompose):
152
161
  "INFRAHUB_TESTING_TASKMGR_BACKGROUND_SVC_REPLICAS": "1",
153
162
  "PREFECT_MESSAGING_BROKER": "prefect_redis.messaging",
154
163
  "PREFECT_MESSAGING_CACHE": "prefect_redis.messaging",
164
+ "PREFECT_SERVER_EVENTS_CAUSAL_ORDERING": "prefect_redis.ordering",
165
+ "PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE": "prefect_redis.lease_storage",
155
166
  "PREFECT__SERVER_WEBSERVER_ONLY": "true",
156
167
  "PREFECT_API_DATABASE_MIGRATE_ON_START": "false",
157
168
  "PREFECT_API_BLOCKS_REGISTER_ON_START": "false",
@@ -237,7 +248,12 @@ class InfrahubDockerCompose(DockerCompose):
237
248
  for service_name, service_data in INFRAHUB_SERVICES.items()
238
249
  }
239
250
 
240
- def database_create_backup(self, backup_name: str = "neo4j_database.backup", dest_dir: Path | None = None) -> None:
251
+ def database_create_backup(
252
+ self,
253
+ backup_name: str = "neo4j_database.backup",
254
+ dest_dir: Path | None = None,
255
+ compress: bool = False,
256
+ ) -> None:
241
257
  assert self.use_neo4j_enterprise
242
258
 
243
259
  self.exec_in_container(
@@ -245,7 +261,7 @@ class InfrahubDockerCompose(DockerCompose):
245
261
  "neo4j-admin",
246
262
  "database",
247
263
  "backup",
248
- "--compress=false",
264
+ f"--compress={'true' if compress else 'false'}",
249
265
  "--to-path",
250
266
  str(self.internal_backup_dir),
251
267
  ],
@@ -279,7 +295,14 @@ class InfrahubDockerCompose(DockerCompose):
279
295
  self.start_container(service_name=service_name)
280
296
 
281
297
  self.exec_in_container(
282
- command=["cypher-shell", "-u", "neo4j", "-p", "admin", "STOP DATABASE neo4j;"],
298
+ command=[
299
+ "cypher-shell",
300
+ "-u",
301
+ "neo4j",
302
+ "-p",
303
+ "admin",
304
+ "STOP DATABASE neo4j;",
305
+ ],
283
306
  service_name=service_name,
284
307
  )
285
308
 
@@ -364,7 +387,14 @@ class InfrahubDockerCompose(DockerCompose):
364
387
  time.sleep(10)
365
388
 
366
389
  self.exec_in_container(
367
- command=["cypher-shell", "-u", "neo4j", "-p", "admin", "DROP DATABASE neo4j;"],
390
+ command=[
391
+ "cypher-shell",
392
+ "-u",
393
+ "neo4j",
394
+ "-p",
395
+ "admin",
396
+ "DROP DATABASE neo4j;",
397
+ ],
368
398
  service_name=service_name,
369
399
  )
370
400
 
@@ -513,3 +543,111 @@ class InfrahubDockerCompose(DockerCompose):
513
543
  )
514
544
  self.start()
515
545
  print("Database restored successfully")
546
+
547
+ def task_manager_create_backup(self, backup_name: str = "prefect.dump", dest_dir: Path | None = None) -> Path:
548
+ """Create a backup of the task manager PostgreSQL database using ``pg_dump``.
549
+
550
+ Args:
551
+ backup_name: Name of the archive file to create. Defaults to ``prefect.dump``.
552
+ dest_dir: Optional host directory where the backup should be copied after it is
553
+ produced. When omitted, the backup remains in ``external_backup_dir``.
554
+
555
+ Returns:
556
+ Path to the backup archive on the host filesystem.
557
+
558
+ Raises:
559
+ FileNotFoundError: If the pg_dump command completes but no archive is produced.
560
+ """
561
+
562
+ service_name = "task-manager-db"
563
+
564
+ try:
565
+ self.get_container(service_name=service_name)
566
+ except ContainerIsNotRunning:
567
+ self.start_container(service_name=service_name)
568
+
569
+ self.external_backup_dir.mkdir(parents=True, exist_ok=True)
570
+
571
+ internal_backup_path = self.internal_backup_dir / backup_name
572
+ dump_command = [
573
+ "pg_dump",
574
+ "--format=custom",
575
+ "--blobs",
576
+ "--no-owner",
577
+ "--no-privileges",
578
+ "--dbname=postgresql://postgres:postgres@localhost:5432/prefect",
579
+ f"--file={internal_backup_path}",
580
+ ]
581
+ self.exec_in_container(command=dump_command, service_name=service_name)
582
+
583
+ source_path = self.external_backup_dir / backup_name
584
+ if not source_path.exists():
585
+ raise FileNotFoundError(f"Backup file {source_path} was not created")
586
+
587
+ final_path = source_path
588
+ if dest_dir:
589
+ dest_dir.mkdir(parents=True, exist_ok=True)
590
+ if dest_dir.resolve() != self.external_backup_dir.resolve():
591
+ final_path = dest_dir / backup_name
592
+ shutil.copy(source_path, final_path)
593
+
594
+ return final_path
595
+
596
+ def task_manager_restore_backup(self, backup_file: Path) -> None:
597
+ """Restore the task manager PostgreSQL database from a ``pg_restore`` archive.
598
+
599
+ Args:
600
+ backup_file: Path to the backup archive on the host filesystem.
601
+
602
+ Raises:
603
+ FileNotFoundError: If the provided backup archive does not exist.
604
+ """
605
+
606
+ if not backup_file.exists():
607
+ raise FileNotFoundError(f"Backup file {backup_file} does not exist")
608
+
609
+ service_name = "task-manager-db"
610
+
611
+ try:
612
+ self.get_container(service_name=service_name)
613
+ except ContainerIsNotRunning:
614
+ self.start_container(service_name=service_name)
615
+
616
+ self.external_backup_dir.mkdir(parents=True, exist_ok=True)
617
+ target_path = self.external_backup_dir / backup_file.name
618
+ shutil.copy(backup_file, target_path)
619
+
620
+ admin_dsn = "postgresql://postgres:postgres@localhost:5432/postgres"
621
+ prefect_dsn = "postgresql://postgres:postgres@localhost:5432/prefect"
622
+ internal_backup_path = self.internal_backup_dir / backup_file.name
623
+
624
+ terminate_sessions_command = [
625
+ "psql",
626
+ f"--dbname={admin_dsn}",
627
+ "--command",
628
+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'prefect';",
629
+ ]
630
+ drop_database_command = [
631
+ "psql",
632
+ f"--dbname={admin_dsn}",
633
+ "--command",
634
+ "DROP DATABASE IF EXISTS prefect WITH (FORCE);",
635
+ ]
636
+ create_database_command = [
637
+ "psql",
638
+ f"--dbname={admin_dsn}",
639
+ "--command",
640
+ "CREATE DATABASE prefect OWNER postgres;",
641
+ ]
642
+ restore_command = [
643
+ "pg_restore",
644
+ "--no-owner",
645
+ "--role=postgres",
646
+ f"--dbname={prefect_dsn}",
647
+ str(internal_backup_path),
648
+ ]
649
+
650
+ self.exec_in_container(command=terminate_sessions_command, service_name=service_name)
651
+ self.exec_in_container(command=drop_database_command, service_name=service_name)
652
+ self.exec_in_container(command=create_database_command, service_name=service_name)
653
+ self.exec_in_container(command=restore_command, service_name=service_name)
@@ -184,6 +184,8 @@ services:
184
184
 
185
185
  PREFECT_MESSAGING_BROKER:
186
186
  PREFECT_MESSAGING_CACHE:
187
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING:
188
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE:
187
189
  PREFECT__SERVER_WEBSERVER_ONLY:
188
190
  PREFECT_API_DATABASE_MIGRATE_ON_START:
189
191
  PREFECT_API_BLOCKS_REGISTER_ON_START:
@@ -225,6 +227,8 @@ services:
225
227
  INFRAHUB_CACHE_ADDRESS: ${INFRAHUB_TESTING_CACHE_ADDRESS}
226
228
  PREFECT_MESSAGING_BROKER: prefect_redis.messaging
227
229
  PREFECT_MESSAGING_CACHE: prefect_redis.messaging
230
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING: prefect_redis.ordering
231
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE: prefect_redis.lease_storage
228
232
  PREFECT_REDIS_MESSAGING_HOST: "${INFRAHUB_TESTING_CACHE_ADDRESS:-cache}"
229
233
  PREFECT_REDIS_MESSAGING_DB: "1"
230
234
  PREFECT_REDIS_MESSAGING_CONSUMER_MIN_IDLE_TIME: "30"
@@ -244,6 +248,7 @@ services:
244
248
  - POSTGRES_DB=prefect
245
249
  volumes:
246
250
  - workflow_db:/var/lib/postgresql/data
251
+ - "./${INFRAHUB_TESTING_LOCAL_DB_BACKUP_DIRECTORY}:${INFRAHUB_TESTING_INTERNAL_DB_BACKUP_DIRECTORY}"
247
252
  healthcheck:
248
253
  test: ["CMD-SHELL", "pg_isready"]
249
254
  interval: 10s
@@ -95,6 +95,8 @@ services:
95
95
 
96
96
  PREFECT_MESSAGING_BROKER:
97
97
  PREFECT_MESSAGING_CACHE:
98
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING:
99
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE:
98
100
  PREFECT__SERVER_WEBSERVER_ONLY:
99
101
  PREFECT_API_DATABASE_MIGRATE_ON_START:
100
102
  PREFECT_API_BLOCKS_REGISTER_ON_START:
@@ -136,6 +138,8 @@ services:
136
138
  INFRAHUB_CACHE_ADDRESS: ${INFRAHUB_TESTING_CACHE_ADDRESS}
137
139
  PREFECT_MESSAGING_BROKER: prefect_redis.messaging
138
140
  PREFECT_MESSAGING_CACHE: prefect_redis.messaging
141
+ PREFECT_SERVER_EVENTS_CAUSAL_ORDERING: prefect_redis.ordering
142
+ PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE: prefect_redis.lease_storage
139
143
  PREFECT_REDIS_MESSAGING_HOST: "${INFRAHUB_TESTING_CACHE_ADDRESS:-cache}"
140
144
  PREFECT_REDIS_MESSAGING_DB: "1"
141
145
  PREFECT_REDIS_MESSAGING_CONSUMER_MIN_IDLE_TIME: "30"
@@ -155,6 +159,7 @@ services:
155
159
  - POSTGRES_DB=prefect
156
160
  volumes:
157
161
  - workflow_db:/var/lib/postgresql/data
162
+ - "./${INFRAHUB_TESTING_LOCAL_DB_BACKUP_DIRECTORY}:${INFRAHUB_TESTING_INTERNAL_DB_BACKUP_DIRECTORY}"
158
163
  healthcheck:
159
164
  test: ["CMD-SHELL", "pg_isready"]
160
165
  interval: 10s
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  import os
2
4
  import subprocess # noqa: S404
3
5
  import uuid
@@ -24,13 +26,21 @@ class TestInfrahubDocker:
24
26
  env["INFRAHUB_API_TOKEN"] = PROJECT_ENV_VARIABLES["INFRAHUB_TESTING_INITIAL_ADMIN_TOKEN"]
25
27
  env["INFRAHUB_MAX_CONCURRENT_EXECUTION"] = "1"
26
28
  result = subprocess.run( # noqa: S602
27
- f"infrahubctl run {script}", shell=True, capture_output=True, text=True, env=env, check=False
29
+ f"infrahubctl run {script}",
30
+ shell=True,
31
+ capture_output=True,
32
+ text=True,
33
+ env=env,
34
+ check=False,
28
35
  )
29
36
  return result.stdout
30
37
 
31
38
  @staticmethod
32
39
  def execute_command(
33
- command: str, address: str, concurrent_execution: int = 10, pagination_size: int = 50
40
+ command: str,
41
+ address: str,
42
+ concurrent_execution: int = 10,
43
+ pagination_size: int = 50,
34
44
  ) -> subprocess.CompletedProcess[str]:
35
45
  env = os.environ.copy()
36
46
  env["INFRAHUB_ADDRESS"] = address
@@ -79,7 +89,9 @@ class TestInfrahubDocker:
79
89
  deployment_type: str | None,
80
90
  ) -> InfrahubDockerCompose:
81
91
  return InfrahubDockerCompose.init(
82
- directory=tmp_directory, version=infrahub_version, deployment_type=deployment_type
92
+ directory=tmp_directory,
93
+ version=infrahub_version,
94
+ deployment_type=deployment_type,
83
95
  )
84
96
 
85
97
  @pytest.fixture(scope="class")
@@ -90,7 +102,10 @@ class TestInfrahubDocker:
90
102
  tests_failed_during_class = request.session.testsfailed - tests_failed_before_class
91
103
  if tests_failed_during_class > 0:
92
104
  stdout, stderr = infrahub_compose.get_logs("infrahub-server", "task-worker")
93
- warnings.warn(f"Container logs:\nStdout:\n{stdout}\nStderr:\n{stderr}", stacklevel=2)
105
+ warnings.warn(
106
+ f"Container logs:\nStdout:\n{stdout}\nStderr:\n{stderr}",
107
+ stacklevel=2,
108
+ )
94
109
  infrahub_compose.stop()
95
110
 
96
111
  request.addfinalizer(cleanup)
@@ -1,6 +1,8 @@
1
- from datetime import UTC, datetime
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timezone
2
4
  from enum import Enum
3
- from typing import Any
5
+ from typing import Any, Union
4
6
 
5
7
  from pydantic import BaseModel, Field
6
8
 
@@ -15,24 +17,24 @@ class ContextUnit(str, Enum):
15
17
  class MeasurementDefinition(BaseModel):
16
18
  name: str
17
19
  description: str
18
- dimensions: list[str] = Field(default_factory=dict)
20
+ dimensions: list[str] = Field(default_factory=list)
19
21
  unit: ContextUnit
20
22
 
21
23
 
22
24
  class InfrahubResultContext(BaseModel):
23
25
  name: str
24
- value: int | float | str
26
+ value: Union[int, float, str]
25
27
  unit: ContextUnit
26
28
 
27
29
 
28
30
  class InfrahubActiveMeasurementItem(BaseModel):
29
31
  definition: MeasurementDefinition
30
- start_time: datetime = Field(default_factory=lambda: datetime.now(UTC))
32
+ start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
31
33
  context: dict[str, Any] = Field(default_factory=dict)
32
34
 
33
35
 
34
36
  class InfrahubMeasurementItem(BaseModel):
35
37
  name: str
36
- value: int | float | str
38
+ value: Union[int, float, str]
37
39
  unit: ContextUnit
38
40
  context: dict[str, Any] = Field(default_factory=dict)
@@ -1,6 +1,8 @@
1
+ from __future__ import annotations
2
+
1
3
  import hashlib
2
4
  import json
3
- from datetime import UTC, datetime
5
+ from datetime import datetime, timezone
4
6
  from types import TracebackType
5
7
  from typing import Any
6
8
 
@@ -35,7 +37,7 @@ class InfrahubPerformanceTest:
35
37
  self.env_vars = {}
36
38
  self.project_name = ""
37
39
  self.test_info = {}
38
- self.start_time = datetime.now(UTC)
40
+ self.start_time = datetime.now(timezone.utc)
39
41
  self.end_time: datetime | None = None
40
42
  self.results_url = results_url
41
43
  self.scraper_endpoint = ""
@@ -57,7 +59,7 @@ class InfrahubPerformanceTest:
57
59
 
58
60
  def finalize(self, session: pytest.Session) -> None:
59
61
  if self.initialized:
60
- self.end_time = datetime.now(UTC)
62
+ self.end_time = datetime.now(timezone.utc)
61
63
  self.extract_test_session_information(session)
62
64
  self.send_results()
63
65
 
@@ -129,7 +131,7 @@ class InfrahubPerformanceTest:
129
131
  if not exc_type and self.active_measurements:
130
132
  self.add_measurement(
131
133
  definition=self.active_measurements.definition,
132
- value=(datetime.now(UTC) - self.active_measurements.start_time).total_seconds() * 1000,
134
+ value=(datetime.now(timezone.utc) - self.active_measurements.start_time).total_seconds() * 1000,
133
135
  context=self.active_measurements.context,
134
136
  )
135
137
 
@@ -1,11 +1,11 @@
1
1
  [project]
2
2
  name = "infrahub-testcontainers"
3
- version = "1.5.0b1"
3
+ version = "1.5.1"
4
4
  requires-python = ">=3.9"
5
5
 
6
6
  [tool.poetry]
7
7
  name = "infrahub-testcontainers"
8
- version = "1.5.0b1"
8
+ version = "1.5.1"
9
9
  description = "Testcontainers instance for Infrahub to easily build integration tests"
10
10
  authors = ["OpsMill <info@opsmill.com>"]
11
11
  readme = "README.md"
@@ -43,3 +43,9 @@ prefect-client = "3.4.23"
43
43
 
44
44
  [tool.poetry.group.dev.dependencies]
45
45
  rich = "^13.9.4"
46
+ pytest-cov = "7.0.0"
47
+ pytest-xdist = "~3.4"
48
+
49
+ [tool.ruff]
50
+ line-length = 120
51
+ target-version = "py39"