Skip to content

Commit 553eed9

Browse files
authored
docs: add sample to include run notification (#173)
* docs: add sample to include run notification * blacken samples * fix sample lint
1 parent 20abeb5 commit 553eed9

File tree

6 files changed

+124
-10
lines changed

6 files changed

+124
-10
lines changed

bigquery-datatransfer/snippets/conftest.py

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,48 @@
1414

1515
import datetime
1616
import os
17+
import random
1718
import uuid
1819

1920
from google.api_core import client_options
2021
import google.api_core.exceptions
2122
import google.auth
2223
from google.cloud import bigquery
2324
from google.cloud import bigquery_datatransfer
25+
from google.cloud import pubsub_v1
2426
import pytest
2527

2628

29+
RESOURCE_PREFIX = "python_bigquery_datatransfer_samples_snippets"
30+
RESOURCE_DATE_FORMAT = "%Y%m%d%H%M%S"
31+
RESOURCE_DATE_LENGTH = 4 + 2 + 2 + 2 + 2 + 2
32+
33+
34+
def resource_prefix() -> str:
35+
timestamp = datetime.datetime.utcnow().strftime(RESOURCE_DATE_FORMAT)
36+
random_string = hex(random.randrange(1000000))[2:]
37+
return f"{RESOURCE_PREFIX}_{timestamp}_{random_string}"
38+
39+
40+
def resource_name_to_date(resource_name: str):
41+
start_date = len(RESOURCE_PREFIX) + 1
42+
date_string = resource_name[start_date : start_date + RESOURCE_DATE_LENGTH]
43+
parsed_date = datetime.datetime.strptime(date_string, RESOURCE_DATE_FORMAT)
44+
return parsed_date
45+
46+
47+
@pytest.fixture(scope="session", autouse=True)
48+
def cleanup_pubsub_topics(pubsub_client: pubsub_v1.PublisherClient, project_id):
49+
yesterday = datetime.datetime.utcnow() - datetime.timedelta(days=1)
50+
for topic in pubsub_client.list_topics(project=f"projects/{project_id}"):
51+
topic_id = topic.name.split("/")[-1]
52+
if (
53+
topic_id.startswith(RESOURCE_PREFIX)
54+
and resource_name_to_date(topic_id) < yesterday
55+
):
56+
pubsub_client.delete_topic(topic=topic.name)
57+
58+
2759
def temp_suffix():
2860
now = datetime.datetime.now()
2961
return f"{now.strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}"
@@ -35,6 +67,21 @@ def bigquery_client(default_credentials):
3567
return bigquery.Client(credentials=credentials, project=project_id)
3668

3769

70+
@pytest.fixture(scope="session")
71+
def pubsub_client(default_credentials):
72+
credentials, _ = default_credentials
73+
return pubsub_v1.PublisherClient(credentials=credentials)
74+
75+
76+
@pytest.fixture(scope="session")
77+
def pubsub_topic(pubsub_client: pubsub_v1.PublisherClient, project_id):
78+
topic_id = resource_prefix()
79+
topic_path = pubsub_v1.PublisherClient.topic_path(project_id, topic_id)
80+
pubsub_client.create_topic(name=topic_path)
81+
yield topic_path
82+
pubsub_client.delete_topic(topic=topic_path)
83+
84+
3885
@pytest.fixture(scope="session")
3986
def dataset_id(bigquery_client, project_id):
4087
dataset_id = f"bqdts_{temp_suffix()}"
@@ -56,10 +103,10 @@ def project_id():
56103
@pytest.fixture(scope="session")
57104
def service_account_name(default_credentials):
58105
credentials, _ = default_credentials
59-
# Note: this property is not available when running with user account
60-
# credentials, but only service account credentials are used in our test
61-
# infrastructure.
62-
return credentials.service_account_email
106+
# The service_account_email attribute is not available when running with
107+
# user account credentials, but should be available when running from our
108+
# continuous integration tests.
109+
return getattr(credentials, "service_account_email", None)
63110

64111

65112
@pytest.fixture(scope="session")

bigquery-datatransfer/snippets/manage_transfer_configs.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,7 @@ def schedule_backfill(override_values={}):
135135
)
136136

137137
response = transfer_client.schedule_transfer_runs(
138-
parent=transfer_config_name,
139-
start_time=start_time,
140-
end_time=end_time,
138+
parent=transfer_config_name, start_time=start_time, end_time=end_time,
141139
)
142140

143141
print("Started transfer runs:")

bigquery-datatransfer/snippets/manage_transfer_configs_test.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,7 @@ def test_update_credentials_with_service_account(
5252

5353
def test_schedule_backfill(capsys, transfer_config_name):
5454
runs = manage_transfer_configs.schedule_backfill(
55-
{
56-
"transfer_config_name": transfer_config_name,
57-
}
55+
{"transfer_config_name": transfer_config_name}
5856
)
5957
out, _ = capsys.readouterr()
6058
assert "Started transfer runs:" in out
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
google-cloud-bigquery==2.20.0
2+
google-cloud-pubsub==2.6.0
23
pytest==6.2.4
34
mock==4.0.3
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Copyright 2021 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
def run_notification(transfer_config_name, pubsub_topic):
17+
orig_transfer_config_name = transfer_config_name
18+
orig_pubsub_topic = pubsub_topic
19+
# [START bigquerydatatransfer_run_notification]
20+
transfer_config_name = "projects/1234/locations/us/transferConfigs/abcd"
21+
pubsub_topic = "projects/PROJECT-ID/topics/TOPIC-ID"
22+
# [END bigquerydatatransfer_run_notification]
23+
transfer_config_name = orig_transfer_config_name
24+
pubsub_topic = orig_pubsub_topic
25+
26+
# [START bigquerydatatransfer_run_notification]
27+
from google.cloud import bigquery_datatransfer
28+
from google.protobuf import field_mask_pb2
29+
30+
transfer_client = bigquery_datatransfer.DataTransferServiceClient()
31+
32+
transfer_config = bigquery_datatransfer.TransferConfig(name=transfer_config_name)
33+
transfer_config.notification_pubsub_topic = pubsub_topic
34+
update_mask = field_mask_pb2.FieldMask(paths=["notification_pubsub_topic"])
35+
36+
transfer_config = transfer_client.update_transfer_config(
37+
{"transfer_config": transfer_config, "update_mask": update_mask}
38+
)
39+
40+
print(f"Updated config: '{transfer_config.name}'")
41+
print(f"Notification Pub/Sub topic: '{transfer_config.notification_pubsub_topic}'")
42+
# [END bigquerydatatransfer_run_notification]
43+
# Return the config name for testing purposes, so that it can be deleted.
44+
return transfer_config
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Copyright 2021 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from . import run_notification
16+
17+
18+
def test_run_notification(capsys, transfer_config_name, pubsub_topic):
19+
run_notification.run_notification(
20+
transfer_config_name=transfer_config_name, pubsub_topic=pubsub_topic,
21+
)
22+
out, _ = capsys.readouterr()
23+
assert "Updated config:" in out
24+
assert transfer_config_name in out
25+
assert "Notification Pub/Sub topic:" in out
26+
assert pubsub_topic in out

0 commit comments

Comments
 (0)