-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathEventSystemIntegrationTest.java
More file actions
263 lines (223 loc) · 11 KB
/
Copy pathEventSystemIntegrationTest.java
File metadata and controls
263 lines (223 loc) · 11 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package com.digitalsanctuary.spring.user.integration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
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.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import com.digitalsanctuary.spring.user.audit.AuditEvent;
import com.digitalsanctuary.spring.user.event.OnRegistrationCompleteEvent;
import com.digitalsanctuary.spring.user.event.UserPreDeleteEvent;
import com.digitalsanctuary.spring.user.persistence.model.User;
import com.digitalsanctuary.spring.user.service.LoginAttemptService;
import com.digitalsanctuary.spring.user.service.UserEmailService;
import com.digitalsanctuary.spring.user.test.annotations.IntegrationTest;
import com.digitalsanctuary.spring.user.test.builders.UserTestDataBuilder;
@IntegrationTest
@TestPropertySource(properties = {"user.registration.sendVerificationEmail=true", "spring.main.allow-bean-definition-overriding=true"})
@Import(EventSystemIntegrationTest.TestEventConfiguration.class)
@DisplayName("Event System Integration Tests")
class EventSystemIntegrationTest {
@TestConfiguration
static class TestEventConfiguration {
@Bean
public TestEventCapture testEventCapture() {
return new TestEventCapture();
}
}
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private TestEventCapture eventCapture;
@MockitoBean
private UserEmailService userEmailService;
@MockitoBean
private LoginAttemptService loginAttemptService;
private User testUser;
@BeforeEach
void setUp() {
// The user must be UNVERIFIED (disabled): as of 4.4.0 RegistrationListener skips sending the
// verification email when the user is already enabled, which is the realistic state for a brand-new
// registration. An enabled user here would make the registration-email assertions never fire.
testUser = UserTestDataBuilder.aUser().withId(1L).withEmail("test@example.com").withFirstName("Test").withLastName("User").unverified().build();
eventCapture.clear();
}
@Nested
@DisplayName("Registration Event Flow Tests")
class RegistrationEventFlowTests {
@Test
@DisplayName("Registration event triggers email service")
void registrationEvent_triggersEmailService() throws Exception {
// Given
String appUrl = "https://example.com";
Locale locale = Locale.ENGLISH;
CountDownLatch latch = new CountDownLatch(1);
doAnswer(invocation -> {
latch.countDown();
return null;
}).when(userEmailService).sendRegistrationVerificationEmail(anyLong(), anyString());
// When
OnRegistrationCompleteEvent event = OnRegistrationCompleteEvent.builder().userId(testUser.getId()).userEmail(testUser.getEmail())
.userEnabled(testUser.isEnabled()).locale(locale).appUrl(appUrl).build();
eventPublisher.publishEvent(event);
// Then
assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
verify(userEmailService).sendRegistrationVerificationEmail(testUser.getId(), appUrl);
assertThat(eventCapture.getCapturedEvents()).filteredOn(e -> e instanceof OnRegistrationCompleteEvent).hasSize(1);
}
@Test
@DisplayName("Multiple registration events are handled independently")
void multipleRegistrationEvents_handledIndependently() throws Exception {
// Given
User user1 = UserTestDataBuilder.aUser().withId(10L).withEmail("user1@example.com").build();
User user2 = UserTestDataBuilder.aUser().withId(20L).withEmail("user2@example.com").build();
CountDownLatch latch = new CountDownLatch(2);
doAnswer(invocation -> {
latch.countDown();
return null;
}).when(userEmailService).sendRegistrationVerificationEmail(anyLong(), anyString());
// When
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user1.getId(), user1.getEmail(), user1.isEnabled(), Locale.ENGLISH, "app1"));
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user2.getId(), user2.getEmail(), user2.isEnabled(), Locale.FRENCH, "app2"));
// Then
assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
verify(userEmailService).sendRegistrationVerificationEmail(user1.getId(), "app1");
verify(userEmailService).sendRegistrationVerificationEmail(user2.getId(), "app2");
}
}
@Nested
@DisplayName("Authentication Event Flow Tests")
class AuthenticationEventFlowTests {
@Test
@DisplayName("Success event updates login attempt service")
void successEvent_updatesLoginAttemptService() {
// Given
String username = "test@example.com";
Authentication auth = new UsernamePasswordAuthenticationToken(username, "password");
// When
eventPublisher.publishEvent(new AuthenticationSuccessEvent(auth));
// Then
verify(loginAttemptService, timeout(1000)).loginSucceeded(username);
assertThat(eventCapture.getCapturedEvents()).filteredOn(e -> e instanceof AuthenticationSuccessEvent).hasSize(1);
}
@Test
@DisplayName("Failure event updates login attempt service")
void failureEvent_updatesLoginAttemptService() {
// Given
String username = "test@example.com";
Authentication auth = new UsernamePasswordAuthenticationToken(username, "password");
BadCredentialsException exception = new BadCredentialsException("Bad credentials");
// When
eventPublisher.publishEvent(new AuthenticationFailureBadCredentialsEvent(auth, exception));
// Then
verify(loginAttemptService, timeout(1000)).loginFailed(username);
assertThat(eventCapture.getCapturedEvents()).filteredOn(e -> e instanceof AuthenticationFailureBadCredentialsEvent).hasSize(1);
}
}
@Nested
@DisplayName("User Deletion Event Flow Tests")
class UserDeletionEventFlowTests {
@Test
@DisplayName("UserPreDeleteEvent is captured correctly")
void userPreDeleteEvent_capturedCorrectly() {
// When
UserPreDeleteEvent event = new UserPreDeleteEvent(this, testUser.getId(), testUser.getEmail());
eventPublisher.publishEvent(event);
// Then
assertThat(eventCapture.getCapturedEvents()).filteredOn(e -> e instanceof UserPreDeleteEvent).hasSize(1).first().satisfies(e -> {
UserPreDeleteEvent deleteEvent = (UserPreDeleteEvent) e;
assertThat(deleteEvent.getUserId()).isEqualTo(1L);
assertThat(deleteEvent.getUserEmail()).isEqualTo(testUser.getEmail());
});
}
}
@Nested
@DisplayName("Audit Event Flow Tests")
class AuditEventFlowTests {
@Test
@DisplayName("Audit events are captured")
void auditEvents_areCaptured() {
// Given
AuditEvent auditEvent = AuditEvent.builder().source(this).user(testUser).action("Test Action").actionStatus("Success")
.message("Test audit event").build();
// When
eventPublisher.publishEvent(auditEvent);
// Then
assertThat(eventCapture.getCapturedEvents()).filteredOn(e -> e instanceof AuditEvent).hasSize(1).first().satisfies(e -> {
AuditEvent captured = (AuditEvent) e;
assertThat(captured.getAction()).isEqualTo("Test Action");
assertThat(captured.getUser()).isEqualTo(testUser);
});
}
}
@Nested
@DisplayName("Event Ordering Tests")
class EventOrderingTests {
@Test
@DisplayName("Events are processed in order")
void events_processedInOrder() throws Exception {
// Given
CountDownLatch latch = new CountDownLatch(3);
List<String> processedEvents = Collections.synchronizedList(new ArrayList<>());
doAnswer(invocation -> {
processedEvents.add("registration");
latch.countDown();
return null;
}).when(userEmailService).sendRegistrationVerificationEmail(anyLong(), anyString());
doAnswer(invocation -> {
processedEvents.add("login-success");
latch.countDown();
return null;
}).when(loginAttemptService).loginSucceeded(any());
// When
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(testUser.getId(), testUser.getEmail(), testUser.isEnabled(), Locale.ENGLISH, "app"));
eventPublisher.publishEvent(new AuthenticationSuccessEvent(new UsernamePasswordAuthenticationToken("user", "pass")));
eventPublisher.publishEvent(new UserPreDeleteEvent(this, testUser.getId(), testUser.getEmail()));
processedEvents.add("delete");
latch.countDown();
// Then
assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(processedEvents).hasSize(3);
}
}
/**
* Test utility class to capture all events for verification
*/
static class TestEventCapture {
private final List<Object> capturedEvents = Collections.synchronizedList(new ArrayList<>());
@EventListener
public void handleEvent(Object event) {
capturedEvents.add(event);
}
public List<Object> getCapturedEvents() {
return new ArrayList<>(capturedEvents);
}
public void clear() {
capturedEvents.clear();
}
}
}