def test_add_user_responses_bad_request_when_malformed_request_body(self, json_mock, logging_mock):
        request = Mock()
        request.body.read.side_effect = Exception('Test - request body read exception')

        response = add_user(request)

        request.body.read.assert_called_once_with()
        assert_that(response.status_code).is_equal_to(HttpStatus.BAD_REQUEST)
    def test_add_user_responses_bad_request_when_error_in_json_data(self, logging_mock, json_mock, user_data_error):
        request = Mock()
        request_user_data = Mock()
        json_mock.loads.return_value = request_user_data

        with patch.object(User, '__init__', side_effect=user_data_error) as user_mock:
            response = add_user(request)
            user_mock.assert_called_once_with(request_user_data)

        assert_that(response.status_code).is_equal_to(HttpStatus.BAD_REQUEST)
    def test_add_user_responses_internal_error_when_getting_db_instance_fails(self, logging_mock, json_mock):
        request = Mock()
        request_user_data = Mock()
        json_mock.loads.return_value = request_user_data

        with patch.object(User, '_get_missing_mandatory_attr', return_value=[]):
            with patch.object(User, '_check_valid_date', return_value=True):
                with patch.object(DataBase, 'get_instance') as db_get_instance_mock:
                    db_get_instance_mock.side_effect = DataBaseInstanceError('Test DB get instance error')
                    response = add_user(request)
                    db_get_instance_mock.assert_called_once_with()

        assert_that(response.status_code).is_equal_to(HttpStatus.INTERNAL_ERROR)
    def test_add_user_responses_ok_status_code_when_user_is_correctly_stored_in_db(self, logging_mock, json_mock):
        request = Mock()
        request_user_data = Mock()
        json_mock.loads.return_value = request_user_data

        with patch.object(User, '_get_missing_mandatory_attr', return_value=[]):
            with patch.object(User, '_check_valid_date', return_value=True):
                with patch.object(DataBase, 'get_instance') as db_get_instance_mock:
                    db_instance_mock = Mock()
                    db_instance_mock.side_effect = None
                    db_get_instance_mock.return_value = db_instance_mock

                    response = add_user(request)
                    db_instance_mock.insert_user.assert_called_once()

        assert_that(response.status_code).is_equal_to(HttpStatus.CREATED)
def add_new_user():
    logging.info("\n\n---------------- Add user request ---------------- \n")
    logging.info("URL: {0} \n".format(request.url))
    return user_handler.add_user(request)