"""Tests for the create view.""" from unittest.mock import MagicMock import pytest from owsresponse import response from abacus_common_logic.constants import error from abacus_common_logic.marshalling.custom_fields import ma from abacus_common_logic.test_utils.helpers import get_json_body from abacus_common_logic.views.create_view import CreateView class ChestbursterSchema(ma.Schema): """POST schema.""" tooth_count = ma.Integer(required=True) class ChestbursterCreateView(CreateView): """Handler for Chestburster creation.""" post_schema = ChestbursterSchema() @pytest.fixture(scope='module') def register_endpoint(test_app): """Register endpoint for testing.""" test_app.add_url_rule( '/chestburster', view_func=ChestbursterCreateView.as_view('create_chestburster'), methods=['POST'], ) @pytest.fixture def mock_create_handler(): """Mock the create handler.""" mock_create_logic = MagicMock() ChestbursterCreateView.create_handler = mock_create_logic return mock_create_logic def test_post_without_json_body(register_endpoint, fixture_client, mock_create_handler): """Respond with standard Flask 415 if no JSON body and content type.""" res = fixture_client.post('/chestburster') assert res.status_code == 415 def test_post_empty_json_body(register_endpoint, fixture_client, mock_create_handler): """Respond with 400 if empty JSON body.""" res = fixture_client.post('/chestburster', json={}) assert res.status_code == 400 assert get_json_body(res)['message'] == error.ERROR_MISSING_JSON_BODY mock_create_handler.assert_not_called() def test_post_with_invalid_post_body( register_endpoint, fixture_client, mock_create_handler ): """Respond with 400 if invalid JSON body.""" res = fixture_client.post('/chestburster', json={'cuteness': 'high'}) assert res.status_code == 400 assert error.ERROR_FIELD_MISSING in get_json_body(res)['message']['tooth_count'] mock_create_handler.assert_not_called() def test_post_with_valid_post_body( register_endpoint, fixture_client, mock_create_handler ): """Success.""" mock_create_handler.return_value = response.Response(message='Ta-da!!', status=201) res = fixture_client.post('/chestburster', json={'tooth_count': 1023}) assert res.status_code == 201 mock_create_handler.assert_called_with(tooth_count=1023)