File size: 9,780 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
package com.anthony.failsafeapi.service;

import com.anthony.failsafeapi.audit.TokenAuditRepository;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.*;

/**
 * Tests para DataRetentionService.
 *
 * la purga se hace en lotes pequeΓ±os
 * (deleteBatchBefore con LIMIT 1000) en vez de un DELETE masivo ΓΊnico.
 * Estos tests verifican el comportamiento del loop, no la SQL subyacente.
 *
 * Conceptos clave:
 *  - MAX_BATCHES_PER_RUN: lΓ­mite de seguridad (100 lotes por ejecuciΓ³n)
 *  - Cada lote es independiente: si uno falla, los anteriores se mantienen
 *  - El loop para cuando un lote devuelve 0 (no hay mΓ‘s registros viejos)
 */
@ExtendWith(MockitoExtension.class)
@DisplayName("DataRetentionService - Purga de registros de auditorΓ­a (batching)")
class DataRetentionServiceTest {

    @Mock
    private TokenAuditRepository auditRepository;

    @InjectMocks
    private DataRetentionService dataRetentionService;

    // ─────────────────────────────────────────────────────────────
    // CΓ‘lculo del cutoff date (~30 dΓ­as atrΓ‘s)
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("CΓ‘lculo de fecha de corte")
    class CutoffDateTests {

        @Test
        @DisplayName("Llama a deleteBatchBefore con fecha de hace ~30 dΓ­as")
        void shouldCallDeleteWithCutoff30DaysAgo() {
            // Primer lote: devuelve 0 β†’ el loop termina inmediatamente
            when(auditRepository.deleteBatchBefore(any(Instant.class), anyInt()))
                    .thenReturn(0);

            dataRetentionService.purgeOldAuditRecords();

            ArgumentCaptor<Instant> cutoffCaptor = ArgumentCaptor.forClass(Instant.class);
            verify(auditRepository).deleteBatchBefore(cutoffCaptor.capture(), anyInt());

            Instant capturedCutoff = cutoffCaptor.getValue();
            Instant expected30DaysAgo = Instant.now().minus(30, ChronoUnit.DAYS);

            // Tolerancia de 5 segundos para tiempo de ejecuciΓ³n del test
            assertThat(capturedCutoff)
                    .isAfter(expected30DaysAgo.minusSeconds(5))
                    .isBefore(expected30DaysAgo.plusSeconds(5));
        }

        @Test
        @DisplayName("Pasa BATCH_SIZE como lΓ­mite a deleteBatchBefore")
        void shouldPassBatchSizeAsLimit() {
            when(auditRepository.deleteBatchBefore(any(), anyInt())).thenReturn(0);

            dataRetentionService.purgeOldAuditRecords();

            ArgumentCaptor<Integer> limitCaptor = ArgumentCaptor.forClass(Integer.class);
            verify(auditRepository).deleteBatchBefore(any(), limitCaptor.capture());

            // El batch size debe ser positivo (el valor exacto es 1000 pero no
            // queremos acoplar el test a una constante mΓ‘gica β€” solo verificar
            // que es razonable)
            assertThat(limitCaptor.getValue()).isPositive().isLessThanOrEqualTo(10000);
        }
    }

    // ─────────────────────────────────────────────────────────────
    // Comportamiento del loop de lotes
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("Loop de borrado por lotes")
    class BatchLoopTests {

        @Test
        @DisplayName("No lanza excepciΓ³n cuando el repositorio elimina registros")
        void shouldNotThrowWhenDeletionSucceeds() {
            // 3 lotes de 1000 y luego 0 β†’ loop termina
            when(auditRepository.deleteBatchBefore(any(), anyInt()))
                    .thenReturn(1000, 1000, 1000, 0);

            assertThatNoException().isThrownBy(() ->
                    dataRetentionService.purgeOldAuditRecords());
        }

        @Test
        @DisplayName("No lanza excepciΓ³n cuando no hay registros a eliminar (primer lote devuelve 0)")
        void shouldNotThrowWhenNothingToDelete() {
            when(auditRepository.deleteBatchBefore(any(), anyInt())).thenReturn(0);

            assertThatNoException().isThrownBy(() ->
                    dataRetentionService.purgeOldAuditRecords());
        }

