"""Tests for the create view.""" from unittest.mock import MagicMock from owsresponse import response import pytest from royalty_common.constants import error from royalty_common.marshalling.custom_fields import ma from royalty_common.test_utils.helpers import get_json_body from royalty_common.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 400 if no JSON body.""" res = fixture_client.post('/chestburster') 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)