Source code for pytest_databases.docker.bigquery

"""Google BigQuery emulator container service fixtures."""

from __future__ import annotations

import email.message
import http.client
import importlib
import io
import json
import os
import urllib.error
import warnings
from contextlib import closing, contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any

import pytest

from pytest_databases.helpers import get_xdist_worker_num, http_request, resolve_legacy_platform
from pytest_databases.types import ServiceContainer, XdistIsolationLevel

if TYPE_CHECKING:
    from collections.abc import Generator

    from docker.models.containers import Container

    from pytest_databases._service import DockerService

__all__ = (
    "DEFAULT_BIGQUERY_IMAGE",
    "BigQueryService",
    "bigquery_client",
    "bigquery_image",
    "bigquery_platform",
    "bigquery_service",
    "platform",
    "provide_bigquery_client",
    "provide_bigquery_service",
    "query_bigquery_emulator",
    "xdist_bigquery_isolation_level",
)

DEFAULT_BIGQUERY_IMAGE = "ghcr.io/goccy/bigquery-emulator:0.8.1"


[docs] @dataclass(init=False) class BigQueryService(ServiceContainer): """Connection metadata for a Google BigQuery emulator container service. ``dataset`` is the dataset reserved for the current test process. Under ``pytest-xdist`` with ``database`` isolation, workers share one emulator and each gets its own dataset (``test-dataset_<worker>``); otherwise it is ``test-dataset``. """ project: str dataset: str
[docs] def __init__( self, container: Container, host: str, port: int, project: str, dataset: str, credentials: Any = None, ) -> None: """Initialize the service metadata. Args: container: Running emulator container. host: Host name the emulator is reachable on. port: Published emulator HTTP port. project: Emulator project ID. dataset: Dataset reserved for the current test process. credentials: Deprecated and ignored; credentials are built on access by :attr:`credentials`. """ super().__init__(container=container, host=host, port=port) self.project = project self.dataset = dataset if credentials is not None: warnings.warn( "Passing 'credentials' to BigQueryService is deprecated in v0.20.0 and will be removed in v1.0.0. " "The argument is ignored.", DeprecationWarning, stacklevel=2, )
@property def endpoint(self) -> str: """The HTTP API endpoint URL for the BigQuery emulator.""" return f"http://{self.host}:{self.port}" @property def credentials(self) -> Any: """Deprecated ``AnonymousCredentials`` instance for the BigQuery emulator.""" warnings.warn( "BigQueryService.credentials is deprecated in v0.20.0 and will be removed in v1.0.0. " "Construct your own google.auth.credentials.AnonymousCredentials() instance.", DeprecationWarning, stacklevel=2, ) creds_mod: Any = importlib.import_module("google.auth.credentials") return creds_mod.AnonymousCredentials() @property def client_options(self) -> Any: """Deprecated ``ClientOptions`` configured with the emulator API endpoint.""" warnings.warn( "BigQueryService.client_options is deprecated in v0.20.0 and will be removed in v1.0.0. " "Construct ClientOptions(api_endpoint=service.endpoint) directly.", DeprecationWarning, stacklevel=2, ) options_mod: Any = importlib.import_module("google.api_core.client_options") return options_mod.ClientOptions(api_endpoint=self.endpoint)
[docs] def is_healthy(self, *, timeout: float = 5.0) -> bool: """Return ``True`` when ``SELECT 1`` completes successfully against the emulator.""" try: payload = query_bigquery_emulator(self.host, self.port, self.project, "SELECT 1", timeout=timeout) except (RuntimeError, urllib.error.URLError, TimeoutError, OSError, ValueError, http.client.HTTPException): return False if payload.get("jobComplete") is not True: return False try: return bool(payload["rows"][0]["f"][0]["v"] == "1") except (KeyError, IndexError, TypeError): return False
[docs] def query_bigquery_emulator( host: str, port: int, project: str, sql: str, *, timeout: float = 2.0, ) -> dict[str, Any]: """Execute a SQL query against the BigQuery emulator REST API bypassing ambient proxies.""" body = json.dumps({"query": sql, "useLegacySql": False}).encode("utf-8") url = f"http://{host}:{port}/bigquery/v2/projects/{project}/queries" status, resp_body = http_request( url, method="POST", data=body, headers={"Content-Type": "application/json"}, timeout=timeout, ) if status >= 400: raise urllib.error.HTTPError(url, status, f"HTTP {status}", email.message.Message(), io.BytesIO(resp_body)) parsed = json.loads(resp_body.decode("utf-8")) if not isinstance(parsed, dict): msg = f"Expected JSON object from BigQuery emulator query endpoint, got {type(parsed).__name__}" raise TypeError(msg) return parsed
[docs] @contextmanager def provide_bigquery_service( docker_service: DockerService, isolation_level: XdistIsolationLevel, image: str, platform_arch: str | None, ) -> Generator[BigQueryService, None, None]: """Start and yield a BigQuery emulator service container. Args: docker_service: Docker service manager. isolation_level: xdist isolation mode. image: BigQuery emulator image name. platform_arch: Target container platform architecture. Yields: A running :class:`BigQueryService` instance. """ project = "emulator-test-project" default_dataset = "test-dataset" dataset = default_dataset container_name = "bigquery" worker_num = get_xdist_worker_num() if worker_num is not None: if isolation_level == "server": container_name += f"_{worker_num}" else: dataset = f"{default_dataset}_{worker_num}" def check(_service: ServiceContainer) -> bool: try: payload = query_bigquery_emulator( _service.host, _service.port, project, "SELECT 1 as one", ) except ( urllib.error.URLError, json.JSONDecodeError, RuntimeError, TimeoutError, OSError, http.client.HTTPException, ): return False if payload.get("jobComplete") is not True: return False try: return bool(payload["rows"][0]["f"][0]["v"] == "1") except (KeyError, IndexError, TypeError): return False with docker_service.run( image=image, command=f"--project={project} --dataset={default_dataset}", name=container_name, check=check, env={ "PROJECT_ID": project, "DATASET_NAME": default_dataset, }, container_port=9050, timeout=60, transient=worker_num is not None and isolation_level == "server", platform=platform_arch, ) as service: if dataset != default_dataset: _ensure_bigquery_dataset(service.host, service.port, project, dataset) yield BigQueryService( host=service.host, port=service.port, container=service.container, project=project, dataset=dataset, )
[docs] @contextmanager def provide_bigquery_client(bigquery_service: BigQueryService) -> Generator[Any, None, None]: """Emit a deprecation warning and yield a ``google.cloud.bigquery.Client`` instance. Yields: A configured ``bigquery.Client`` connected to ``bigquery_service``. """ warnings.warn( "The 'bigquery_client' fixture is deprecated in v0.20.0 and will be removed in v1.0.0. " "Use 'bigquery_service' and construct your own google.cloud.bigquery.Client.", DeprecationWarning, stacklevel=3, ) bq_mod: Any = importlib.import_module("google.cloud.bigquery") options_mod: Any = importlib.import_module("google.api_core.client_options") creds_mod: Any = importlib.import_module("google.auth.credentials") client = bq_mod.Client( project=bigquery_service.project, client_options=options_mod.ClientOptions(api_endpoint=bigquery_service.endpoint), credentials=creds_mod.AnonymousCredentials(), ) with closing(client): yield client
[docs] @pytest.fixture(scope="session") def xdist_bigquery_isolation_level() -> XdistIsolationLevel: """Return the default pytest-xdist isolation level for BigQuery (``server``).""" return "server"
[docs] @pytest.fixture(scope="session") def bigquery_image() -> str: """Return the BigQuery emulator container image tag, honoring ``BIGQUERY_IMAGE``.""" return os.getenv("BIGQUERY_IMAGE", DEFAULT_BIGQUERY_IMAGE)
[docs] @pytest.fixture(scope="session") def bigquery_platform(request: pytest.FixtureRequest) -> str | None: """Return the container platform for the BigQuery emulator, which publishes x86_64 images only.""" return resolve_legacy_platform(request, "bigquery_platform", "linux/x86_64")
[docs] @pytest.fixture(scope="session") def platform() -> str: """Return the legacy ``linux/x86_64`` platform string. .. deprecated:: 0.20.0 Use ``bigquery_platform`` instead. ``platform`` will be removed in v1.0.0. """ warnings.warn( "The 'platform' fixture is deprecated in v0.20.0 and will be removed in v1.0.0. " "Use 'mysql_platform', 'dolt_platform', or 'bigquery_platform' instead.", DeprecationWarning, stacklevel=2, ) return "linux/x86_64"
[docs] @pytest.fixture(scope="session") def bigquery_service( docker_service: DockerService, xdist_bigquery_isolation_level: XdistIsolationLevel, bigquery_image: str, bigquery_platform: str | None, ) -> Generator[BigQueryService, None, None]: """Provide a session-scoped BigQuery emulator service. Yields: A running :class:`BigQueryService` instance. """ with provide_bigquery_service( docker_service, xdist_bigquery_isolation_level, bigquery_image, bigquery_platform, ) as service: yield service
[docs] @pytest.fixture(scope="session") def bigquery_client(bigquery_service: BigQueryService) -> Generator[Any, None, None]: """Provide a deprecated ``google.cloud.bigquery.Client`` connected to the emulator. Yields: A configured ``bigquery.Client`` instance. """ with provide_bigquery_client(bigquery_service) as client: yield client
def _ensure_bigquery_dataset(host: str, port: int, project: str, dataset: str, *, timeout: float = 5.0) -> None: body = json.dumps({"datasetReference": {"projectId": project, "datasetId": dataset}}).encode("utf-8") url = f"http://{host}:{port}/bigquery/v2/projects/{project}/datasets" status, resp_body = http_request( url, method="POST", data=body, headers={"Content-Type": "application/json"}, timeout=timeout, ) if 200 <= status < 300 or status == 409: return raise urllib.error.HTTPError(url, status, f"HTTP {status}", email.message.Message(), io.BytesIO(resp_body))