155 lines
12 KiB
Java
155 lines
12 KiB
Java
|
|
package com.ruoyi.system.notification;
|
||
|
|
|
||
|
|
import com.ruoyi.RuoYiApplication;
|
||
|
|
import com.ruoyi.common.core.domain.entity.SysUser;
|
||
|
|
import com.ruoyi.common.core.domain.model.LoginUser;
|
||
|
|
import com.ruoyi.common.exception.ServiceException;
|
||
|
|
import com.ruoyi.common.notification.NotificationGateway.*;
|
||
|
|
import com.ruoyi.common.notification.NotificationPolicy;
|
||
|
|
import com.ruoyi.common.utils.SecurityUtils;
|
||
|
|
import java.util.*;
|
||
|
|
import org.junit.jupiter.api.*;
|
||
|
|
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
||
|
|
import org.springframework.boot.test.context.SpringBootTest;
|
||
|
|
import org.springframework.boot.test.context.TestConfiguration;
|
||
|
|
import org.springframework.boot.test.mock.mockito.MockBean;
|
||
|
|
import org.springframework.context.annotation.Bean;
|
||
|
|
import org.springframework.context.annotation.Import;
|
||
|
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||
|
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||
|
|
import org.springframework.test.util.ReflectionTestUtils;
|
||
|
|
import org.springframework.transaction.PlatformTransactionManager;
|
||
|
|
import org.springframework.transaction.support.TransactionTemplate;
|
||
|
|
import static org.junit.jupiter.api.Assertions.*;
|
||
|
|
import static org.mockito.Mockito.*;
|
||
|
|
import static org.mockito.ArgumentMatchers.*;
|
||
|
|
|
||
|
|
/** Every fixture rolls back in the guarded dev database. Mail is always mocked. */
|
||
|
|
@EnabledIfSystemProperty(named="notificationDbTests",matches="true")
|
||
|
|
@SpringBootTest(classes=RuoYiApplication.class,webEnvironment=SpringBootTest.WebEnvironment.MOCK,
|
||
|
|
properties={"notification-center.enabled=false","feedback-notification.enabled=false","minio.enabled=false","spring.quartz.auto-startup=false","spring.devtools.restart.enabled=false","logging.level.com.ruoyi=warn","logging.level.org.springframework=warn"})
|
||
|
|
@Import(NotificationDatabaseTest.TestPolicies.class)
|
||
|
|
class NotificationDatabaseTest {
|
||
|
|
@Autowired JdbcTemplate db;
|
||
|
|
@Autowired PlatformTransactionManager transactions;
|
||
|
|
@Autowired NotificationService service;
|
||
|
|
@Autowired MutablePolicy policy;
|
||
|
|
@MockBean NotificationMailSender mail;
|
||
|
|
|
||
|
|
@TestConfiguration static class TestPolicies {
|
||
|
|
@Bean MutablePolicy notificationTestPolicy(){return new MutablePolicy();}
|
||
|
|
}
|
||
|
|
static class MutablePolicy implements NotificationPolicy {
|
||
|
|
boolean allowed=true;
|
||
|
|
public String businessType(){return "TEST_SCOPE";}
|
||
|
|
public void checkPublisher(Command command){if(!SecurityUtils.isAdmin()||!"fixture".equals(command.businessId()))throw new ServiceException("denied",403);}
|
||
|
|
public boolean canReceive(long userId,Command command){return allowed;}
|
||
|
|
}
|
||
|
|
@BeforeEach void setup() {
|
||
|
|
assertEquals("cmvr-project-dev",db.queryForObject("SELECT DATABASE()",String.class));
|
||
|
|
assertEquals(0,db.queryForObject("SELECT COUNT(*) FROM sys_notification_delivery WHERE channel='EMAIL' AND state IN ('QUEUED','SENDING')",Integer.class),"Never compete with real pending deliveries");
|
||
|
|
ReflectionTestUtils.setField(service,"enabled",true);policy.allowed=true;login(1);
|
||
|
|
when(mail.ready()).thenReturn(true);
|
||
|
|
}
|
||
|
|
@AfterEach void cleanup(){ReflectionTestUtils.setField(service,"enabled",false);SecurityContextHolder.clearContext();}
|
||
|
|
private void login(long id) {
|
||
|
|
var user=new SysUser();user.setUserId(id);user.setUserName("notification-test");
|
||
|
|
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(id,1L,user,Set.of("*:*:*")),null));
|
||
|
|
}
|
||
|
|
record Fixture(long first,long second,long missing,long role) { }
|
||
|
|
private Fixture fixture() {
|
||
|
|
String suffix=UUID.randomUUID().toString().substring(0,8);
|
||
|
|
var ids=new ArrayList<Long>();
|
||
|
|
for(int i=0;i<3;i++) {
|
||
|
|
String name="nt_"+suffix+"_"+i;
|
||
|
|
db.update("INSERT INTO sys_user(user_name,nick_name,email,status,del_flag) VALUES(?,?,?,'0','0')",name,"通知回滚测试",i==2?"":"shared@example.com");
|
||
|
|
ids.add(db.queryForObject("SELECT user_id FROM sys_user WHERE user_name=?",Long.class,name));
|
||
|
|
}
|
||
|
|
db.update("INSERT INTO sys_role(role_name,role_key,role_sort,status,del_flag) VALUES(?,?,1,'0','0')","通知回滚测试","nt_"+suffix);
|
||
|
|
long role=db.queryForObject("SELECT role_id FROM sys_role WHERE role_key=?",Long.class,"nt_"+suffix);
|
||
|
|
for(long id:ids.subList(0,2))db.update("INSERT INTO sys_user_role(user_id,role_id) VALUES(?,?)",id,role);
|
||
|
|
return new Fixture(ids.get(0),ids.get(1),ids.get(2),role);
|
||
|
|
}
|
||
|
|
private Command command(String type,String key,Set<Long> users,Set<Long> roles) {
|
||
|
|
return new Command(type,"fixture",key,"待处理通知","只是回归测试,邮件不会发往外部",users,roles,Set.of(Channel.INBOX,Channel.EMAIL),"/index");
|
||
|
|
}
|
||
|
|
private void rollback(java.util.function.Consumer<Fixture> test) {
|
||
|
|
new TransactionTemplate(transactions).executeWithoutResult(status->{status.setRollbackOnly();test.accept(fixture());});
|
||
|
|
}
|
||
|
|
@SuppressWarnings("unchecked") private List<Map<String,Object>> items(){return (List<Map<String,Object>>)service.inbox(null,20,false).get("items");}
|
||
|
|
private long inboxId(long user,String eventId){return db.queryForObject("SELECT id FROM sys_notification_delivery WHERE event_id=? AND user_id=? AND channel='INBOX'",Long.class,eventId,user);}
|
||
|
|
|
||
|
|
@Test void bothChannelsDeduplicateUserRoleAndEmailAndKeepMissingEmailInbox() throws Exception {
|
||
|
|
rollback(f->{
|
||
|
|
var c=command("SYSTEM_MESSAGE","both:"+f.first(),Set.of(f.first(),f.missing()),Set.of(f.role()));
|
||
|
|
var receipt=service.publish(c);assertEquals(3,receipt.inboxDelivered());assertEquals(2,receipt.emailQueued());assertEquals(1,receipt.emailBlocked());
|
||
|
|
var duplicate=service.publish(c);assertTrue(duplicate.duplicate());assertEquals(receipt.eventId(),duplicate.eventId());
|
||
|
|
var changed=new Command(c.businessType(),c.businessId(),c.eventKey(),"changed",c.content(),c.userIds(),c.roleIds(),c.channels(),c.sourcePath());
|
||
|
|
assertThrows(ServiceException.class,()->service.publish(changed));
|
||
|
|
try{verify(mail,never()).send(anyList(),anyString(),anyString(),anyString());}catch(Exception e){throw new RuntimeException(e);}
|
||
|
|
login(f.first());assertEquals(1,items().size());long own=inboxId(f.first(),receipt.eventId());long other=inboxId(f.second(),receipt.eventId());
|
||
|
|
assertEquals(404,assertThrows(ServiceException.class,()->service.inboxDetail(other)).getCode());
|
||
|
|
assertThrows(ServiceException.class,()->service.markRead(List.of(own,other)));
|
||
|
|
assertNull(db.queryForObject("SELECT read_at FROM sys_notification_delivery WHERE id=?",java.sql.Timestamp.class,own));
|
||
|
|
service.markRead(List.of(own));service.markRead(List.of(own));assertEquals(0L,service.unread().get("count"));
|
||
|
|
assertThrows(ServiceException.class,()->service.deliveries(receipt.eventId()));
|
||
|
|
login(1);service.processPending();service.processPending();
|
||
|
|
assertEquals(2,service.deliveries(receipt.eventId()).stream().filter(d->d.channel()==Channel.EMAIL&&d.state().equals("SENT")).count());
|
||
|
|
try{verify(mail,times(1)).send(eq(List.of("shared@example.com")),anyString(),anyString(),anyString());}catch(Exception e){throw new RuntimeException(e);}
|
||
|
|
login(f.missing());assertEquals(1,items().size()); // Email failure never loses station inbox.
|
||
|
|
});
|
||
|
|
}
|
||
|
|
@Test void liveBusinessRevocationHidesContentAndCancelsUnsentMail() {
|
||
|
|
rollback(f->{
|
||
|
|
var r=service.publish(command("TEST_SCOPE","revoked:"+f.first(),Set.of(f.first()),Set.of()));
|
||
|
|
policy.allowed=false;login(f.first());assertTrue(items().isEmpty());assertEquals(0L,service.unread().get("count"));
|
||
|
|
assertEquals(404,assertThrows(ServiceException.class,()->service.inboxDetail(inboxId(f.first(),r.eventId()))).getCode());
|
||
|
|
login(1);service.processPending();assertTrue(service.deliveries(r.eventId()).stream().anyMatch(d->d.channel()==Channel.EMAIL&&d.state().equals("CANCELLED")));
|
||
|
|
try{verify(mail,never()).send(anyList(),anyString(),anyString(),anyString());}catch(Exception e){throw new RuntimeException(e);}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
@Test void roleRevocationRevalidatesPerUserAndSharedMailboxStillNotifiesRemainingMember() {
|
||
|
|
rollback(f->{
|
||
|
|
var r=service.publish(command("SYSTEM_MESSAGE","role:"+f.first(),Set.of(),Set.of(f.role())));
|
||
|
|
db.update("DELETE FROM sys_user_role WHERE user_id=? AND role_id=?",f.first(),f.role());
|
||
|
|
login(f.first());assertTrue(items().isEmpty());login(1);service.processPending();
|
||
|
|
var statuses=service.deliveries(r.eventId());
|
||
|
|
assertTrue(statuses.stream().anyMatch(d->d.userId()==f.first()&&d.channel()==Channel.EMAIL&&d.state().equals("CANCELLED")));
|
||
|
|
assertTrue(statuses.stream().anyMatch(d->d.userId()==f.second()&&d.channel()==Channel.EMAIL&&d.state().equals("SENT")));
|
||
|
|
try{verify(mail,times(1)).send(anyList(),anyString(),anyString(),anyString());}catch(Exception e){throw new RuntimeException(e);}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
@Test void ambiguousSharedMailboxIsNotAutoRetriedAndExplicitRetryIsDeduplicated() throws Exception {
|
||
|
|
doThrow(new RuntimeException("simulated timeout")).when(mail).send(anyList(),anyString(),anyString(),anyString());
|
||
|
|
rollback(f->{
|
||
|
|
var r=service.publish(command("SYSTEM_MESSAGE","unknown:"+f.first(),Set.of(f.first(),f.second()),Set.of()));
|
||
|
|
service.processPending();service.processPending();
|
||
|
|
var unknown=service.deliveries(r.eventId()).stream().filter(d->d.channel()==Channel.EMAIL).toList();
|
||
|
|
assertEquals(2,unknown.size());assertTrue(unknown.stream().allMatch(d->d.state().equals("UNKNOWN")));
|
||
|
|
var d=unknown.get(0);assertThrows(ServiceException.class,()->service.retryEmail(d.id(),d.version(),false));
|
||
|
|
service.retryEmail(d.id(),d.version(),true);
|
||
|
|
try{doNothing().when(mail).send(anyList(),anyString(),anyString(),anyString());}catch(Exception e){throw new RuntimeException(e);}
|
||
|
|
service.processPending();assertTrue(service.deliveries(r.eventId()).stream().filter(x->x.channel()==Channel.EMAIL).allMatch(x->x.state().equals("SENT")));
|
||
|
|
assertThrows(ServiceException.class,()->service.retryEmail(d.id(),d.version(),true));
|
||
|
|
try{verify(mail,times(2)).send(anyList(),anyString(),anyString(),anyString());}catch(Exception e){throw new RuntimeException(e);}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
@Test void changedAddressRequiresExplicitReviewAndRollbackLeavesNoNotification() {
|
||
|
|
var events=new ArrayList<String>();
|
||
|
|
rollback(f->{
|
||
|
|
var r=service.publish(command("SYSTEM_MESSAGE","email-change:"+f.first(),Set.of(f.first()),Set.of()));events.add(r.eventId());
|
||
|
|
db.update("UPDATE sys_user SET email='changed@example.com' WHERE user_id=?",f.first());
|
||
|
|
service.processPending();var d=service.deliveries(r.eventId()).stream().filter(x->x.channel()==Channel.EMAIL).findFirst().orElseThrow();assertEquals("REVIEW",d.state());
|
||
|
|
assertThrows(ServiceException.class,()->service.retryEmail(d.id(),d.version()-1,false));
|
||
|
|
service.retryEmail(d.id(),d.version(),false);service.processPending();
|
||
|
|
try{verify(mail).send(eq(List.of("changed@example.com")),anyString(),anyString(),anyString());}catch(Exception e){throw new RuntimeException(e);}
|
||
|
|
});
|
||
|
|
assertEquals(0,db.queryForObject("SELECT COUNT(*) FROM sys_notification_event WHERE id=?",Integer.class,events.get(0)));
|
||
|
|
}
|
||
|
|
@Test void ordinaryAccountCannotPublishAdministratorNamespaceEvenWithWildcardPermission() {
|
||
|
|
rollback(f->{login(f.first());assertEquals(403,assertThrows(ServiceException.class,()->service.publish(command("SYSTEM_MESSAGE","forbidden:"+f.first(),Set.of(f.second()),Set.of()))).getCode());});
|
||
|
|
}
|
||
|
|
}
|