Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions dataflow/snippets/test/test_streaming_process_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Iterator
from unittest import mock
import uuid

from apache_beam.io import PubsubMessage
from apache_beam.testing.test_stream import TestStream
from apache_beam.transforms.window import TimestampedValue

from google.cloud import storage

import pytest

from ..streaming_process_storage import run

SALES_CSV = """order_id,product,amount
1001,widget,19.99
1002,gadget,5.49
1003,widget,19.99
1004,gizmo,42.00
"""

storage_client = storage.Client()


@pytest.fixture(scope="function")
def bucket_name() -> Iterator[str]:
bucket = storage_client.create_bucket(f"test-bucket-{uuid.uuid4()}")
try:
yield bucket.name
finally:
bucket.delete(force=True)
Comment on lines +36 to +45

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Initializing storage.Client() at the module level can cause test discovery to fail in environments where active Google Cloud credentials are not configured. It is safer and more idiomatic to define a storage_client fixture and inject it into the bucket_name fixture and the test function.

Suggested change
storage_client = storage.Client()
@pytest.fixture(scope="function")
def bucket_name() -> Iterator[str]:
bucket = storage_client.create_bucket(f"test-bucket-{uuid.uuid4()}")
try:
yield bucket.name
finally:
bucket.delete(force=True)
@pytest.fixture(scope="session")
def storage_client() -> storage.Client:
return storage.Client()
@pytest.fixture(scope="function")
def bucket_name(storage_client: storage.Client) -> Iterator[str]:
bucket = storage_client.create_bucket(f"test-bucket-{{uuid.uuid4()}}")
try:
yield bucket.name
finally:
bucket.delete(force=True)
References
  1. Maintain consistency in test structures by matching the patterns employed by existing or neighboring tests in the same directory, such as using a try...finally block with a teardown function for resource cleanup.



def notification(bucket_name: str, object_id: str, event_type: str) -> PubsubMessage:
"""Builds a message like the ones that Cloud Storage sends to Pub/Sub."""
return PubsubMessage(
data=b"",
attributes={
"bucketId": bucket_name,
"objectId": object_id,
"eventType": event_type,
},
)


def fake_notifications(bucket_name: str) -> TestStream:
"""Replaces ReadFromPubSub with a bounded stream of notifications."""
return (
TestStream()
.advance_watermark_to(0)
.add_elements(
[
TimestampedValue(
notification(bucket_name, "input/sales.csv", "OBJECT_FINALIZE"),
10,
),
# The pipeline must ignore events other than OBJECT_FINALIZE.
# This object doesn't exist, so reading it would fail.
TimestampedValue(
notification(bucket_name, "input/deleted.csv", "OBJECT_DELETE"),
20,
),
]
)
.advance_watermark_to_infinity()
)


def test_streaming_process_storage(bucket_name: str) -> None:
bucket = storage_client.bucket(bucket_name)
bucket.blob("input/sales.csv").upload_from_string(SALES_CSV)
Comment on lines +83 to +85

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Update the test function signature to accept the storage_client fixture so that it is properly injected and used within the test.

Suggested change
def test_streaming_process_storage(bucket_name: str) -> None:
bucket = storage_client.bucket(bucket_name)
bucket.blob("input/sales.csv").upload_from_string(SALES_CSV)
def test_streaming_process_storage(storage_client: storage.Client, bucket_name: str) -> None:
bucket = storage_client.bucket(bucket_name)
bucket.blob("input/sales.csv").upload_from_string(SALES_CSV)


with mock.patch(
"apache_beam.io.ReadFromPubSub",
lambda **kwargs: fake_notifications(bucket_name),
):
run(
[
"--subscription=projects/unused/subscriptions/unused",
f"--output=gs://{bucket_name}/output/",
]
)

# Ensure the pipeline wrote the aggregated results to Cloud Storage.
blobs = [
blob
for blob in storage_client.list_blobs(bucket_name, prefix="output/sales")
if blob.name.endswith(".csv")
]
assert blobs
rows = []
for blob in blobs:
rows.extend(blob.download_as_text().splitlines())
assert sorted(rows) == ["gadget,5.49", "gizmo,42.00", "widget,39.98"]