"""Tests for Handlers.""" import json from unittest.mock import MagicMock from unittest.mock import patch import application from oto import response from oto import status import pytest from prs import handlers from prs.api import app from prs.logic import label_details_logic @patch('prs.handlers.g') def test_exception_handler(mock_g): """Verify exception_Handler returns 500 status code and json payload.""" message = ( 'The server encountered an internal error ' 'and was unable to complete your request.') mock_error = MagicMock() server_response = handlers.exception_handler(mock_error) mock_g.log.exception.assert_called_with(mock_error) # assert status code is 500 assert server_response.status_code == 500 # assert json payload response_message = json.loads(server_response.data.decode()) assert response_message['message'] == message assert response_message['code'] == response.error.ERROR_CODE_INTERNAL_ERROR def test_get_label_details(tool_param_data, label_details_response, mocker): """Test get_label_details on success.""" mocker.patch.object( label_details_logic, 'fetch_label_details', return_value=response.Response(message=label_details_response)) with application.app.test_request_context( data=json.dumps(tool_param_data), content_type='application/json'): handler_response = handlers.get_label_details() assert handler_response.status_code == status.OK def test_get_label_details_failure(tool_param_data, mocker): """Test get_label_details on failure.""" mocker.patch.object( label_details_logic, 'fetch_label_details', return_value=response.create_not_found_response()) with application.app.test_request_context( data=json.dumps(tool_param_data), content_type='application/json'): handler_response = handlers.get_label_details() assert handler_response.status_code == status.NOT_FOUND @pytest.mark.parametrize('description, request_body', [ ('test with empty request body', ''), ('test with invalid data passed to request body', 'abc'), ('test with empty manual_label', {'manual_label': ''}), ('test with invalid manual_label', {'manual_label': '12'})]) def test_get_label_details_invalid_request_body( description, request_body): """Test for get_label_details invalid request body.""" with app.test_client() as client: result = client.post('/label-details', data=request_body) assert result.status_code == status.BAD_REQUEST