|
| 1 | +# Copyright 2020 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 | +# [START functions_pubsub_integration_test] |
| 16 | +import base64 |
| 17 | +import os |
| 18 | +import subprocess |
| 19 | +import uuid |
| 20 | + |
| 21 | +import requests |
| 22 | +from requests.packages.urllib3.util.retry import Retry |
| 23 | + |
| 24 | + |
| 25 | +def test_print_name(): |
| 26 | + name = str(uuid.uuid4()) |
| 27 | + port = 8088 # Each running framework instance needs a unique port |
| 28 | + |
| 29 | + encoded_name = base64.b64encode(name.encode('utf-8')).decode('utf-8') |
| 30 | + pubsub_message = { |
| 31 | + 'data': {'data': encoded_name} |
| 32 | + } |
| 33 | + |
| 34 | + process = subprocess.Popen( |
| 35 | + [ |
| 36 | + 'functions-framework', |
| 37 | + '--target', 'hello_pubsub', |
| 38 | + '--signature-type', 'event', |
| 39 | + '--port', str(port) |
| 40 | + ], |
| 41 | + cwd=os.path.dirname(__file__), |
| 42 | + stdout=subprocess.PIPE |
| 43 | + ) |
| 44 | + |
| 45 | + # Send HTTP request simulating Pub/Sub message |
| 46 | + # (GCF translates Pub/Sub messages to HTTP requests internally) |
| 47 | + url = f'http://localhost:{port}/' |
| 48 | + |
| 49 | + retry_policy = Retry(total=6, backoff_factor=1) |
| 50 | + retry_adapter = requests.adapters.HTTPAdapter( |
| 51 | + max_retries=retry_policy) |
| 52 | + |
| 53 | + session = requests.Session() |
| 54 | + session.mount(url, retry_adapter) |
| 55 | + |
| 56 | + response = session.post(url, json=pubsub_message) |
| 57 | + |
| 58 | + assert response.status_code == 200 |
| 59 | + |
| 60 | + # Stop the functions framework process |
| 61 | + process.kill() |
| 62 | + process.wait() |
| 63 | + out, err = process.communicate() |
| 64 | + |
| 65 | + print(out, err, response.content) |
| 66 | + |
| 67 | + assert f'Hello {name}!' in str(out) |
| 68 | +# [END functions_pubsub_integration_test] |
0 commit comments