File size: 10,170 Bytes
a718a03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package com.anthony.failsafeapi.exception;

import com.anthony.failsafeapi.model.ProcessingContext;
import com.anthony.failsafeapi.model.TicketResponse;
import com.anthony.failsafeapi.util.constants.SecurityLayer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@DisplayName("GlobalExceptionHandler - Manejo centralizado de excepciones")
class GlobalExceptionHandlerTest {

    private GlobalExceptionHandler handler;

    @BeforeEach
    void setUp() {
        handler = new GlobalExceptionHandler();
    }

    // ─────────────────────────────────────────────────────────────
    // AIResponseParseException β†’ 500
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("AIResponseParseException β†’ HTTP 500")
    class ParseExceptionTests {

        @Test
        @DisplayName("Devuelve 500 con fuente AI_PARSER")
        void shouldReturn500() {
            ResponseEntity<ErrorResponse> response = handler.handleParse(
                    new AIResponseParseException("parse error", null));

            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
            assertThat(response.getBody()).isNotNull();
            assertThat(response.getBody().source()).isEqualTo("AI_PARSER");
            assertThat(response.getBody().status()).isEqualTo("ERROR");
        }
    }

    // ─────────────────────────────────────────────────────────────
    // AISanitizationException β†’ 400
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("AISanitizationException β†’ HTTP 400")
    class SanitizationExceptionTests {

        @Test
        @DisplayName("Devuelve 400 con fuente SANITIZER y el mensaje original")
        void shouldReturn400WithMessage() {
            String reason = "SEGURIDAD: inyecciΓ³n detectada";
            ResponseEntity<ErrorResponse> response = handler.handleSanitization(
                    new AISanitizationException(reason));

            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
            assertThat(response.getBody()).isNotNull();
            assertThat(response.getBody().source()).isEqualTo("SANITIZER");
            assertThat(response.getBody().status()).isEqualTo("REJECTED");
            assertThat(response.getBody().message()).isEqualTo(reason);
        }
    }

    // ─────────────────────────────────────────────────────────────
    // RateLimitExceededException β†’ 429
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("RateLimitExceededException β†’ HTTP 429")
    class RateLimitExceptionTests {

        @Test
        @DisplayName("Devuelve 429 con fuente RATE_LIMITER")
        void shouldReturn429() {
            ResponseEntity<ErrorResponse> response = handler.handleRateLimit(
                    new RateLimitExceededException("IP limit exceeded"));

            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
            assertThat(response.getBody()).isNotNull();
            assertThat(response.getBody().source()).isEqualTo("RATE_LIMITER");
            assertThat(response.getBody().status()).isEqualTo("REJECTED");
            assertThat(response.getBody().message()).isEqualTo("RATE_LIMIT_EXCEEDED");
        }
    }

    // ─────────────────────────────────────────────────────────────
    // IllegalArgumentException β†’ 400
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("IllegalArgumentException β†’ HTTP 400")
    class IllegalArgumentTests {

        @Test
        @DisplayName("Devuelve 400 con fuente VALIDATOR e informaciΓ³n del error")
        void shouldReturn400WithValidatorSource() {
            ResponseEntity<ErrorResponse> response = handler.handleIllegalArgument(
                    new IllegalArgumentException("DescripciΓ³n vacΓ­a"));

            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
            assertThat(response.getBody()).isNotNull();
            assertThat(response.getBody().source()).isEqualTo("VALIDATOR");
            assertThat(response.getBody().message()).contains("DescripciΓ³n vacΓ­a");
        }
    }

    // ─────────────────────────────────────────────────────────────
    // FallbackActivatedException β†’ 503
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("FallbackActivatedException β†’ HTTP 503")
    class FallbackExceptionTests {

        @Test
        @DisplayName("Devuelve 503 con estado DEGRADED y la categorΓ­a inferida")
        void shouldReturn503WithDegradedStatus() {
            ProcessingContext ctx = new ProcessingContext();
            ctx.addSecurityLayer(SecurityLayer.INJECTION_DETECTION);

            FallbackActivatedException ex = new FallbackActivatedException("URGENTE", ctx);
            ResponseEntity<TicketResponse> response = handler.handleFallback(ex);

            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
            TicketResponse body = response.getBody();
            assertThat(body).isNotNull();
            assertThat(body.status()).isEqualTo("DEGRADED");
            assertThat(body.category()).isEqualTo("URGENTE");
            assertThat(body.provider()).isEqualTo("LOCAL_BERT_MODEL");
        }

        @Test
        @DisplayName("Incluye las capas de seguridad del contexto en la respuesta")
        void shouldIncludeSecurityLayersFromContext() {
            ProcessingContext ctx = new ProcessingContext();
            ctx.addSecurityLayer(SecurityLayer.INJECTION_DETECTION);
            ctx.addSecurityLayer(SecurityLayer.PII_MASKING_FAILED);

            FallbackActivatedException ex = new FallbackActivatedException("NORMAL", ctx);
            ResponseEntity<TicketResponse> response = handler.handleFallback(ex);

            assertThat(response.getBody().securityLayersPassed())
                    .contains("INJECTION_DETECTION", "PII_MASKING_FAILED");
        }

        @Test
        @DisplayName("Refleja el estado de PII detectada en la respuesta fallback")
        void shouldReflectPiiDetectedState() {
            ProcessingContext ctx = new ProcessingContext();
            ctx.markPiiDetected();

            FallbackActivatedException ex = new FallbackActivatedException("BAJO", ctx);
            ResponseEntity<TicketResponse> response = handler.handleFallback(ex);

            assertThat(response.getBody().piiDetected()).isTrue();
        }
    }

    // ─────────────────────────────────────────────────────────────
    // IllegalStateException β†’ 503
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("IllegalStateException β†’ HTTP 503")
    class IllegalStateTests {

        @Test
        @DisplayName("Devuelve 503 con fuente MODEL_LOADER")
        void shouldReturn503WithModelLoaderSource() {
            ResponseEntity<ErrorResponse> response = handler.handleIllegalState(
                    new IllegalStateException("Modelos aΓΊn cargando"));

            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
            assertThat(response.getBody().source()).isEqualTo("MODEL_LOADER");
            assertThat(response.getBody().status()).isEqualTo("UNAVAILABLE");
        }
    }

    // ─────────────────────────────────────────────────────────────
    // Exception genΓ©rica β†’ 500
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("Exception genΓ©rica β†’ HTTP 500")
    class GenericExceptionTests {

        @Test
        @DisplayName("Devuelve 500 con fuente UNKNOWN para excepciones no clasificadas")
        void shouldReturn500ForUnknownException() {
            ResponseEntity<ErrorResponse> response = handler.handleGenericException(
                    new RuntimeException("Unexpected"));

            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
            assertThat(response.getBody().source()).isEqualTo("UNKNOWN");
            assertThat(response.getBody().message()).isEqualTo("UNEXPECTED_ERROR");
        }
    }
}