|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Full-coverage unit tests for **mcpgateway.utils.error_formatter** |
| 4 | +
|
| 5 | +Running: |
| 6 | +
|
| 7 | + pytest -q --cov=mcpgateway.utils.error_formatter --cov-report=term-missing |
| 8 | +
|
| 9 | +Should show **100 %** statement coverage for the target module. |
| 10 | +
|
| 11 | +Copyright 2025 |
| 12 | +SPDX-License-Identifier: Apache-2.0 |
| 13 | +Author: Mihai Criveti |
| 14 | +""" |
| 15 | + |
| 16 | +import pytest |
| 17 | +from unittest.mock import Mock |
| 18 | +from pydantic import BaseModel, ValidationError, field_validator |
| 19 | +from sqlalchemy.exc import DatabaseError, IntegrityError |
| 20 | + |
| 21 | +from mcpgateway.utils.error_formatter import ErrorFormatter |
| 22 | + |
| 23 | +class NameModel(BaseModel): |
| 24 | + name: str |
| 25 | + |
| 26 | + @field_validator('name') |
| 27 | + def validate_name(cls, v): |
| 28 | + if not v.startswith('A'): |
| 29 | + raise ValueError('Tool name must start with a letter') |
| 30 | + if len(v) > 255: |
| 31 | + raise ValueError('Tool name exceeds maximum length') |
| 32 | + return v |
| 33 | + |
| 34 | +class UrlModel(BaseModel): |
| 35 | + url: str |
| 36 | + |
| 37 | + @field_validator('url') |
| 38 | + def validate_url(cls, v): |
| 39 | + if not v.startswith('http'): |
| 40 | + raise ValueError('Tool URL must start with http') |
| 41 | + return v |
| 42 | + |
| 43 | +class PathModel(BaseModel): |
| 44 | + path: str |
| 45 | + |
| 46 | + @field_validator('path') |
| 47 | + def validate_path(cls, v): |
| 48 | + if '..' in v: |
| 49 | + raise ValueError('cannot contain directory traversal') |
| 50 | + return v |
| 51 | + |
| 52 | +class ContentModel(BaseModel): |
| 53 | + content: str |
| 54 | + |
| 55 | + @field_validator('content') |
| 56 | + def validate_content(cls, v): |
| 57 | + if '<' in v and '>' in v: |
| 58 | + raise ValueError('contains HTML tags') |
| 59 | + return v |
| 60 | + |
| 61 | +def test_format_validation_error_letter_requirement(): |
| 62 | + with pytest.raises(ValidationError) as exc: |
| 63 | + NameModel(name="Bobby") |
| 64 | + result = ErrorFormatter.format_validation_error(exc.value) |
| 65 | + assert result["message"] == "Validation failed" |
| 66 | + assert result["success"] is False |
| 67 | + assert result["details"][0]["field"] == "name" |
| 68 | + assert "must start with a letter" in result["details"][0]["message"] |
| 69 | + |
| 70 | +def test_format_validation_error_length(): |
| 71 | + with pytest.raises(ValidationError) as exc: |
| 72 | + NameModel(name="A" * 300) |
| 73 | + result = ErrorFormatter.format_validation_error(exc.value) |
| 74 | + assert "too long" in result["details"][0]["message"] |
| 75 | + |
| 76 | +def test_format_validation_error_url(): |
| 77 | + with pytest.raises(ValidationError) as exc: |
| 78 | + UrlModel(url="ftp://example.com") |
| 79 | + result = ErrorFormatter.format_validation_error(exc.value) |
| 80 | + assert "valid HTTP" in result["details"][0]["message"] |
| 81 | + |
| 82 | +def test_format_validation_error_directory_traversal(): |
| 83 | + with pytest.raises(ValidationError) as exc: |
| 84 | + PathModel(path="../etc/passwd") |
| 85 | + result = ErrorFormatter.format_validation_error(exc.value) |
| 86 | + assert "invalid characters" in result["details"][0]["message"] |
| 87 | + |
| 88 | +def test_format_validation_error_html_injection(): |
| 89 | + with pytest.raises(ValidationError) as exc: |
| 90 | + ContentModel(content="<script>alert(1)</script>") |
| 91 | + result = ErrorFormatter.format_validation_error(exc.value) |
| 92 | + assert "cannot contain HTML" in result["details"][0]["message"] |
| 93 | + |
| 94 | +def test_format_validation_error_fallback(): |
| 95 | + class CustomModel(BaseModel): |
| 96 | + custom: str |
| 97 | + |
| 98 | + @field_validator('custom') |
| 99 | + def validate_custom(cls, v): |
| 100 | + raise ValueError('Some unknown error') |
| 101 | + with pytest.raises(ValidationError) as exc: |
| 102 | + CustomModel(custom="foo") |
| 103 | + result = ErrorFormatter.format_validation_error(exc.value) |
| 104 | + assert result["details"][0]["message"] == "Invalid custom" |
| 105 | + |
| 106 | +def test_format_validation_error_multiple_fields(): |
| 107 | + class MultiModel(BaseModel): |
| 108 | + name: str |
| 109 | + url: str |
| 110 | + |
| 111 | + @field_validator('name') |
| 112 | + def validate_name(cls, v): |
| 113 | + if len(v) > 255: |
| 114 | + raise ValueError('Tool name exceeds maximum length') |
| 115 | + return v |
| 116 | + |
| 117 | + @field_validator('url') |
| 118 | + def validate_url(cls, v): |
| 119 | + if not v.startswith('http'): |
| 120 | + raise ValueError('Tool URL must start with http') |
| 121 | + return v |
| 122 | + |
| 123 | + with pytest.raises(ValidationError) as exc: |
| 124 | + MultiModel(name="A" * 300, url="ftp://bad") |
| 125 | + result = ErrorFormatter.format_validation_error(exc.value) |
| 126 | + assert len(result["details"]) == 2 |
| 127 | + messages = [d["message"] for d in result["details"]] |
| 128 | + assert any("too long" in m for m in messages) |
| 129 | + assert any("valid HTTP" in m for m in messages) |
| 130 | + |
| 131 | +def test_get_user_message_all_patterns(): |
| 132 | + # Directly test _get_user_message for all mappings and fallback |
| 133 | + assert "must start with a letter" in ErrorFormatter._get_user_message("name", "Tool name must start with a letter") |
| 134 | + assert "too long" in ErrorFormatter._get_user_message("description", "Tool name exceeds maximum length") |
| 135 | + assert "valid HTTP" in ErrorFormatter._get_user_message("endpoint", "Tool URL must start with http") |
| 136 | + assert "invalid characters" in ErrorFormatter._get_user_message("path", "cannot contain directory traversal") |
| 137 | + assert "cannot contain HTML" in ErrorFormatter._get_user_message("content", "contains HTML tags") |
| 138 | + assert ErrorFormatter._get_user_message("foo", "random error") == "Invalid foo" |
| 139 | + |
| 140 | +def make_mock_integrity_error(msg): |
| 141 | + mock = Mock(spec=IntegrityError) |
| 142 | + mock.orig = Mock() |
| 143 | + mock.orig.__str__ = lambda self=mock.orig: msg |
| 144 | + return mock |
| 145 | + |
| 146 | +@pytest.mark.parametrize("msg,expected", [ |
| 147 | + ("UNIQUE constraint failed: gateways.url", "A gateway with this URL already exists"), |
| 148 | + ("UNIQUE constraint failed: gateways.name", "A gateway with this name already exists"), |
| 149 | + ("UNIQUE constraint failed: tools.name", "A tool with this name already exists"), |
| 150 | + ("UNIQUE constraint failed: resources.uri", "A resource with this URI already exists"), |
| 151 | + ("UNIQUE constraint failed: servers.name", "A server with this name already exists"), |
| 152 | + ("FOREIGN KEY constraint failed", "Referenced item not found"), |
| 153 | + ("NOT NULL constraint failed", "Required field is missing"), |
| 154 | + ("CHECK constraint failed: invalid_data", "Validation failed. Please check the input data."), |
| 155 | +]) |
| 156 | +def test_format_database_error_integrity_patterns(msg, expected): |
| 157 | + err = make_mock_integrity_error(msg) |
| 158 | + result = ErrorFormatter.format_database_error(err) |
| 159 | + assert result["message"] == expected |
| 160 | + assert result["success"] is False |
| 161 | + |
| 162 | +def test_format_database_error_generic_integrity(): |
| 163 | + err = make_mock_integrity_error("SOME OTHER ERROR") |
| 164 | + result = ErrorFormatter.format_database_error(err) |
| 165 | + assert result["message"].startswith("Unable to complete") |
| 166 | + assert result["success"] is False |
| 167 | + |
| 168 | +def test_format_database_error_generic_database(): |
| 169 | + mock = Mock(spec=DatabaseError) |
| 170 | + mock.orig = None |
| 171 | + result = ErrorFormatter.format_database_error(mock) |
| 172 | + assert result["message"].startswith("Unable to complete") |
| 173 | + assert result["success"] is False |
| 174 | + |
| 175 | +def test_format_database_error_no_orig(): |
| 176 | + # Simulate error without .orig attribute |
| 177 | + class DummyError(Exception): |
| 178 | + pass |
| 179 | + dummy = DummyError("fail") |
| 180 | + result = ErrorFormatter.format_database_error(dummy) |
| 181 | + assert result["message"].startswith("Unable to complete") |
| 182 | + assert result["success"] is False |
0 commit comments