:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(batch-exports): add a bigquery connection test for destinations that create their dataset (#115547)
Tom Owersb7045a5a9840
diff --git a/products/batch_exports/backend/destination_tests/__init__.py b/products/batch_exports/backend/destination_tests/__init__.pyindex ad8d97aa47bd..6401d256665e 100644--- a/products/batch_exports/backend/destination_tests/__init__.py+++ b/products/batch_exports/backend/destination_tests/__init__.py@@ -7,6 +7,9 @@ def get_destination_test() -> DestinationTest:"""Resolve a destination to its corresponding `DestinationTest` implementation.+ `destination` is a batch export destination type, or the key of a destination test variant+ that is not a batch export destination (`BigQueryCreateDataset`).+Per-branch deferred imports: each destination test module pulls a heavy vendor SDK(databricks, google-cloud-bigquery, snowflake, etc.). Importing them lazily keeps theSDKs off the API import path — only the requested destination's SDK loads.@@ -23,6 +26,13 @@ def get_destination_test(from products.batch_exports.backend.destination_tests.bigquery import BigQueryDestinationTest # noqa: PLC0415return BigQueryDestinationTest()+ elif destination == "BigQueryCreateDataset":+ # Not a batch export destination: batch exports require the dataset to exist.+ from products.batch_exports.backend.destination_tests.bigquery_create_dataset import ( # noqa: PLC0415+ BigQueryCreateDatasetDestinationTest,+ )++ return BigQueryCreateDatasetDestinationTest()elif destination == "Snowflake":from products.batch_exports.backend.destination_tests.snowflake import SnowflakeDestinationTest # noqa: PLC0415diff --git a/products/batch_exports/backend/destination_tests/bigquery_create_dataset.py b/products/batch_exports/backend/destination_tests/bigquery_create_dataset.pynew file mode 100644index 000000000000..7d8c303e3c01--- /dev/null+++ b/products/batch_exports/backend/destination_tests/bigquery_create_dataset.py@@ -0,0 +1,292 @@+import typing+import asyncio+import urllib.parse+import collections.abc++import requests+import google.auth.exceptions+import google.auth.transport.requests+from google.api_core.exceptions import NotFound+from google.oauth2 import service_account++from posthog.models.integration import GoogleCloudServiceAccountIntegration+from posthog.models.integration.google_cloud import require_google_token_uri++from products.batch_exports.backend.destination_tests.base import DestinationTestStep, DestinationTestStepResult, Status+from products.batch_exports.backend.destination_tests.bigquery import (+ BigQueryDatasetTestStep,+ BigQueryDestinationTest,+ BigQueryImpersonateServiceAccountTestStep,+ BigQueryProjectTestStep,+ BigQueryTableTestStep,+ BigQueryVerifyServiceAccountOwnershipTestStep,+ ServiceAccountInfo,+ get_client,+)+from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import impersonate_service_account++if typing.TYPE_CHECKING:+ from google.auth.credentials import Credentials++# Impersonated BigQuery credentials only carry the bigquery scope, which Cloud Resource Manager rejects.+IAM_CHECK_SCOPES = ("https://www.googleapis.com/auth/cloud-platform.read-only",)+IAM_CHECK_TIMEOUT_SECONDS = 30++JOBS_CREATE_PERMISSION = "bigquery.jobs.create"+DATASETS_CREATE_PERMISSION = "bigquery.datasets.create"+++def get_iam_check_credentials(+ integration: GoogleCloudServiceAccountIntegration | None,+ service_account_info: ServiceAccountInfo | None,+) -> "Credentials":+ """Get credentials for the service account with a scope that allows `projects.testIamPermissions`."""+ if integration is not None:+ if integration.has_key():+ return service_account.Credentials.from_service_account_info(+ integration.service_account_info, scopes=list(IAM_CHECK_SCOPES)+ )+ return impersonate_service_account(integration, scopes=IAM_CHECK_SCOPES)++ if service_account_info is not None:+ return service_account.Credentials.from_service_account_info(+ {**service_account_info, "token_uri": require_google_token_uri(service_account_info["token_uri"])},+ scopes=list(IAM_CHECK_SCOPES),+ )++ raise ValueError("Either integration or service account information must be defined")+++def is_service_disabled_error(response: requests.Response) -> bool:+ """Return whether an error response says that the API is disabled in the project.++ Google reports this as a `PERMISSION_DENIED` error with a `google.rpc.ErrorInfo` detail whose+ reason is `SERVICE_DISABLED`. Other 403 errors, such as a disabled billing account, also say+ "disabled" in the message, so only the structured reason is reliable.+ """+ try:+ body = response.json()+ except ValueError:+ return False++ error = body.get("error") if isinstance(body, dict) else None+ if not isinstance(error, dict) or error.get("status") != "PERMISSION_DENIED":+ return False++ details = error.get("details")+ if not isinstance(details, list):+ return False++ return any(+ isinstance(detail, dict)+ and detail.get("@type") == "type.googleapis.com/google.rpc.ErrorInfo"+ and detail.get("reason") == "SERVICE_DISABLED"+ for detail in details+ )+++def dataset_exists(+ project_id: str | None,+ dataset_id: str,+ integration: GoogleCloudServiceAccountIntegration | None,+ service_account_info: ServiceAccountInfo | None,+) -> bool:+ client = get_client(project_id, integration, service_account_info)+ try:+ _ = client.sync_client.get_dataset(dataset_id)+ except NotFound:+ return False+ return True+++class BigQueryProjectPermissionsTestStep(DestinationTestStep):+ """Test whether a service account has the project permissions to create a dataset and run jobs.++ The service account always needs `bigquery.jobs.create` to run load, copy and merge jobs. It+ also needs `bigquery.datasets.create` on the project when the dataset does not exist yet.++ Attributes:+ project_id: ID of the BigQuery project we are checking.+ dataset_id: ID of the dataset that is created if it does not exist.+ integration: Integration with service account configuration.+ service_account_info: Service account credentials used when there is no integration.+ """++ name = "Verify BigQuery project permissions"+ description = (+ "Ensure the service account can run BigQuery jobs in the configured project, "+ "and can create the configured dataset if it does not exist."+ )++ def __init__(+ self,+ project_id: str | None = None,+ dataset_id: str | None = None,+ integration: GoogleCloudServiceAccountIntegration | None = None,+ service_account_info: ServiceAccountInfo | None = None,+ ) -> None:+ super().__init__()+ self.project_id = project_id+ self.dataset_id = dataset_id+ self.integration = integration+ self.service_account_info = service_account_info++ def _is_configured(self) -> bool:+ """Ensure required configuration parameters are set."""+ if (+ self.project_id is None+ or self.dataset_id is None+ or (self.service_account_info is None and self.integration is None)+ ):+ return False+ return True++ async def _run_step(self) -> DestinationTestStepResult:+ """Run this test step."""+ return await asyncio.to_thread(self._check_permissions)++ def _check_permissions(self) -> DestinationTestStepResult:+ # This method should be called by `run()` which ensures this test step is configured+ # with non-`None` values.+ assert self.project_id is not None+ assert self.dataset_id is not None++ if dataset_exists(self.project_id, self.dataset_id, self.integration, self.service_account_info):+ required = [JOBS_CREATE_PERMISSION]+ else:+ required = [DATASETS_CREATE_PERMISSION, JOBS_CREATE_PERMISSION]++ credentials = get_iam_check_credentials(self.integration, self.service_account_info)+ url = (+ "https://cloudresourcemanager.googleapis.com/v1/projects/"+ f"{urllib.parse.quote(self.project_id, safe='')}:testIamPermissions"+ )++ try:+ with google.auth.transport.requests.AuthorizedSession(credentials) as session:+ response = session.post(url, json={"permissions": required}, timeout=IAM_CHECK_TIMEOUT_SECONDS)+ except google.auth.exceptions.GoogleAuthError:+ return DestinationTestStepResult(+ status=Status.FAILED,+ message=f"Could not check permissions on project '{self.project_id}' because authentication failed. Review the service account credentials and try again.",+ )+ except requests.exceptions.RequestException:+ return DestinationTestStepResult(+ status=Status.FAILED,+ message=f"Could not check permissions on project '{self.project_id}' because the request to Google Cloud failed. This is usually temporary, so try again.",+ )++ if response.status_code != 200:+ if is_service_disabled_error(response):+ return DestinationTestStepResult(+ status=Status.SKIPPED,+ message=f"Could not check permissions because the Cloud Resource Manager API is disabled in project '{self.project_id}'. Enable the API to run this check.",+ )+ if response.status_code == 429 or response.status_code >= 500:+ advice = "This is usually temporary, so try again."+ else:+ advice = "Review the service account credentials and its access to the project, then try again."+ return DestinationTestStepResult(+ status=Status.FAILED,+ message=f"Could not check permissions on project '{self.project_id}' (HTTP {response.status_code}). {advice}",+ )++ granted = set(response.json().get("permissions", []))+ missing = [permission for permission in required if permission not in granted]+ if not missing:+ return DestinationTestStepResult(status=Status.PASSED)++ message = f"The service account is missing permissions on project '{self.project_id}': {', '.join(missing)}."+ if DATASETS_CREATE_PERMISSION in missing:+ message += f" Dataset '{self.dataset_id}' does not exist, so grant the BigQuery Data Editor role on the project, or create the dataset first."+ if JOBS_CREATE_PERMISSION in missing:+ message += " Grant the BigQuery Job User role on the project."++ return DestinationTestStepResult(status=Status.FAILED, message=message)+++class BigQueryDatasetExistsOrCreatableTestStep(BigQueryDatasetTestStep):+ """Test whether a BigQuery dataset exists, and skip when it does not exist yet.++ A missing dataset is not a failure here, because the dataset is created when data is first+ written. `BigQueryProjectPermissionsTestStep` checks that the service account can create it.+ """++ description = "Ensure the configured BigQuery dataset exists and that we have the required permissions to access it. A dataset that does not exist yet is created when data is first written."++ async def _run_step(self) -> DestinationTestStepResult:+ """Run this test step."""+ assert self.dataset_id is not None++ if dataset_exists(self.project_id, self.dataset_id, self.integration, self.service_account_info):+ return DestinationTestStepResult(status=Status.PASSED)++ return DestinationTestStepResult(+ status=Status.SKIPPED,+ message=f"Dataset '{self.dataset_id}' does not exist yet. It is created when data is first written.",+ )+++class BigQueryTableIfDatasetExistsTestStep(BigQueryTableTestStep):+ """Run the table test only when the dataset exists.++ Creating a test table in a missing dataset always fails, and the tables are created together+ with the dataset when data is first written.+ """++ async def _run_step(self) -> DestinationTestStepResult:+ """Run this test step."""+ assert self.dataset_id is not None++ if not dataset_exists(self.project_id, self.dataset_id, self.integration, self.service_account_info):+ return DestinationTestStepResult(+ status=Status.SKIPPED,+ message=f"Dataset '{self.dataset_id}' does not exist yet, so its tables cannot be checked. They are created with the dataset.",+ )++ return await super()._run_step()+++class BigQueryCreateDatasetDestinationTest(BigQueryDestinationTest):+ """A `DestinationTest` for a BigQuery destination that creates its dataset when it is missing.++ Batch exports require the dataset to exist, so they use `BigQueryDestinationTest`. This test+ is for destinations that create the dataset and run their own jobs. It requires the Cloud+ Resource Manager API to check project permissions.+ """++ @property+ def steps(self) -> collections.abc.Sequence[DestinationTestStep]:+ """Sequence of test steps that make up this destination test."""+ return [+ BigQueryImpersonateServiceAccountTestStep(project_id=self.project_id, integration=self.integration),+ BigQueryVerifyServiceAccountOwnershipTestStep(+ project_id=self.project_id,+ integration=self.integration,+ organization_id=str(self.integration.integration.team.organization_id) if self.integration else None,+ ),+ BigQueryProjectTestStep(+ project_id=self.project_id,+ integration=self.integration,+ service_account_info=self.service_account_info,+ ),+ BigQueryProjectPermissionsTestStep(+ project_id=self.project_id,+ dataset_id=self.dataset_id,+ integration=self.integration,+ service_account_info=self.service_account_info,+ ),+ BigQueryDatasetExistsOrCreatableTestStep(+ project_id=self.project_id,+ dataset_id=self.dataset_id,+ integration=self.integration,+ service_account_info=self.service_account_info,+ ),+ BigQueryTableIfDatasetExistsTestStep(+ project_id=self.project_id,+ dataset_id=self.dataset_id,+ table_id=self.table_id,+ integration=self.integration,+ service_account_info=self.service_account_info,+ ),+ ]diff --git a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.pyindex 914ed64f60df..36c91eed386a 100644--- a/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/bigquery_batch_export.py@@ -552,6 +552,7 @@ async def verify_impersonated_service_account_ownership(def impersonate_service_account(integration: GoogleCloudServiceAccountIntegration,+ scopes: tuple[str, ...] = ("https://www.googleapis.com/auth/bigquery",),) -> google.auth.impersonated_credentials.Credentials:"""Impersonate a user's service account using our own.@@ -564,7 +565,7 @@ def impersonate_service_account(their_credentials = google.auth.impersonated_credentials.Credentials(source_credentials=our_credentials,target_principal=service_account_email,- target_scopes=["https://www.googleapis.com/auth/bigquery"],+ target_scopes=list(scopes),lifetime=3600,)diff --git a/products/batch_exports/backend/tests/destination_tests/test_bigquery_create_dataset_destination_tests.py b/products/batch_exports/backend/tests/destination_tests/test_bigquery_create_dataset_destination_tests.pynew file mode 100644index 000000000000..db3c142e5ee7--- /dev/null+++ b/products/batch_exports/backend/tests/destination_tests/test_bigquery_create_dataset_destination_tests.py@@ -0,0 +1,374 @@+import json+import typing++import pytest+from unittest.mock import MagicMock, patch++import requests+import google.auth.exceptions+from google.api_core.exceptions import NotFound++from posthog.models.integration import GoogleCloudServiceAccountIntegration++from products.batch_exports.backend.destination_tests import get_destination_test+from products.batch_exports.backend.destination_tests.base import DestinationTestStepResult, Status+from products.batch_exports.backend.destination_tests.bigquery import (+ BigQueryDatasetTestStep,+ BigQueryDestinationTest,+ BigQueryImpersonateServiceAccountTestStep,+ BigQueryProjectTestStep,+ BigQueryTableTestStep,+ BigQueryVerifyServiceAccountOwnershipTestStep,+ ServiceAccountInfo,+)+from products.batch_exports.backend.destination_tests.bigquery_create_dataset import (+ BigQueryCreateDatasetDestinationTest,+ BigQueryDatasetExistsOrCreatableTestStep,+ BigQueryProjectPermissionsTestStep,+ BigQueryTableIfDatasetExistsTestStep,+ get_iam_check_credentials,+)+from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import impersonate_service_account++MODULE = "products.batch_exports.backend.destination_tests.bigquery_create_dataset"+BIGQUERY_MODULE = "products.batch_exports.backend.destination_tests.bigquery"+BATCH_EXPORT_MODULE = "products.batch_exports.backend.temporal.destinations.bigquery_batch_export"++READ_ONLY_SCOPE = "https://www.googleapis.com/auth/cloud-platform.read-only"+JOBS = "bigquery.jobs.create"+DATASETS = "bigquery.datasets.create"++SERVICE_ACCOUNT_INFO: ServiceAccountInfo = {+ "private_key": "dummy-key",+ "private_key_id": "dummy-key-id",+ "token_uri": "https://oauth2.googleapis.com/token",+ "client_email": "[email protected]",+}+++def make_response(status_code: int, body: object) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = json.dumps(body).encode()+ return response+++def make_error(status: str, message: str, reason: str | None = None) -> dict[str, typing.Any]:+ details = []+ if reason is not None:+ details.append(+ {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": reason, "domain": "googleapis.com"}+ )+ return {"error": {"code": 403, "message": message, "status": status, "details": details}}+++def make_client(dataset_exists: bool) -> MagicMock:+ client = MagicMock()+ if not dataset_exists:+ client.sync_client.get_dataset.side_effect = NotFound("missing")+ return client+++ "dataset_exists,post_result,expected_status,expected_message_parts,unexpected_message_parts",+ [+ pytest.param(True, make_response(200, {"permissions": [JOBS]}), Status.PASSED, (), (), id="exists-granted"),+ pytest.param(+ True,+ make_response(200, {}),+ Status.FAILED,+ (JOBS, "BigQuery Job User"),+ (DATASETS, "BigQuery Data Editor"),+ id="exists-jobs-denied",+ ),+ pytest.param(+ False,+ make_response(200, {"permissions": [DATASETS, JOBS]}),+ Status.PASSED,+ (),+ (),+ id="missing-granted",+ ),+ pytest.param(+ False,+ make_response(200, {"permissions": [JOBS]}),+ Status.FAILED,+ (DATASETS, "BigQuery Data Editor", "create the dataset first"),+ ("BigQuery Job User",),+ id="missing-datasets-denied",+ ),+ pytest.param(+ False,+ make_response(200, {}),+ Status.FAILED,+ (f"{DATASETS}, {JOBS}", "BigQuery Data Editor", "BigQuery Job User"),+ (),+ id="missing-all-denied",+ ),+ pytest.param(+ False,+ make_response(403, make_error("PERMISSION_DENIED", "API has not been used", reason="SERVICE_DISABLED")),+ Status.SKIPPED,+ ("Cloud Resource Manager API is disabled",),+ (),+ id="service-disabled",+ ),+ pytest.param(+ True,+ make_response(403, make_error("PERMISSION_DENIED", "Billing is disabled for this project")),+ Status.FAILED,+ ("HTTP 403",),+ ("Cloud Resource Manager",),+ id="billing-disabled-is-not-service-disabled",+ ),+ pytest.param(+ True,+ make_response(403, make_error("PERMISSION_DENIED", "Access denied", reason="BILLING_DISABLED")),+ Status.FAILED,+ ("HTTP 403",),+ ("Cloud Resource Manager",),+ id="other-error-reason",+ ),+ pytest.param(True, make_response(500, "oops"), Status.FAILED, ("HTTP 500", "try again"), (), id="server-error"),+ pytest.param(+ True,+ requests.exceptions.ConnectionError("down"),+ Status.FAILED,+ ("request to Google Cloud failed", "try again"),+ (),+ id="connection-error",+ ),+ pytest.param(+ False,+ requests.exceptions.Timeout("slow"),+ Status.FAILED,+ ("request to Google Cloud failed", "try again"),+ (),+ id="timeout",+ ),+ pytest.param(+ True,+ google.auth.exceptions.RefreshError("no token"),+ Status.FAILED,+ ("authentication failed", "Review the service account credentials"),+ (),+ id="credentials-refresh-error",+ ),+ ],+)+async def test_project_permissions_step(+ dataset_exists: bool,+ post_result: requests.Response | Exception,+ expected_status: Status,+ expected_message_parts: tuple[str, ...],+ unexpected_message_parts: tuple[str, ...],+) -> None:+ step = BigQueryProjectPermissionsTestStep(+ project_id="my-project", dataset_id="d", service_account_info=SERVICE_ACCOUNT_INFO+ )+ post_kwargs = {"side_effect": post_result} if isinstance(post_result, Exception) else {"return_value": post_result}++ with (+ patch(f"{MODULE}.get_client", return_value=make_client(dataset_exists)),+ patch(f"{MODULE}.service_account.Credentials.from_service_account_info", return_value=MagicMock()),+ patch(f"{MODULE}.google.auth.transport.requests.AuthorizedSession.post", **post_kwargs) as post,+ ):+ result = await step.run()++ assert result.status == expected_status, result.message+ for part in expected_message_parts:+ assert result.message is not None and part in result.message+ for part in unexpected_message_parts:+ assert result.message is None or part not in result.message+ if expected_status == Status.PASSED:+ assert result.message is None++ post.assert_called_once_with(+ "https://cloudresourcemanager.googleapis.com/v1/projects/my-project:testIamPermissions",+ json={"permissions": [JOBS] if dataset_exists else [DATASETS, JOBS]},+ timeout=30,+ )+++async def test_project_permissions_step_quotes_project_id() -> None:+ step = BigQueryProjectPermissionsTestStep(+ project_id="evil/../projects/other?x=1", dataset_id="d", service_account_info=SERVICE_ACCOUNT_INFO+ )++ with (+ patch(f"{MODULE}.get_client", return_value=make_client(True)),+ patch(f"{MODULE}.service_account.Credentials.from_service_account_info", return_value=MagicMock()),+ patch(+ f"{MODULE}.google.auth.transport.requests.AuthorizedSession.post",+ return_value=make_response(200, {"permissions": [JOBS]}),+ ) as post,+ ):+ await step.run()++ assert post.call_args.args[0] == (+ "https://cloudresourcemanager.googleapis.com/v1/projects/evil%2F..%2Fprojects%2Fother%3Fx%3D1:testIamPermissions"+ )+++def make_integration(has_key: bool) -> MagicMock:+ integration = MagicMock(spec=GoogleCloudServiceAccountIntegration)+ integration.has_key.return_value = has_key+ integration.service_account_email = "[email protected]"+ integration.service_account_info = {**SERVICE_ACCOUNT_INFO, "project_id": "my-project"}+ return integration+++ "integration,service_account_info",+ [+ pytest.param(make_integration(has_key=True), None, id="key-file-integration"),+ pytest.param(None, SERVICE_ACCOUNT_INFO, id="service-account-inputs"),+ ],+)+def test_iam_check_credentials_from_key_use_read_only_scope(+ integration: MagicMock | None, service_account_info: ServiceAccountInfo | None+) -> None:+ with patch(f"{MODULE}.service_account.Credentials.from_service_account_info") as from_info:+ get_iam_check_credentials(integration, service_account_info)++ assert from_info.call_args.kwargs["scopes"] == [READ_ONLY_SCOPE]+++ "build_credentials,expected_scopes",+ [+ pytest.param(+ lambda integration: get_iam_check_credentials(integration, None),+ [READ_ONLY_SCOPE],+ id="iam-check",+ ),+ pytest.param(+ impersonate_service_account,+ ["https://www.googleapis.com/auth/bigquery"],+ id="default-bigquery-scope-unchanged",+ ),+ ],+)+def test_impersonated_credentials_scopes(+ build_credentials: typing.Callable[[MagicMock], object], expected_scopes: list[str]+) -> None:+ integration = make_integration(has_key=False)++ with (+ patch(f"{BATCH_EXPORT_MODULE}.get_our_google_cloud_credentials", return_value=MagicMock()),+ patch(f"{BATCH_EXPORT_MODULE}.google.auth.impersonated_credentials.Credentials") as impersonated,+ ):+ build_credentials(integration)++ assert impersonated.call_args.kwargs["target_scopes"] == expected_scopes+ assert impersonated.call_args.kwargs["target_principal"] == integration.service_account_email+++ORIGINAL_DATASET_MISSING_MESSAGE = (+ "Dataset 'd' could not be found because it doesn't exist or we don't have permissions to use it"+)+++ "step_class,dataset_exists,expected_status,expected_message",+ [+ pytest.param(BigQueryDatasetTestStep, True, Status.PASSED, None, id="original-exists"),+ pytest.param(+ BigQueryDatasetTestStep, False, Status.FAILED, ORIGINAL_DATASET_MISSING_MESSAGE, id="original-missing"+ ),+ pytest.param(BigQueryDatasetExistsOrCreatableTestStep, True, Status.PASSED, None, id="creatable-exists"),+ pytest.param(+ BigQueryDatasetExistsOrCreatableTestStep,+ False,+ Status.SKIPPED,+ "Dataset 'd' does not exist yet. It is created when data is first written.",+ id="creatable-missing",+ ),+ ],+)+async def test_dataset_steps(+ step_class: type[BigQueryDatasetTestStep],+ dataset_exists: bool,+ expected_status: Status,+ expected_message: str | None,+) -> None:+ client = make_client(dataset_exists)+ step = step_class(project_id="p", dataset_id="d", service_account_info=SERVICE_ACCOUNT_INFO)++ with (+ patch(f"{MODULE}.get_client", return_value=client),+ patch(f"{BIGQUERY_MODULE}.get_client", return_value=client),+ ):+ result = await step.run()++ assert result == DestinationTestStepResult(status=expected_status, message=expected_message)+++ "dataset_exists,expected_status,create_table_called",+ [+ pytest.param(True, Status.PASSED, True, id="dataset-exists"),+ pytest.param(False, Status.SKIPPED, False, id="dataset-missing"),+ ],+)+async def test_table_step_runs_only_when_dataset_exists(+ dataset_exists: bool, expected_status: Status, create_table_called: bool+) -> None:+ client = make_client(dataset_exists)+ client.sync_client.get_table.side_effect = NotFound("missing")+ step = BigQueryTableIfDatasetExistsTestStep(+ project_id="p", dataset_id="d", table_id="t", service_account_info=SERVICE_ACCOUNT_INFO+ )++ with (+ patch(f"{MODULE}.get_client", return_value=client),+ patch(f"{BIGQUERY_MODULE}.get_client", return_value=client),+ ):+ result = await step.run()++ assert result.status == expected_status+ assert client.sync_client.create_table.called is create_table_called+++ "destination_type,expected_class,expected_step_classes",+ [+ pytest.param(+ "BigQuery",+ BigQueryDestinationTest,+ [+ BigQueryImpersonateServiceAccountTestStep,+ BigQueryVerifyServiceAccountOwnershipTestStep,+ BigQueryProjectTestStep,+ BigQueryDatasetTestStep,+ BigQueryTableTestStep,+ ],+ id="batch-exports-bigquery",+ ),+ pytest.param(+ "BigQueryCreateDataset",+ BigQueryCreateDatasetDestinationTest,+ [+ BigQueryImpersonateServiceAccountTestStep,+ BigQueryVerifyServiceAccountOwnershipTestStep,+ BigQueryProjectTestStep,+ BigQueryProjectPermissionsTestStep,+ BigQueryDatasetExistsOrCreatableTestStep,+ BigQueryTableIfDatasetExistsTestStep,+ ],+ id="create-dataset",+ ),+ ],+)+def test_destination_test_registry(+ destination_type: str, expected_class: type[BigQueryDestinationTest], expected_step_classes: list[type]+) -> None:+ destination_test = get_destination_test(destination_type)+ destination_test.configure(project_id="p", dataset_id="d", table_id="t", create_dataset_if_missing=True)++ assert type(destination_test) is expected_class+ assert [type(step) for step in destination_test.steps] == expected_step_classes