Skip to content

Commit 4203190

Browse files
authored
samples: add pubsub notifications samples (#646)
* samples: add sample list notifications * samples: add sample get notification * add tests for get list notifications samples * add sample and test for creating a pubsub notification * add sample for deleting a pubsub notification * revise notification samples tests * update samples readme * clean up pubsub topic in tests * revise readme per comment
1 parent 2439d01 commit 4203190

6 files changed

+352
-0
lines changed

samples/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,12 @@ for instructions on setting up credentials for applications.
6565
* [CORS Configuration](#cors-configuration)
6666
* [Create Bucket](#create-bucket)
6767
* [Create Bucket Class Location](#create-bucket-class-location)
68+
* [Create Bucket Notifications](#create-bucket-notifications)
6869
* [Create HMAC Key](#create-hmac-key)
6970
* [Deactivate HMAC Key](#deactivate-hmac-key)
7071
* [Define Bucket Website Configuration](#define-bucket-website-configuration)
7172
* [Delete Bucket](#delete-bucket)
73+
* [Delete Bucket Notification](#delete-bucket-notification)
7274
* [Delete File](#delete-file)
7375
* [Delete File Archived Generation](#delete-file-archived-generation)
7476
* [Delete HMAC Key](#delete-hmac-key)
@@ -104,6 +106,7 @@ for instructions on setting up credentials for applications.
104106
* [Get Service Account](#get-service-account)
105107
* [Get Uniform Bucket Level Access](#get-uniform-bucket-level-access)
106108
* [List Buckets](#list-buckets)
109+
* [List Bucket Notifications](#list-bucket-notifications)
107110
* [List File Archived Generations](#list-file-archived-generations)
108111
* [List Files](#list-files)
109112
* [List Files With Prefix](#list-files-with-prefix)
@@ -117,6 +120,7 @@ for instructions on setting up credentials for applications.
117120
* [Print Bucket ACL For User](#print-bucket-acl-for-user)
118121
* [Print File ACL](#print-file-acl)
119122
* [Print File ACL For User](#print-file-acl-for-user)
123+
* [Print PubSub Bucket Notification](#print-pubsub-bucket-notification)
120124
* [Release Event Based Hold](#release-event-based-hold)
121125
* [Release Temporary Hold](#release-temporary-hold)
122126
* [Remove Bucket Conditional IAM Binding](#remove-bucket-conditional-iam-binding)
@@ -299,6 +303,15 @@ View the [source code](https://github.com/googleapis/python-storage/blob/main/sa
299303
300304
`python storage_create_bucket_class_location.py`
301305
306+
-----
307+
### Create Bucket Notifications
308+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_create_bucket_notifications.py,samples/README.md)
309+
310+
View the [source code](https://github.com/googleapis/python-storage/blob/main/samples/snippets/storage_create_bucket_notifications.py). To run this sample:
311+
312+
313+
`python storage_create_bucket_notifications.py <BUCKET_NAME> <TOPIC_NAME>`
314+
302315
-----
303316
### Create HMAC Key
304317
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_create_hmac_key.py,samples/README.md)
@@ -335,6 +348,15 @@ View the [source code](https://github.com/googleapis/python-storage/blob/main/sa
335348
336349
`python storage_delete_bucket.py`
337350
351+
-----
352+
### Delete Bucket Notification
353+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_delete_bucket_notification.py,samples/README.md)
354+
355+
View the [source code](https://github.com/googleapis/python-storage/blob/main/samples/snippets/storage_delete_bucket_notification.py). To run this sample:
356+
357+
358+
`python storage_delete_bucket_notification.py <BUCKET_NAME> <NOTIFICATION_ID>`
359+
338360
-----
339361
### Delete File
340362
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_delete_file.py,samples/README.md)
@@ -648,6 +670,15 @@ View the [source code](https://github.com/googleapis/python-storage/blob/main/sa
648670
649671
`python storage_list_buckets.py`
650672
673+
-----
674+
### List Bucket Notifications
675+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_list_bucket_notifications.py,samples/README.md)
676+
677+
View the [source code](https://github.com/googleapis/python-storage/blob/main/samples/snippets/storage_list_bucket_notifications.py). To run this sample:
678+
679+
680+
`python storage_list_bucket_notifications.py <BUCKET_NAME>`
681+
651682
-----
652683
### List File Archived Generations
653684
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_list_file_archived_generations.py,samples/README.md)
@@ -765,6 +796,15 @@ View the [source code](https://github.com/googleapis/python-storage/blob/main/sa
765796
766797
`python storage_print_file_acl_for_user.py`
767798
799+
-----
800+
### Print PubSub Bucket Notification
801+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_print_pubsub_bucket_notification.py,samples/README.md)
802+
803+
View the [source code](https://github.com/googleapis/python-storage/blob/main/samples/snippets/storage_print_pubsub_bucket_notification.py). To run this sample:
804+
805+
806+
`python storage_print_pubsub_bucket_notification.py <BUCKET_NAME> <NOTIFICATION_ID>`
807+
768808
-----
769809
### Release Event Based Hold
770810
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-storage&page=editor&open_in_editor=samples/snippets/storage_release_event_based_hold.py,samples/README.md)

samples/snippets/notification_test.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
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+
import uuid
17+
18+
from google.api_core.exceptions import NotFound
19+
from google.cloud import storage
20+
21+
import pytest
22+
23+
import storage_create_bucket_notifications
24+
import storage_delete_bucket_notification
25+
import storage_list_bucket_notifications
26+
import storage_print_pubsub_bucket_notification
27+
28+
_topic_name = f"notification-{uuid.uuid4()}"
29+
30+
31+
@pytest.fixture(scope="module")
32+
def storage_client():
33+
return storage.Client()
34+
35+
36+
@pytest.fixture(scope="module")
37+
def publisher_client():
38+
try:
39+
from google.cloud.pubsub_v1 import PublisherClient
40+
except ImportError:
41+
pytest.skip("Cannot import pubsub")
42+
43+
return PublisherClient()
44+
45+
46+
@pytest.fixture(scope="module")
47+
def _notification_topic(storage_client, publisher_client):
48+
topic_path = publisher_client.topic_path(storage_client.project, _topic_name)
49+
try:
50+
topic = publisher_client.get_topic(request={"topic": topic_path})
51+
except NotFound:
52+
topic = publisher_client.create_topic(request={"name": topic_path})
53+
54+
policy = publisher_client.get_iam_policy(request={"resource": topic_path})
55+
binding = policy.bindings.add()
56+
binding.role = "roles/pubsub.publisher"
57+
binding.members.append(
58+
"serviceAccount:{}".format(storage_client.get_service_account_email())
59+
)
60+
publisher_client.set_iam_policy(request={"resource": topic_path, "policy": policy})
61+
62+
yield topic
63+
64+
try:
65+
publisher_client.delete_topic(request={"topic": topic.name})
66+
except NotFound:
67+
pass
68+
69+
70+
@pytest.fixture(scope="module")
71+
def bucket_w_notification(storage_client, _notification_topic):
72+
"""Yields a bucket with notification that is deleted after the tests complete."""
73+
bucket = None
74+
while bucket is None or bucket.exists():
75+
bucket_name = f"notification-test-{uuid.uuid4()}"
76+
bucket = storage_client.bucket(bucket_name)
77+
bucket.create()
78+
79+
notification = bucket.notification(topic_name=_topic_name)
80+
notification.create()
81+
82+
yield bucket
83+
84+
bucket.delete(force=True)
85+
86+
87+
def test_list_bucket_notifications(bucket_w_notification, capsys):
88+
storage_list_bucket_notifications.list_bucket_notifications(bucket_w_notification.name)
89+
out, _ = capsys.readouterr()
90+
assert "Notification ID" in out
91+
92+
93+
def test_print_pubsub_bucket_notification(bucket_w_notification, capsys):
94+
notification_id = 1
95+
storage_print_pubsub_bucket_notification.print_pubsub_bucket_notification(bucket_w_notification.name, notification_id)
96+
out, _ = capsys.readouterr()
97+
assert "Notification ID: 1" in out
98+
99+
100+
def test_create_bucket_notifications(bucket_w_notification, capsys):
101+
# test only bucket notification ID 1 was created in the fixture
102+
assert bucket_w_notification.notification(notification_id=1).exists() is True
103+
assert bucket_w_notification.notification(notification_id=2).exists() is False
104+
105+
storage_create_bucket_notifications.create_bucket_notifications(bucket_w_notification.name, _topic_name)
106+
out, _ = capsys.readouterr()
107+
assert "Successfully created notification" in out
108+
# test succesfully creates new bucket notification with ID 2
109+
assert bucket_w_notification.notification(notification_id=2).exists() is True
110+
111+
112+
def test_delete_bucket_notification(bucket_w_notification, capsys):
113+
# test bucket notification ID 1 was created in the fixture
114+
notification_id = 1
115+
assert bucket_w_notification.notification(notification_id=notification_id).exists() is True
116+
117+
storage_delete_bucket_notification.delete_bucket_notification(bucket_w_notification.name, notification_id)
118+
out, _ = capsys.readouterr()
119+
assert "Successfully deleted notification" in out
120+
assert bucket_w_notification.notification(notification_id=notification_id).exists() is False
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2021 Google LLC. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the 'License');
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
import sys
18+
19+
"""Sample that creates a notification configuration for a bucket.
20+
This sample is used on this page:
21+
https://cloud.google.com/storage/docs/reporting-changes
22+
For more information, see README.md.
23+
"""
24+
25+
# [START storage_create_bucket_notifications]
26+
from google.cloud import storage
27+
28+
29+
def create_bucket_notifications(bucket_name, topic_name):
30+
"""Creates a notification configuration for a bucket."""
31+
# The ID of your GCS bucket
32+
# bucket_name = "your-bucket-name"
33+
# The name of a topic
34+
# topic_name = "your-topic-name"
35+
36+
storage_client = storage.Client()
37+
bucket = storage_client.bucket(bucket_name)
38+
notification = bucket.notification(topic_name=topic_name)
39+
notification.create()
40+
41+
print(f"Successfully created notification with ID {notification.notification_id} for bucket {bucket_name}")
42+
43+
# [END storage_create_bucket_notifications]
44+
45+
46+
if __name__ == "__main__":
47+
create_bucket_notifications(bucket_name=sys.argv[1], topic_name=sys.argv[2])
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2021 Google LLC. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the 'License');
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
import sys
18+
19+
"""Sample that deletes a notification configuration for a bucket.
20+
This sample is used on this page:
21+
https://cloud.google.com/storage/docs/reporting-changes
22+
For more information, see README.md.
23+
"""
24+
25+
# [START storage_delete_bucket_notification]
26+
from google.cloud import storage
27+
28+
29+
def delete_bucket_notification(bucket_name, notification_id):
30+
"""Deletes a notification configuration for a bucket."""
31+
# The ID of your GCS bucket
32+
# bucket_name = "your-bucket-name"
33+
# The ID of the notification
34+
# notification_id = "your-notification-id"
35+
36+
storage_client = storage.Client()
37+
bucket = storage_client.bucket(bucket_name)
38+
notification = bucket.notification(notification_id=notification_id)
39+
notification.delete()
40+
41+
print(f"Successfully deleted notification with ID {notification_id} for bucket {bucket_name}")
42+
43+
# [END storage_delete_bucket_notification]
44+
45+
46+
if __name__ == "__main__":
47+
delete_bucket_notification(bucket_name=sys.argv[1], notification_id=sys.argv[2])
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2021 Google LLC. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the 'License');
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
import sys
18+
19+
"""Sample that lists notification configurations for a bucket.
20+
This sample is used on this page:
21+
https://cloud.google.com/storage/docs/reporting-changes
22+
For more information, see README.md.
23+
"""
24+
25+
# [START storage_list_bucket_notifications]
26+
from google.cloud import storage
27+
28+
29+
def list_bucket_notifications(bucket_name):
30+
"""Lists notification configurations for a bucket."""
31+
# The ID of your GCS bucket
32+
# bucket_name = "your-bucket-name"
33+
34+
storage_client = storage.Client()
35+
bucket = storage_client.bucket(bucket_name)
36+
notifications = bucket.list_notifications()
37+
38+
for notification in notifications:
39+
print(f"Notification ID: {notification.notification_id}")
40+
41+
# [END storage_list_bucket_notifications]
42+
43+
44+
if __name__ == "__main__":
45+
list_bucket_notifications(bucket_name=sys.argv[1])

0 commit comments

Comments
 (0)