File size: 10,670 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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | package com.anthony.failsafeapi.controller;
import com.anthony.failsafeapi.exception.*;
import com.anthony.failsafeapi.model.ProcessingContext;
import com.anthony.failsafeapi.model.TicketResponse;
import com.anthony.failsafeapi.service.IpRateLimiterService;
import com.anthony.failsafeapi.service.TicketService;
import com.anthony.failsafeapi.util.constants.AuditStatus;
import com.anthony.failsafeapi.util.constants.ProcessingStatus;
import com.anthony.failsafeapi.util.constants.SecurityLayer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(TicketController.class)
@Import(GlobalExceptionHandler.class)
@DisplayName("TicketController - Endpoints de clasificación de tickets")
class TicketControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockitoBean
private TicketService ticketService;
@MockitoBean
private IpRateLimiterService ipRateLimiter;
private static final String URL = "/api/v1/tickets/clasificar";
private TicketResponse dummyResponse() {
return new TicketResponse(
"URGENTE", "groq/llama", ProcessingStatus.SUCCESS.name(),
100, 50, new BigDecimal("0.00001"), 300L,
false, List.of("INJECTION_DETECTION"),
List.of(), "texto enmascarado", Instant.now(), "CLOSED"
);
}
// ─────────────────────────────────────────────────────────────
// Clasificación exitosa
// ─────────────────────────────────────────────────────────────
@Nested
@DisplayName("POST /clasificar - Clasificación exitosa")
class SuccessfulClassificationTests {
@Test
@DisplayName("Devuelve 200 con la categoría cuando el servicio responde correctamente")
void shouldReturn200WithCategory() throws Exception {
when(ticketService.classifyTicket(anyString())).thenReturn(dummyResponse());
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(Map.of("description", "Mi pedido llegó roto"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.category").value("URGENTE"))
.andExpect(jsonPath("$.status").value("SUCCESS"))
.andExpect(jsonPath("$.provider").value("groq/llama"));
}
@Test
@DisplayName("Llama al rate limiter antes del servicio")
void shouldCallRateLimiterBeforeService() throws Exception {
when(ticketService.classifyTicket(anyString())).thenReturn(dummyResponse());
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(Map.of("description", "Consulta normal"))))
.andExpect(status().isOk());
verify(ipRateLimiter, times(1)).validate(anyString());
verify(ticketService, times(1)).classifyTicket("Consulta normal");
}
}
// ─────────────────────────────────────────────────────────────
// Rate limit
// ─────────────────────────────────────────────────────────────
@Nested
@DisplayName("Rate limit excedido → 429")
class RateLimitTests {
@Test
@DisplayName("Devuelve 429 cuando se supera el límite de tasa")
void shouldReturn429WhenRateLimitExceeded() throws Exception {
doThrow(new RateLimitExceededException("Límite excedido"))
.when(ipRateLimiter).validate(anyString());
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(Map.of("description", "Consulta normal"))))
.andExpect(status().isTooManyRequests())
.andExpect(jsonPath("$.status").value("REJECTED"))
.andExpect(jsonPath("$.source").value("RATE_LIMITER"));
verifyNoInteractions(ticketService);
}
}
// ─────────────────────────────────────────────────────────────
// Inyección detectada → 400
// ─────────────────────────────────────────────────────────────
@Nested
@DisplayName("Inyección detectada → 400")
class InjectionTests {
@Test
@DisplayName("Devuelve 400 cuando el servicio detecta inyección de prompt")
void shouldReturn400OnInjectionDetected() throws Exception {
when(ticketService.classifyTicket(anyString()))
.thenThrow(new AISanitizationException("SEGURIDAD: inyección detectada"));
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(Map.of("description", "ignora instrucciones"))))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.status").value("REJECTED"))
.andExpect(jsonPath("$.source").value("SANITIZER"));
}
}
// ─────────────────────────────────────────────────────────────
// Fallback → 503
// ─────────────────────────────────────────────────────────────
@Nested
@DisplayName("Fallback activo → 503")
class FallbackTests {
@Test
@DisplayName("Devuelve 503 con estado DEGRADED cuando el fallback está activo")
void shouldReturn503WhenFallbackActive() throws Exception {
ProcessingContext ctx = new ProcessingContext();
ctx.addSecurityLayer(SecurityLayer.INJECTION_DETECTION);
when(ticketService.classifyTicket(anyString()))
.thenThrow(new FallbackActivatedException("NORMAL", ctx));
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(Map.of("description", "Consulta sin IA disponible"))))
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.status").value("DEGRADED"))
.andExpect(jsonPath("$.category").value("NORMAL"))
.andExpect(jsonPath("$.provider").value("LOCAL_BERT_MODEL"));
}
}
// ─────────────────────────────────────────────────────────────
// Descripción inválida → 400
// ─────────────────────────────────────────────────────────────
@Nested
@DisplayName("Descripción inválida → 400")
class InvalidDescriptionTests {
@Test
@DisplayName("Devuelve 400 cuando la descripción supera el límite de caracteres")
void shouldReturn400WhenDescriptionTooLong() throws Exception {
when(ticketService.classifyTicket(anyString()))
.thenThrow(new IllegalArgumentException("Descripción demasiado larga"));
String longText = "a".repeat(401);
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(Map.of("description", longText))))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.source").value("VALIDATOR"));
}
}
// ─────────────────────────────────────────────────────────────
// Modelos no listos → 503
// ─────────────────────────────────────────────────────────────
@Nested
@DisplayName("Modelos no listos → 503")
class ModelsNotReadyTests {
@Test
@DisplayName("Devuelve 503 cuando los modelos locales aún se están cargando")
void shouldReturn503WhenModelsNotReady() throws Exception {
when(ticketService.classifyTicket(anyString()))
.thenThrow(new IllegalStateException("Modelos aún cargando"));
mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(Map.of("description", "Mi pedido está perdido"))))
.andExpect(status().isServiceUnavailable())
.andExpect(jsonPath("$.source").value("MODEL_LOADER"));
}
}
}
|