|
| 1 | +from http import HTTPStatus |
| 2 | + |
| 3 | +import pytest |
| 4 | +from flask import Flask, request |
| 5 | + |
| 6 | +from server.request_parsing import get_json_object_or_abort |
| 7 | + |
| 8 | + |
| 9 | +class AbortCalled(Exception): |
| 10 | + def __init__(self, status, message): |
| 11 | + self.status = status |
| 12 | + self.message = message |
| 13 | + super().__init__(message) |
| 14 | + |
| 15 | + |
| 16 | +@pytest.fixture |
| 17 | +def app(): |
| 18 | + return Flask(__name__) |
| 19 | + |
| 20 | + |
| 21 | +def abort_func(status, message): |
| 22 | + raise AbortCalled(status, message) |
| 23 | + |
| 24 | + |
| 25 | +def test_get_json_object_or_abort_returns_payload_for_valid_json_object(app): |
| 26 | + with app.test_request_context( |
| 27 | + '/', |
| 28 | + method='POST', |
| 29 | + json={'city_name': 'Gotham'}, |
| 30 | + ): |
| 31 | + payload = get_json_object_or_abort(request, abort_func) |
| 32 | + |
| 33 | + assert payload == {'city_name': 'Gotham'} |
| 34 | + |
| 35 | + |
| 36 | +def test_get_json_object_or_abort_allows_empty_object(app): |
| 37 | + with app.test_request_context('/', method='PUT', json={}): |
| 38 | + payload = get_json_object_or_abort(request, abort_func) |
| 39 | + |
| 40 | + assert payload == {} |
| 41 | + |
| 42 | + |
| 43 | +def test_get_json_object_or_abort_rejects_malformed_json(app): |
| 44 | + with app.test_request_context( |
| 45 | + '/', |
| 46 | + method='POST', |
| 47 | + data='{"city_name": "Broken"', |
| 48 | + content_type='application/json', |
| 49 | + ): |
| 50 | + with pytest.raises(AbortCalled) as exc_info: |
| 51 | + get_json_object_or_abort(request, abort_func) |
| 52 | + |
| 53 | + assert exc_info.value.status == HTTPStatus.BAD_REQUEST |
| 54 | + assert exc_info.value.message == 'Request body must be a valid JSON object' |
| 55 | + |
| 56 | + |
| 57 | +def test_get_json_object_or_abort_rejects_non_object_json(app): |
| 58 | + with app.test_request_context('/', method='POST', json=['not', 'an', 'object']): |
| 59 | + with pytest.raises(AbortCalled) as exc_info: |
| 60 | + get_json_object_or_abort(request, abort_func) |
| 61 | + |
| 62 | + assert exc_info.value.status == HTTPStatus.BAD_REQUEST |
| 63 | + assert exc_info.value.message == 'Request body must be a valid JSON object' |
0 commit comments