Skip to content
Merged
Show file tree
Hide file tree
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
25 changes: 18 additions & 7 deletions functions/helloworld/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,27 @@ def hello_pubsub(event, context):
"""Background Cloud Function to be triggered by Pub/Sub.
Args:
event (dict): The dictionary with data specific to this type of
event. The `data` field contains the PubsubMessage message. The
`attributes` field will contain custom attributes if there are any.
context (google.cloud.functions.Context): The Cloud Functions event
metadata. The `event_id` field contains the Pub/Sub message ID. The
`timestamp` field contains the publish time.
event. The `@type` field maps to
`type.googleapis.com/google.pubsub.v1.PubsubMessage`.
The `data` field maps to the PubsubMessage data
in a base64-encoded string. The `attributes` field maps
to the PubsubMessage attributes if any is present.
context (google.cloud.functions.Context): Metadata of triggering event
including `event_id` which maps to the PubsubMessage
messageId, `timestamp` which maps to the PubsubMessage
publishTime, `event_type` which maps to
`google.pubsub.topic.publish`, and `resource` which is
a dictionary that describes the service API endpoint
pubsub.googleapis.com, the triggering topic's name, and
the triggering event type
`type.googleapis.com/google.pubsub.v1.PubsubMessage`.
Returns:
None. The output is written to Cloud Logging.
"""
import base64

print("""This Function was triggered by messageId {} published at {}
""".format(context.event_id, context.timestamp))
print("""This Function was triggered by messageId {} published at {} to {}
""".format(context.event_id, context.timestamp, context.resource["name"]))

if 'data' in event:
name = base64.b64decode(event['data']).decode('utf-8')
Expand Down
5 changes: 5 additions & 0 deletions functions/helloworld/sample_pubsub_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
mock_context = mock.Mock()
mock_context.event_id = '617187464135194'
mock_context.timestamp = '2019-07-15T22:09:03.761Z'
mock_context.resource = {
'name': 'projects/my-project/topics/my-topic',
'service': 'pubsub.googleapis.com',
'type': 'type.googleapis.com/google.pubsub.v1.PubsubMessage',
}


def test_print_hello_world(capsys):
Expand Down