|
| 1 | +import os |
| 2 | +import socket |
| 3 | +from uuid import uuid4 |
| 4 | + |
| 5 | +import boto3 |
| 6 | +import pytest |
| 7 | + |
| 8 | +LOCALSTACK_ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") |
| 9 | +AWS_REGION = os.environ.get("AWS_REGION", "us-east-1") |
| 10 | + |
| 11 | +os.environ.setdefault("AWS_ACCESS_KEY_ID", "test") |
| 12 | +os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "test") |
| 13 | +os.environ.setdefault("AWS_DEFAULT_REGION", AWS_REGION) |
| 14 | +os.environ.setdefault("AWS_REGION", AWS_REGION) |
| 15 | +os.environ.setdefault("AWS_ENDPOINT_URL", LOCALSTACK_ENDPOINT) |
| 16 | +os.environ.setdefault("AWS_EC2_METADATA_DISABLED", "true") |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture |
| 20 | +def aws_test_env(monkeypatch): |
| 21 | + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test") |
| 22 | + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test") |
| 23 | + monkeypatch.setenv("AWS_DEFAULT_REGION", AWS_REGION) |
| 24 | + monkeypatch.setenv("AWS_REGION", AWS_REGION) |
| 25 | + monkeypatch.setenv("AWS_ENDPOINT_URL", LOCALSTACK_ENDPOINT) |
| 26 | + |
| 27 | + |
| 28 | +@pytest.fixture |
| 29 | +def localstack_available(aws_test_env): |
| 30 | + host, port = _host_port_from_endpoint(LOCALSTACK_ENDPOINT) |
| 31 | + try: |
| 32 | + with socket.create_connection((host, port), timeout=0.5): |
| 33 | + return True |
| 34 | + except OSError: |
| 35 | + pytest.skip(f"LocalStack is not available at {LOCALSTACK_ENDPOINT}") |
| 36 | + |
| 37 | + |
| 38 | +@pytest.fixture |
| 39 | +def local_sqs_client(localstack_available): |
| 40 | + return boto3.client("sqs", region_name=AWS_REGION, endpoint_url=LOCALSTACK_ENDPOINT) |
| 41 | + |
| 42 | + |
| 43 | +@pytest.fixture |
| 44 | +def unique_queue_name(): |
| 45 | + def build(prefix): |
| 46 | + return f"{prefix}-{uuid4().hex}" |
| 47 | + |
| 48 | + return build |
| 49 | + |
| 50 | + |
| 51 | +def _host_port_from_endpoint(endpoint): |
| 52 | + without_scheme = endpoint.removeprefix("http://").removeprefix("https://") |
| 53 | + host_port = without_scheme.split("/", 1)[0] |
| 54 | + if ":" not in host_port: |
| 55 | + return host_port, 443 if endpoint.startswith("https://") else 80 |
| 56 | + host, port = host_port.rsplit(":", 1) |
| 57 | + return host, int(port) |
0 commit comments