Skip to content

Commit 5de120f

Browse files
docs: describe event and context in Pub/Sub example (GoogleCloudPlatform#5862)
* docs: describe event and context in Pub/Sub example * mock context resource as well
1 parent 3d06649 commit 5de120f

2 files changed

Lines changed: 23 additions & 7 deletions

File tree

functions/helloworld/main.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,16 +70,27 @@ def hello_pubsub(event, context):
7070
"""Background Cloud Function to be triggered by Pub/Sub.
7171
Args:
7272
event (dict): The dictionary with data specific to this type of
73-
event. The `data` field contains the PubsubMessage message. The
74-
`attributes` field will contain custom attributes if there are any.
75-
context (google.cloud.functions.Context): The Cloud Functions event
76-
metadata. The `event_id` field contains the Pub/Sub message ID. The
77-
`timestamp` field contains the publish time.
73+
event. The `@type` field maps to
74+
`type.googleapis.com/google.pubsub.v1.PubsubMessage`.
75+
The `data` field maps to the PubsubMessage data
76+
in a base64-encoded string. The `attributes` field maps
77+
to the PubsubMessage attributes if any is present.
78+
context (google.cloud.functions.Context): Metadata of triggering event
79+
including `event_id` which maps to the PubsubMessage
80+
messageId, `timestamp` which maps to the PubsubMessage
81+
publishTime, `event_type` which maps to
82+
`google.pubsub.topic.publish`, and `resource` which is
83+
a dictionary that describes the service API endpoint
84+
pubsub.googleapis.com, the triggering topic's name, and
85+
the triggering event type
86+
`type.googleapis.com/google.pubsub.v1.PubsubMessage`.
87+
Returns:
88+
None. The output is written to Cloud Logging.
7889
"""
7990
import base64
8091

81-
print("""This Function was triggered by messageId {} published at {}
82-
""".format(context.event_id, context.timestamp))
92+
print("""This Function was triggered by messageId {} published at {} to {}
93+
""".format(context.event_id, context.timestamp, context.resource["name"]))
8394

8495
if 'data' in event:
8596
name = base64.b64decode(event['data']).decode('utf-8')

functions/helloworld/sample_pubsub_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@
2323
mock_context = mock.Mock()
2424
mock_context.event_id = '617187464135194'
2525
mock_context.timestamp = '2019-07-15T22:09:03.761Z'
26+
mock_context.resource = {
27+
'name': 'projects/my-project/topics/my-topic',
28+
'service': 'pubsub.googleapis.com',
29+
'type': 'type.googleapis.com/google.pubsub.v1.PubsubMessage',
30+
}
2631

2732

2833
def test_print_hello_world(capsys):

0 commit comments

Comments
 (0)