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.system.domain.SysFeedbackCreateRequest; import com.ruoyi.system.service.impl.SysFeedbackService; import java.util.*; import org.junit.jupiter.api.Test; 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.mock.mockito.MockBean; 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.*; /** Guarded real dev SQL, all fixtures roll back; only mocked mail transport can run. */ @EnabledIfSystemProperty(named="feedbackNotificationDbTests",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"}) class FeedbackNotificationDatabaseTest { @Autowired JdbcTemplate db; @Autowired PlatformTransactionManager transactions; @Autowired FeedbackNotificationService notifications; @Autowired SysFeedbackService feedbacks; @MockBean FeedbackTriageClient triage; @MockBean FeedbackMailSender mail; @Test void classificationPreviewRolesStaleGuardDuplicateSendAndUnknownDeliveryRollBack() throws Exception { assertEquals("cmvr-project-dev",db.queryForObject("SELECT DATABASE()",String.class)); assertEquals(0,db.queryForObject("SELECT COUNT(*) FROM sys_feedback_notification WHERE analysis_state IN ('PENDING','PROCESSING') OR mail_state IN ('QUEUED','SENDING')",Integer.class),"Do not compete with real pending notifications"); var user=new SysUser();user.setUserId(1L);user.setUserName("admin");user.setNickName("回滚测试"); SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(1L,1L,user,Set.of("*:*:*")),null)); ReflectionTestUtils.setField(notifications,"enabled",true); when(mail.ready()).thenReturn(true);when(mail.senderAddress()).thenReturn("sender@example.com"); when(triage.classify(any(),anyList())).thenReturn(new FeedbackTriageClient.Result("OTHER",0.98,"采购反馈")); var tx=new TransactionTemplate(transactions);var ids=new ArrayList(); try { tx.executeWithoutResult(status->{status.setRollbackOnly(); String suffix=UUID.randomUUID().toString().substring(0,8); db.update("INSERT INTO sys_role(role_name,role_key,role_sort,status,del_flag) VALUES(?,?,1,'0','0')","反馈测试角色", "feedback_"+suffix); Long role=db.queryForObject("SELECT role_id FROM sys_role WHERE role_key=?",Long.class,"feedback_"+suffix); db.update("INSERT INTO sys_user(user_name,nick_name,email,status,del_flag) VALUES(?,?,?,'0','0')","feedback_"+suffix,"测试收件人","recipient@example.com"); Long recipient=db.queryForObject("SELECT user_id FROM sys_user WHERE user_name=?",Long.class,"feedback_"+suffix); db.update("INSERT INTO sys_user_role(user_id,role_id) VALUES(?,?)",recipient,role); // Reset only transaction-local configuration; restores original role routes on rollback. db.update("DELETE FROM sys_feedback_notify_route WHERE module='OTHER'"); notifications.saveRoute(new FeedbackNotificationService.RouteRequest("OTHER",List.of(role),false,0)); assertThrows(ServiceException.class,()->notifications.saveRoute(new FeedbackNotificationService.RouteRequest("OTHER",List.of(role),false,0))); var feedback=feedbacks.create(new SysFeedbackCreateRequest("BUG","回滚测试采购问题","只是验证通知,不发送真实邮件","/procurement/details","采购明细",List.of())); Long id=feedback.getId();ids.add(id); assertEquals("PENDING",notifications.detail(id).get("analysisState")); notifications.processPending();assertEquals("COMPLETE",notifications.detail(id).get("analysisState")); var plan=notifications.preview(id);assertEquals(List.of("recipient@example.com"),plan.get("recipients")); assertFalse(plan.get("body").toString().contains("http://192.168.28.10:9000")); int version=((Number)plan.get("version")).intValue(); assertThrows(ServiceException.class,()->notifications.send(id,new FeedbackNotificationService.SendRequest(version,"old-token",false))); notifications.send(id,new FeedbackNotificationService.SendRequest(version,plan.get("previewToken").toString(),false)); assertThrows(ServiceException.class,()->notifications.send(id,new FeedbackNotificationService.SendRequest(version,plan.get("previewToken").toString(),false))); notifications.processPending();assertEquals("SENT",notifications.detail(id).get("mailState")); notifications.processPending(); try { verify(mail,times(1)).send(eq(List.of("recipient@example.com")),contains("回滚测试采购问题"),anyString(),anyString()); }catch(Exception e){throw new RuntimeException(e);} // New notification with an ambiguous SMTP result must not automatically resend. var second=feedbacks.create(new SysFeedbackCreateRequest("FEATURE","回滚测试未知送达","通知失败不丢失反馈","/inventory","库存",List.of())); Long id2=second.getId();ids.add(id2);notifications.processPending(); try { doThrow(new RuntimeException("simulated connection loss")).when(mail).send(anyList(),anyString(),anyString(),anyString()); }catch(Exception e){throw new RuntimeException(e);} var p2=notifications.preview(id2);notifications.send(id2,new FeedbackNotificationService.SendRequest(((Number)p2.get("version")).intValue(),p2.get("previewToken").toString(),false)); notifications.processPending();assertEquals("UNKNOWN",notifications.detail(id2).get("mailState")); notifications.processPending();var p3=notifications.preview(id2); assertThrows(ServiceException.class,()->notifications.send(id2,new FeedbackNotificationService.SendRequest(((Number)p3.get("version")).intValue(),p3.get("previewToken").toString(),false))); try { verify(mail,times(2)).send(anyList(),anyString(),anyString(),anyString()); }catch(Exception e){throw new RuntimeException(e);} }); for(Long id:ids)assertEquals(0,db.queryForObject("SELECT COUNT(*) FROM sys_feedback WHERE id=?",Integer.class,id)); }finally{ReflectionTestUtils.setField(notifications,"enabled",false);SecurityContextHolder.clearContext();} } }