|
| 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 | +import base64 |
| 15 | + |
| 16 | +import copy |
| 17 | + |
| 18 | +from uuid import uuid4 |
| 19 | + |
| 20 | +import pytest |
| 21 | + |
| 22 | +import main |
| 23 | + |
| 24 | + |
| 25 | +required_fields = ['Ce-Id', 'Ce-Source', 'Ce-Type', 'Ce-Specversion'] |
| 26 | + |
| 27 | +header_data = {field: str(uuid4()) for field in required_fields} |
| 28 | + |
| 29 | + |
| 30 | +@pytest.fixture |
| 31 | +def client(): |
| 32 | + main.app.testing = True |
| 33 | + return main.app.test_client() |
| 34 | + |
| 35 | + |
| 36 | +def test_empty_payload(client): |
| 37 | + r = client.post('/', json='', headers=header_data) |
| 38 | + assert r.status_code == 400 |
| 39 | + |
| 40 | + |
| 41 | +def test_invalid_payload(client): |
| 42 | + r = client.post('/', json={'nomessage': 'invalid'}, headers=header_data) |
| 43 | + assert r.status_code == 400 |
| 44 | + |
| 45 | + |
| 46 | +def test_invalid_mimetype(client): |
| 47 | + r = client.post('/', json="{ message: true }", headers=header_data) |
| 48 | + assert r.status_code == 400 |
| 49 | + |
| 50 | + |
| 51 | +def test_minimally_valid_message(client, capsys): |
| 52 | + r = client.post('/', json={'message': True}, headers=header_data) |
| 53 | + assert r.status_code == 200 |
| 54 | + |
| 55 | + out, _ = capsys.readouterr() |
| 56 | + ce_id = header_data['Ce-Id'] |
| 57 | + assert f'Hello, World! ID: {ce_id}' in out |
| 58 | + |
| 59 | + |
| 60 | +def test_populated_message(client, capsys): |
| 61 | + name = str(uuid4()) |
| 62 | + data = base64.b64encode(name.encode()).decode() |
| 63 | + |
| 64 | + r = client.post('/', json={'message': {'data': data}}, headers=header_data) |
| 65 | + assert r.status_code == 200 |
| 66 | + |
| 67 | + out, _ = capsys.readouterr() |
| 68 | + ce_id = header_data['Ce-Id'] |
| 69 | + assert f'Hello, {name}! ID: {ce_id}' in out |
| 70 | + |
| 71 | + |
| 72 | +def test_missing_required_fields(client, capsys): |
| 73 | + for field in required_fields: |
| 74 | + test_headers = copy.copy(header_data) |
| 75 | + test_headers.pop(field) |
| 76 | + |
| 77 | + r = client.post('/', headers=test_headers) |
| 78 | + assert r.status_code == 400 |
| 79 | + |
| 80 | + out, _ = capsys.readouterr() |
| 81 | + assert f'Bad Request: missing required header {field}' in out |
0 commit comments