        @Test
        @DisplayName("Cuando el primer lote devuelve 0, solo se llama una vez al repositorio")
        void shouldCallRepositoryOnceWhenFirstBatchIsEmpty() {
            when(auditRepository.deleteBatchBefore(any(), anyInt())).thenReturn(0);

            dataRetentionService.purgeOldAuditRecords();

            verify(auditRepository, times(1)).deleteBatchBefore(any(), anyInt());
        }

        @Test
        @DisplayName("Ejecuta varios lotes hasta que uno devuelve 0")
        void shouldExecuteMultipleBatchesUntilEmpty() {
            // 5 lotes con datos, lote 6 devuelve 0 β†’ loop termina
            when(auditRepository.deleteBatchBefore(any(), anyInt()))
                    .thenReturn(1000, 1000, 1000, 1000, 1000, 0);

            dataRetentionService.purgeOldAuditRecords();

            // Debe llamarse 6 veces: 5 con datos + 1 con 0
            verify(auditRepository, times(6)).deleteBatchBefore(any(), anyInt());
        }

        @Test
        @DisplayName("Lotes con menos de BATCH_SIZE tambiΓ©n terminan el loop")
        void shouldStopLoopWhenBatchReturnsFewerThanBatchSize() {
            // Un lote que devuelve 500 (menos de 1000) y luego 0
            // el loop se detiene cuando devuelve 0, no cuando devuelve < BATCH_SIZE
            // porque el repositorio puede devolver < 1000 si quedan menos registros
            when(auditRepository.deleteBatchBefore(any(), anyInt()))
                    .thenReturn(500, 0);

            dataRetentionService.purgeOldAuditRecords();

            verify(auditRepository, times(2)).deleteBatchBefore(any(), anyInt());
        }
    }

    // ─────────────────────────────────────────────────────────────
    // LΓ­mite de seguridad (MAX_BATCHES_PER_RUN)
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("LΓ­mite de seguridad por ejecuciΓ³n")
    class MaxBatchesLimitTests {

        @Test
        @DisplayName("Se detiene despuΓ©s de MAX_BATCHES_PER_RUN lotes aunque queden registros")
        void shouldStopAfterMaxBatchesPerRun() {
            // El repositorio siempre devuelve 1000 (nunca se vacΓ­a)
            // El loop debe detenerse en MAX_BATCHES_PER_RUN (100)
            when(auditRepository.deleteBatchBefore(any(), anyInt())).thenReturn(1000);

            dataRetentionService.purgeOldAuditRecords();

            // Debe llamarse exactamente MAX_BATCHES_PER_RUN veces (100)
            // Si este nΓΊmero mΓ‘gico cambia en el cΓ³digo, actualizar el test.
            verify(auditRepository, times(100)).deleteBatchBefore(any(), anyInt());
        }
    }

    // ─────────────────────────────────────────────────────────────
    // Resistencia a fallos
    // ─────────────────────────────────────────────────────────────
    @Nested
    @DisplayName("Resistencia a fallos del repositorio")
    class RepositoryFailureTests {

        @Test
        @DisplayName("No propaga excepciΓ³n cuando el repositorio falla en el primer lote")
        void shouldNotPropagateRepositoryExceptionOnFirstBatch() {
            when(auditRepository.deleteBatchBefore(any(), anyInt()))
                    .thenThrow(new RuntimeException("Database connection lost"));

            assertThatNoException().isThrownBy(() ->
                    dataRetentionService.purgeOldAuditRecords());
        }

        @Test
        @DisplayName("Si un lote falla a mitad del proceso, los lotes anteriores ya se ejecutaron")
        void shouldKeepPreviousBatchesWhenOneFails() {
            // Lote 1 y 2: exitosos (1000 registros cada uno)
            // Lote 3: falla
            when(auditRepository.deleteBatchBefore(any(), anyInt()))
                    .thenReturn(1000, 1000)
                    .thenThrow(new RuntimeException("Connection lost on batch 3"));

            // El mΓ©todo debe absorber el error y no lanzar
            assertThatNoException().isThrownBy(() ->
                    dataRetentionService.purgeOldAuditRecords());

            // Lotes 1 y 2 ya se ejecutaron antes del fallo (commit atΓ³mico por lote)
            verify(auditRepository, times(3)).deleteBatchBefore(any(), anyInt());
        }
    }
}