function* name([param[, param[, ... param]]]) { statements }

本文详细介绍了JavaScript中的生成器函数,包括如何定义和使用生成器函数、生成器函数的执行流程及特点。通过实例展示了生成器函数的迭代器对象、next方法的使用,以及显式返回的情况。
function* name([param[, param[, ... param]]]) { statements }

name是函数名称,param是要传递的一个参数,一个函数最多可以传递255个参数,statements是普通的js语句。

描述:

生成器函数在执行时能暂停,后面又能从暂停处继续执行。

调用一个生成器函数并不会马上执行它里面的语句,而是返回一个这个生成器的 迭代器(iterator )对象。当这个迭代器的 next() 方法被首次(后续)调用时,其内的语句会执行到第一个(后续)出现yield的位置为止,yield 后紧跟迭代器要返回的值。或者如果用的是 yield*(多了个星号),则表示将执行权移交给另一个生成器函数(当前生成器暂停执行)。

next()方法返回一个对象,这个对象包含两个属性:value 和 done,value 属性表示本次 yield 表达式的返回值,done 属性为布尔类型,表示生成器后续是否还有 yield 语句,即生成器函数是否已经执行完毕并返回。

调用 next()方法时,如果传入了参数,那么这个参数会作为上一条执行的  yield 语句的返回


function *gen(){
    yield 10;
    y=yield 'foo';
    yield y;
}

var gen_obj=gen();
console.log(gen_obj.next());// 执行 yield 10,返回 10
console.log(gen_obj.next());// 执行 yield 'foo',返回 'foo'
console.log(gen_obj.next(10));// 将 10 赋给上一条 yield 'foo' 的左值,即执行 y=10,返回 10
console.log(gen_obj.next());// 执行完毕,value 为 undefined,done 为 true

当在生成器函数中显式 return 时,会导致生成器立即变为完成状态,即调用 next() 方法返回的对象的 done 为 true。如果 return 后面跟了一个值,那么这个值会作为当前调用 next() 方法返回的 value 值。

function *createIterator() {
    let first = yield 1;
    let second = yield first + 2; // 4 + 2 
                                  // first =4 是next(4)将参数赋给上一条的
    yield second + 3;             // 5 + 3
}

let iterator = createIterator();

console.log(iterator.next());    // "{ value: 1, done: false }"
console.log(iterator.next(4));   // "{ value: 6, done: false }"
console.log(iterator.next(5));   // "{ value: 8, done: false }"
console.log(iterator.next());    // "{ value: undefined, done: true }"

显式返回

function* yieldAndReturn() {
  yield "Y";
  return "R";//显式返回处,可以观察到 done 也立即变为了 true
  yield "unreachable";// 不会被执行了
}

var gen = yieldAndReturn()
console.log(gen.next()); // { value: "Y", done: false }
console.log(gen.next()); // { value: "R", done: true }
console.log(gen.next()); // { value: undefined, done: true }

1生成器函数不能当构造器使用

function* f() {}
var obj = new f; // throws "TypeError: f is not a constructor"

传送门

### 数据库快速记忆法 为了帮助你快速记忆数据库相关的知识点,以下是根据提供的文件内容整理的快速记忆法。这些记忆点涵盖了数据库的基本概念、SQL语句、数据库设计等方面,帮助你在短时间内掌握核心内容。 --- #### **一、数据库基本概念** 1. **数据库 (Database)**: - **快速记忆**:长期存储的数据集合,是数据的“仓库”。 2. **数据库管理系统 (DBMS)**: - **快速记忆**:管理数据的“管家”,负责数据的存储、管理访问。 3. **数据库系统 (DBS)**: - **快速记忆**:由数据库、DBMS、应用系统数据库管理员构成的“数据生态系统”。 4. **数据模型**: - **快速记忆**:数据的“蓝图”,包括数据结构、操作完整性约束。 5. **关系模型**: - **快速记忆**:表的形式,每个表代表一个关系,行是元组,列是属性。 6. **E-R图 (Entity-Relationship Diagram)**: - **快速记忆**:实体是“东西”,关系是“联系”,用椭圆、矩形菱形表示。 7. **实体属性**: - **快速记忆**:实体是“对象”,属性是“特性”,如学生是实体,学号是属性。 8. **(Key)**: - **快速记忆**:主键唯一确定一行,外键关联其他表。 9. **完整性约束**: - **快速记忆**:实体完整性(主键唯一)、参照完整性(外键有效)、用户定义完整性(自定义规则)。 --- #### **二、SQL语句快速记忆** 1. **查询数据**: ```sql SELECT column1, column2 FROM table_name WHERE condition; ``` - **快速记忆**:`SELECT`选择列,`FROM`指定表,`WHERE`加条件。 2. **插入数据**: ```sql INSERT INTO table_name (column1, column2) VALUES (value1, value2); ``` - **快速记忆**:`INSERT INTO` + 表名 + (列名) + `VALUES` + ()。 3. **更新数据**: ```sql UPDATE table_name SET column1 = value1 WHERE condition; ``` - **快速记忆**:`UPDATE` + 表名 + `SET` + 列名 = 值 + `WHERE`条件。 4. **删除数据**: ```sql DELETE FROM table_name WHERE condition; ``` - **快速记忆**:`DELETE FROM` + 表名 + `WHERE`条件。 5. **分组查询**: ```sql SELECT column1, COUNT(column2) FROM table_name GROUP BY column1; ``` - **快速记忆**:`GROUP BY`分组,`COUNT`等聚合函数统计。 6. **排序查询**: ```sql SELECT column1, column2 FROM table_name ORDER BY column1 ASC/DESC; ``` - **快速记忆**:`ORDER BY`排序,`ASC`升序,`DESC`降序。 7. **连接查询**: - **内连接**:`INNER JOIN` + `ON`条件 - **左连接**:`LEFT JOIN` + `ON`条件 - **右连接**:`RIGHT JOIN` + `ON`条件 8. **子查询**: ```sql SELECT column_name FROM table_name WHERE column_name operator (SELECT column_name FROM table_name WHERE condition); ``` - **快速记忆**:子查询放在`WHERE`后面的括号中。 9. **创建索引**: ```sql CREATE INDEX index_name ON table_name (column_name); ``` - **快速记忆**:`CREATE INDEX` + 索引名 + `ON` + 表名 + (列名)。 10. **创建视图**: ```sql CREATE VIEW view_name AS SELECT column1, column2 FROM table_name WHERE condition; ``` - **快速记忆**:`CREATE VIEW` + 视图名 + `AS` + `SELECT`语句。 --- #### **三、数据库设计** 1. **数据库设计的六个阶段**: - **快速记忆**:需求分析 → 概念设计 → 逻辑设计 → 物理设计 → 实施 → 运行维护。 2. **范式 (Normalization)**: - **第一范式 (1NF)**:列不可再分,每个值唯一。 - **第二范式 (2NF)**:满足1NF,且非主属性完全依赖主键。 - **第三范式 (3NF)**:满足2NF,且非主属性不依赖其他非主属性。 3. **E-R图转换**: - **快速记忆**:E-R图 → 关系模型,椭圆转实体,矩形转属性,菱形转关系。 --- #### **四、高级SQL功能** 1. **存储过程**: ```sql DELIMITER // CREATE PROCEDURE procedure_name (IN param1 datatype, OUT param2 datatype) BEGIN -- SQL statements END // DELIMITER ; ``` - **快速记忆**:`CREATE PROCEDURE` + 过程名 + 参数 + `BEGIN` + 语句 + `END`。 2. **触发器**: ```sql CREATE TRIGGER trigger_name BEFORE/AFTER event ON table_name FOR EACH ROW BEGIN -- SQL statements END; ``` - **快速记忆**:`CREATE TRIGGER` + 触发器名 + `BEFORE/AFTER` + 事件 + `ON` + 表名 + `FOR EACH ROW`。 3. **函数**: ```sql DELIMITER // CREATE FUNCTION function_name (param1 datatype, ...) RETURNS datatype BEGIN -- SQL statements RETURN result; END // DELIMITER ; ``` - **快速记忆**:`CREATE FUNCTION` + 函数名 + 参数 + `RETURNS` + 返回类型 + `BEGIN` + 语句 + `RETURN` + 结果。 --- ### 快速记忆总结 - **基本概念**:数据库是数据仓库,DBMS是管家,DBS是生态系统,E-R图是蓝图,实体属性是对象特性。 - **SQL语句**:`SELECT`查询,`INSERT`插入,`UPDATE`更新,`DELETE`删除,`GROUP BY`分组,`ORDER BY`排序,连接用`JOIN`,子查询用`WHERE`后的括号。 - **数据库设计**:六阶段,范式确保数据一致性,E-R图转换为关系模型。 - **高级功能**:存储过程、触发器、函数增强数据库功能。 转换为文字模式,不用代码不方便粘贴文档复习
06-25
/* * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved. */ package com.huawei.it.elogic.formula.helper import com.huawei.it.elogic.formula.constants.GroovyEvalConstant import com.huawei.it.publicsaas.framework.context.ContextUtils import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.ast.expr.ArgumentListExpression import org.codehaus.groovy.ast.expr.BinaryExpression import org.codehaus.groovy.ast.expr.ConstantExpression import org.codehaus.groovy.ast.expr.Expression import org.codehaus.groovy.ast.expr.GStringExpression import org.codehaus.groovy.ast.expr.ListExpression import org.codehaus.groovy.ast.expr.MethodCallExpression import org.codehaus.groovy.ast.expr.TernaryExpression import org.codehaus.groovy.ast.expr.TupleExpression import org.codehaus.groovy.control.CompilePhase import org.codehaus.groovy.control.SourceUnit import org.codehaus.groovy.transform.ASTTransformation import org.codehaus.groovy.transform.GroovyASTTransformation /** * groovy的AST树转化,适配fel * * @since 2024/2/22 */ @GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS) class DollarSignTransformer implements ASTTransformation { private static String CONSTANTEXPRESSION_METADATAMAP_KEY = "_IS_STRING" private static List<Class> NEED_CHANGE_PEXRS = Arrays.asList( BinaryExpression.class, MethodCallExpression.class, TernaryExpression.class, ArgumentListExpression.class ) @Override void visit(ASTNode[] nodes, SourceUnit source) { if (!GroovyEvalConstant.FIXED_GROOVY_VALUE.equals(ContextUtils.getValue(GroovyEvalConstant.FIXED_GROOVY_KEY))) { return } nodes.each { node -> { node.statementBlock.statements.each { statement -> { Expression expr = statement.expression if (expr instanceof GStringExpression) { statement.expression = getStringExprFromGStringExpr(expr) } else if (NEED_CHANGE_PEXRS.contains(expr.getClass())) { statement.expression = traverseExpr(expr) } } } } } } /** * 遍历expression,有子expression则递归处理 * @param expr expr */ Expression traverseExpr(Expression expr) { List<Expression> subExprs = getSubExprs(expr) for (int i = 0; i < subExprs.size(); i++) { Expression subExpr = subExprs[i] if (subExpr instanceof GStringExpression) { subExprs[i] = getStringExprFromGStringExpr(subExpr) } else if (NEED_CHANGE_PEXRS.contains(subExpr.getClass())) { subExprs[i] = traverseExpr(subExpr) } } expr = setSubExprs(expr, subExprs) return expr } /** * 将需要修改的expression的所有子expression组装成List返回 * @param exprs * @return */ private List<Expression> getSubExprs(Expression expr) { List<Expression> subExprs = new ArrayList<>() if (expr instanceof BinaryExpression) { subExprs.add(expr.leftExpression) subExprs.add(expr.rightExpression) } else if (expr instanceof MethodCallExpression) { subExprs = expr.arguments.expressions } else if (expr instanceof TernaryExpression) { subExprs.add(expr.booleanExpression) subExprs.add(expr.trueExpression) subExprs.add(expr.falseExpression) } else if (expr instanceof ListExpression) { subExprs = expr.expressions } return subExprs } /** * 将需要修改的expression的所有子expression组装成List返回 * @param exprs expr * @param newSubExprs 转化后的expression * @return 新的expression */ private Expression setSubExprs(Expression expr, List<Expression> newSubExprs) { if (expr instanceof BinaryExpression) { expr.leftExpression = newSubExprs[0] expr.rightExpression = newSubExprs[1] } else if (expr instanceof MethodCallExpression) { expr.setArguments(new TupleExpression(newSubExprs)) } else if (expr instanceof TernaryExpression) { expr = new TernaryExpression(newSubExprs[0], newSubExprs[1], newSubExprs[2]) } else if (expr instanceof ArgumentListExpression) { expr = new ArgumentListExpression(newSubExprs) } return expr } /** * GStringExpression转ConstantExpression,即$引用串转字符串 * * @param gStringExpr gStringExpr * @return ConstantExpression */ private ConstantExpression getStringExprFromGStringExpr(GStringExpression gStringExpr) { def constantExpr = new ConstantExpression(gStringExpr.verbatimText) constantExpr.lineNumber = gStringExpr.lineNumber constantExpr.columnNumber = gStringExpr.columnNumber constantExpr.lastLineNumber = gStringExpr.lastLineNumber constantExpr.lastColumnNumber = gStringExpr.lastColumnNumber Map map = new LinkedHashMap() map.put(CONSTANTEXPRESSION_METADATAMAP_KEY, true) constantExpr.metaDataMap = map return constantExpr } }
最新发布
09-06
以下是onlineReportServiceImplTest的代码:package com.jd.jacp.unit.report; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.jd.jacp.client.service.ICicdClient; import com.jd.jacp.client.service.ICmdbClient; import com.jd.jacp.client.service.ItsmClientService; import com.jd.jacp.common.service.UserHelper; import com.jd.jacp.common.vo.UserVO; import com.jd.jacp.common.vo.enums.YesOrNoEnum; import com.jd.jacp.demand.entity.BizDemandUser; import com.jd.jacp.demand.service.IBizDemandUserService; import com.jd.jacp.notify.entity.BizNotifyRule; import com.jd.jacp.notify.entity.BizNotifySetting; import com.jd.jacp.notify.enums.BizNotifySendWayEnum; import com.jd.jacp.notify.service.IBizNotifyRuleService; import com.jd.jacp.notify.service.IBizNotifySettingService; import com.jd.jacp.report.dto.*; import com.jd.jacp.report.entity.BizReport; import com.jd.jacp.report.entity.BizReportItem; import com.jd.jacp.report.enums.AcceptanceReportEnum; import com.jd.jacp.report.service.IBizReportItemService; import com.jd.jacp.report.service.IBizReportService; import com.jd.jacp.report.service.impl.OnlineReportServiceImpl; import com.jd.jacp.report.vo.SprintOnlineReportInfoVO; import com.jd.jacp.space.dto.CardQuery; import com.jd.jacp.space.dto.SubSystemByParamsDTO; import com.jd.jacp.space.entity.BizSpace; import com.jd.jacp.space.entity.BizSpaceCard; import com.jd.jacp.space.entity.BizSpaceSprint; import com.jd.jacp.space.service.IBizSpaceCardService; import com.jd.jacp.space.service.IBizSpaceService; import com.jd.jacp.space.service.IBizSpaceSettingService; import com.jd.jacp.space.service.IBizSpaceSprintService; import com.jd.jacp.space.vo.DetailVO; import com.jd.jacp.space.vo.QueryReportVO; import com.jd.jacp.unit.MockitoBasedTest; import com.msxf.devops.common.PageResult; import com.msxf.fcid.xmsg.reponse.ChatInfoDataResp; import org.apache.velocity.script.VelocityScriptEngine; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.when; import static org.mockito.Mockito.*; import javax.script.ScriptEngineManager; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; public class OnlineReportServiceImplTest extends MockitoBasedTest { @Spy @InjectMocks private OnlineReportServiceImpl onlineReportService; @Mock private IBizSpaceSprintService bizSpaceSprintService; @Mock private IBizSpaceSettingService spaceSettingService; @Mock private ScriptEngineManager scriptEngineManager; @Mock private IBizSpaceService bizSpaceService; @Mock private IBizReportService bizReportService; @Mock private IBizNotifySettingService bizNotifySettingService; @Mock private IBizNotifyRuleService bizNotifyRuleService; @Mock private ItsmClientService itsmClientService; @Mock private ICmdbClient cmdbClient; @Mock private ICicdClient cicdClient; @Mock private IBizSpaceCardService spaceCardService; @Mock private IBizDemandUserService demandUserService; @Mock private IBizReportItemService reportItemService; @Mock private UserHelper userHelper; @Test(expected = Exception.class) public void selectOnlineReportInfo_SprintNotExist_ThrowsException() { when(bizSpaceSprintService.getById(1)).thenReturn(null); onlineReportService.selectOnlineReportInfo(1); } @Test(expected = Exception.class) public void selectOnlineReportInfo_SpaceNotExist_ThrowsException() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setSpaceId(1); when(bizSpaceSprintService.getById(1)).thenReturn(sprint); when(bizSpaceService.getById(1)).thenReturn(null); onlineReportService.selectOnlineReportInfo(1); } @Test public void selectOnlineReportInfo_Successful() { // Mock data BizSpaceSprint sprint = new BizSpaceSprint().setId(1).setSpaceId(1); BizSpace space = new BizSpace().setId(1).setKey("key"); BizReport report = new BizReport().setId(1).setExtendInfo("{\"reportName\":\"Test Report\"}"); BizNotifySetting notifySetting = new BizNotifySetting().setId(1); BizNotifyRule notifyRule = new BizNotifyRule(); when(bizSpaceSprintService.getById(1)).thenReturn(sprint); when(bizSpaceService.getById(1)).thenReturn(space); when(bizReportService.selectReport(any(), any(), anyInt())).thenReturn(report); when(bizNotifySettingService.getOneBy(anyString(), anyString())).thenReturn(notifySetting); when(bizNotifyRuleService.getOneByNotifyId(anyInt())).thenReturn(notifyRule); SprintOnlineReportInfoVO result = onlineReportService.selectOnlineReportInfo(1); assertNotNull(result); assertEquals("Test Report", result.getOnlineReport().getReportName()); assertNotNull(result.getNotifySetting()); } @Test public void selectOnlineReportInfo_NoNotifySetting() { // Mock data BizSpaceSprint sprint = new BizSpaceSprint().setId(1).setSpaceId(1); BizSpace space = new BizSpace().setId(1).setKey("key"); BizReport report = new BizReport().setId(1).setExtendInfo("{\"reportName\":\"Test Report\"}"); when(bizSpaceSprintService.getById(1)).thenReturn(sprint); when(bizSpaceService.getById(1)).thenReturn(space); when(bizReportService.selectReport(any(), any(), anyInt())).thenReturn(report); when(bizNotifySettingService.getOneBy(anyString(), anyString())).thenReturn(null); SprintOnlineReportInfoVO result = onlineReportService.selectOnlineReportInfo(1); assertNotNull(result); assertEquals("Test Report", result.getOnlineReport().getReportName()); assertNull(result.getNotifySetting()); } @Test public void getOnlineReportBaseInfoDTO_test() { when(bizReportService.selectReport(any(), any(), any())).thenReturn(new BizReport()); when(bizNotifySettingService.getOneBy(any(), any())).thenReturn(null); onlineReportService.getOnlineReportBaseInfoDTO(new BizSpaceSprint(), "1"); } @Test public void saveSprintNotifySetting_Test() { SprintOnlineReportInfoVO reportInfoVO = new SprintOnlineReportInfoVO(); reportInfoVO.setNotifySetting(new NotifySettingDTO()); onlineReportService.saveSprintNotifySetting(reportInfoVO); } @Test(expected = Exception.class) public void saveSpaceNotifySetting_test() { onlineReportService.saveSpaceNotifySetting(new SprintOnlineReportInfoVO()); } @Test public void saveSpaceNotifySetting_test1() { when(bizSpaceSprintService.getById(any())).thenReturn(new BizSpaceSprint().setSpaceId(1)); SprintOnlineReportInfoVO reportInfoVO = new SprintOnlineReportInfoVO(); reportInfoVO.setNotifySetting(new NotifySettingDTO()); reportInfoVO.setOnlineReport(new OnlineReportBaseInfoDTO()); onlineReportService.saveSpaceNotifySetting(reportInfoVO); } @Test public void selectSprintCardPage_NoRecords_ReturnEmptyPage() { CardQuery query = new CardQuery(); query.setPageNum(1); query.setPageSize(10); Page<BizSpaceCard> emptyPage = new Page<>(); emptyPage.setRecords(Collections.emptyList()); when(spaceCardService.queryCardByCondition(any(CardQuery.class))).thenReturn(emptyPage); PageResult<OnlineReportCardDTO> result = onlineReportService.selectSprintCardPage(query); assertTrue(result.getRecords().isEmpty()); assertEquals(1, result.getCurrent()); assertEquals(10, result.getSize()); } @Test public void selectSprintCardPage_WithRecords_ReturnFilledPage() { CardQuery query = new CardQuery(); query.setPageNum(1); query.setPageSize(10); query.setSprintId(1); // Mock card page BizSpaceCard card = new BizSpaceCard(); card.setId(1); Page<BizSpaceCard> cardPage = new Page<>(); cardPage.setRecords(Arrays.asList(card)); when(spaceCardService.queryCardByCondition(any(CardQuery.class))).thenReturn(cardPage); // Mock demand users List<BizDemandUser> demandUsers = Collections.emptyList(); when(demandUserService.selectByDemandIds(anyList(), any(Integer.class))).thenReturn(demandUsers); // Mock report map BizReport uatReport = new BizReport(); BizReport gradationReport = new BizReport(); Map<String, BizReport> reportMap = new java.util.HashMap<>(); reportMap.put(AcceptanceReportEnum.reportType.UAT.name(), uatReport); reportMap.put(AcceptanceReportEnum.reportType.GRADATION.name(), gradationReport); when(bizReportService.selectReportMap(anyList(), any(AcceptanceReportEnum.relationBizType.class), any(Integer.class))).thenReturn(reportMap); // Mock report items List<BizReportItem> reportItems = Collections.emptyList(); when(reportItemService.listReportItemByReportIds(anyList())).thenReturn(reportItems); // Mock user map Map<String, UserVO> userVOMap = new java.util.HashMap<>(); when(userHelper.getUserVoMapWithFSNameByErps(anyList(), any(Function.class), any(Function.class))).thenReturn(userVOMap); PageResult<OnlineReportCardDTO> result = onlineReportService.selectSprintCardPage(query); assertEquals(1, result.getRecords().size()); } @Test public void selectSprintCardPage_WithRecords_ReturnFilledPage2() { CardQuery query = new CardQuery(); query.setPageNum(1); query.setPageSize(10); query.setSprintId(1); // Mock card page BizSpaceCard card = new BizSpaceCard(); card.setId(1); Page<BizSpaceCard> cardPage = new Page<>(); cardPage.setRecords(Arrays.asList(card)); when(spaceCardService.queryCardByCondition(any(CardQuery.class))).thenReturn(cardPage); // Mock demand users List<BizDemandUser> demandUsers = Collections.emptyList(); when(demandUserService.selectByDemandIds(anyList(), any(Integer.class))).thenReturn(demandUsers); // Mock report map BizReport uatReport = new BizReport(); BizReport gradationReport = new BizReport(); Map<String, BizReport> reportMap = new java.util.HashMap<>(); when(bizReportService.selectReportMap(anyList(), any(AcceptanceReportEnum.relationBizType.class), any(Integer.class))).thenReturn(reportMap); // Mock report items List<BizReportItem> reportItems = Collections.emptyList(); when(reportItemService.listReportItemByReportIds(anyList())).thenReturn(reportItems); // Mock user map Map<String, UserVO> userVOMap = new java.util.HashMap<>(); when(userHelper.getUserVoMapWithFSNameByErps(anyList(), any(Function.class), any(Function.class))).thenReturn(userVOMap); PageResult<OnlineReportCardDTO> result = onlineReportService.selectSprintCardPage(query); assertEquals(1, result.getRecords().size()); } @Test public void selectSprintAppList_SprintNotExist_ReturnEmptyList() { when(bizSpaceSprintService.getById(anyInt())).thenReturn(null); List<OnlineReportAppDTO> result = onlineReportService.selectSprintAppList(1); assertEquals(Collections.emptyList(), result); } @Test public void selectSprintAppList_SpaceNotExist_ReturnEmptyList() { BizSpaceSprint bizSpaceSprint = new BizSpaceSprint(); bizSpaceSprint.setId(1); bizSpaceSprint.setSpaceId(1); when(bizSpaceSprintService.getById(anyInt())).thenReturn(bizSpaceSprint); when(bizSpaceService.getById(anyInt())).thenReturn(null); List<OnlineReportAppDTO> result = onlineReportService.selectSprintAppList(1); assertEquals(Collections.emptyList(), result); } @Test public void selectSprintAppList_SprintAndSpaceExist_ReturnAppList() { BizSpaceSprint bizSpaceSprint = new BizSpaceSprint(); bizSpaceSprint.setId(1); bizSpaceSprint.setSpaceId(1); BizSpace bizSpace = new BizSpace(); bizSpace.setId(1); bizSpace.setKey("key"); when(bizSpaceSprintService.getById(anyInt())).thenReturn(bizSpaceSprint); when(bizSpaceService.getById(anyInt())).thenReturn(bizSpace); List<OnlineReportAppDTO> result = onlineReportService.selectSprintAppList(1); } @Test public void selectSprintAppList_test1() { onlineReportService.selectSprintAppList(1, "2"); } @Test public void selectSprintAppList_test2() { QueryReportVO queryReportVO = new QueryReportVO(); queryReportVO.setDetail(Arrays.asList(new DetailVO())); when(itsmClientService.getQueryReport(any(), any())).thenReturn(queryReportVO); onlineReportService.selectSprintAppList(1, "2"); } @Test public void sendOnlineReportNow_SprintNotExist_ShouldThrowException() { SprintOnlineReportInfoVO param = new SprintOnlineReportInfoVO(); param.setSprintId(1); when(bizSpaceSprintService.getById(1)).thenReturn(null); assertThrows(IllegalArgumentException.class, () -> { onlineReportService.sendOnlineReportNow(param); }); } @Test public void sendOnlineReportNow_SpaceNotConfigured_ShouldThrowException() { SprintOnlineReportInfoVO param = new SprintOnlineReportInfoVO(); param.setSprintId(1); BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setSpaceId(1); when(bizSpaceSprintService.getById(1)).thenReturn(sprint); when(onlineReportService.selectSpaceSwitch(1)).thenReturn(false); assertThrows(IllegalArgumentException.class, () -> { onlineReportService.sendOnlineReportNow(param); }); } @Test public void sendOnlineReportNow_ValidConditions_ShouldSendReport() { SprintOnlineReportInfoVO param = new SprintOnlineReportInfoVO(); param.setSprintId(1); param.setNotifySetting(new NotifySettingDTO()); param.setOnlineReport(new OnlineReportBaseInfoDTO()); BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setSpaceId(1); sprint.setArchived(1); when(bizSpaceSprintService.getById(1)).thenReturn(sprint); when(onlineReportService.selectSpaceSwitch(1)).thenReturn(true); onlineReportService.sendOnlineReportNow(param); } @Test public void genDefaultOnlineReportName_test() { onlineReportService.genDefaultOnlineReportName(new BizSpaceSprint(), "1", "2"); } @Test public void genDefaultOnlineReportName_test2() { SubSystemByParamsDTO subSystemByParamsDTO = new SubSystemByParamsDTO(); subSystemByParamsDTO.setDepartment("11"); when(cmdbClient.queryProjectByCode(any())).thenReturn(subSystemByParamsDTO); onlineReportService.genDefaultOnlineReportName(new BizSpaceSprint(), "1", ""); } @Test public void sendOnlineReportByNotifySetting_SprintNotArchived_ShouldThrowException() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setArchived(YesOrNoEnum.NO.getNumCode()); NotifySettingDTO notifySetting = new NotifySettingDTO(); OnlineReportBaseInfoDTO reportBaseInfoDTO = new OnlineReportBaseInfoDTO(); onlineReportService.sendOnlineReportByNotifySetting(sprint, notifySetting, reportBaseInfoDTO); } @Test public void sendOnlineReportByNotifySetting_SpaceNotExist_ShouldLogWarning() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setArchived(YesOrNoEnum.YES.getNumCode()); sprint.setSpaceId(1); NotifySettingDTO notifySetting = new NotifySettingDTO(); OnlineReportBaseInfoDTO reportBaseInfoDTO = new OnlineReportBaseInfoDTO(); when(bizSpaceService.getById(1)).thenReturn(null); onlineReportService.sendOnlineReportByNotifySetting(sprint, notifySetting, reportBaseInfoDTO); verify(bizSpaceService).getById(1); } @Test public void sendOnlineReportByNotifySetting_ReportBaseInfoIsNull_ShouldCreateNew() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setArchived(YesOrNoEnum.YES.getNumCode()); sprint.setSpaceId(1); sprint.setId(1); sprint.setName("sprintName"); BizSpace space = new BizSpace(); space.setId(1); space.setKey("key"); NotifySettingDTO notifySetting = new NotifySettingDTO(); notifySetting.setSendWays(Arrays.asList()); OnlineReportBaseInfoDTO reportBaseInfoDTO = null; when(bizSpaceService.getById(1)).thenReturn(space); when(bizSpaceSprintService.getById(1)).thenReturn(sprint); when(spaceCardService.queryCardByCondition(any())).thenReturn(new Page<>()); onlineReportService.sendOnlineReportByNotifySetting(sprint, notifySetting, reportBaseInfoDTO); verify(bizSpaceService).getById(1); } @Test public void sendOnlineReportByNotifySetting_SendWayIsLark_ShouldCallWKMethod() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setArchived(YesOrNoEnum.YES.getNumCode()); sprint.setSpaceId(1); sprint.setId(1); sprint.setName("sprintName"); BizSpace space = new BizSpace(); space.setId(1); space.setKey("key"); NotifySettingDTO notifySetting = new NotifySettingDTO(); notifySetting.setSendWays(Arrays.asList(BizNotifySendWayEnum.LARK.getCode())); ChatInfoDataResp.ChatData chatData = new ChatInfoDataResp.ChatData(); chatData.setChatId("chatId"); notifySetting.setLarks(Arrays.asList(chatData)); OnlineReportBaseInfoDTO reportBaseInfoDTO = new OnlineReportBaseInfoDTO(); when(bizSpaceService.getById(1)).thenReturn(space); when(spaceCardService.queryCardByCondition(any())).thenReturn(new Page<>()); onlineReportService.sendOnlineReportByNotifySetting(sprint, notifySetting, reportBaseInfoDTO); } @Test public void sendOnlineReportByNotifySetting_SendWayIsEmail_ShouldCallEmailMethod() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setArchived(YesOrNoEnum.YES.getNumCode()); sprint.setSpaceId(1); sprint.setId(1); sprint.setName("sprintName"); BizSpace space = new BizSpace(); space.setId(1); space.setKey("key"); NotifySettingDTO notifySetting = new NotifySettingDTO(); notifySetting.setSendWays(Arrays.asList(BizNotifySendWayEnum.EMAIL.getCode())); notifySetting.setEmails("test@example.com"); OnlineReportBaseInfoDTO reportBaseInfoDTO = new OnlineReportBaseInfoDTO(); when(bizSpaceService.getById(1)).thenReturn(space); when(spaceCardService.queryCardByCondition(any())).thenReturn(new Page<>()); when(scriptEngineManager.getEngineByName(any())).thenReturn(new VelocityScriptEngine()); onlineReportService.sendOnlineReportByNotifySetting(sprint, notifySetting, reportBaseInfoDTO); } @Test public void sendOnlineReportForSprints_test() { BizSpaceSprint sprint = new BizSpaceSprint(); when(spaceSettingService.checkRequireKeyIsYesCode(any(), any())).thenReturn(true); when(bizSpaceSprintService.listByIds(any())).thenReturn(Arrays.asList(sprint)); onlineReportService.sendOnlineReportForSprints(Arrays.asList(1)); } @Test public void sendOnlineReportForSprints_test1() { BizSpaceSprint sprint = new BizSpaceSprint(); when(bizSpaceSprintService.listByIds(any())).thenReturn(Arrays.asList(sprint)); onlineReportService.sendOnlineReportForSprints(Arrays.asList(1)); } @Test public void sendOnlineReportForSprints_test2() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setArchived(0); when(spaceSettingService.checkRequireKeyIsYesCode(any(), any())).thenReturn(true); when(bizSpaceSprintService.listByIds(any())).thenReturn(Arrays.asList(sprint)); onlineReportService.sendOnlineReportForSprints(Arrays.asList(1)); } @Test public void sendOnlineReportForSprints_test3() { BizSpaceSprint sprint = new BizSpaceSprint(); sprint.setArchived(1); when(spaceSettingService.checkRequireKeyIsYesCode(any(), any())).thenReturn(true); BizNotifySetting bizNotifySetting = new BizNotifySetting(); when(bizNotifySettingService.getOneBy(any(), any())).thenReturn(bizNotifySetting); when(bizSpaceSprintService.listByIds(any())).thenReturn(Arrays.asList(sprint)); onlineReportService.sendOnlineReportForSprints(Arrays.asList(1)); } @Test public void selectSpaceNotifySetting_test() { onlineReportService.selectSpaceNotifySetting(1); } @Test public void selectSpaceNotifySetting_test2() { when(bizSpaceSprintService.getSpaceBySprintId(any())).thenReturn(new BizSpace().setId(1)); onlineReportService.selectSpaceNotifySetting(1); } @Test public void selectSpaceNotifySetting_test3() { when(bizSpaceSprintService.getSpaceBySprintId(any())).thenReturn(new BizSpace().setId(1)); when(bizNotifySettingService.getOneBy(any(), any())).thenReturn(new BizNotifySetting().setId(1)); onlineReportService.selectSpaceNotifySetting(1); } @Test public void queryCheckTest() { BizReport bizReport = new BizReport(); bizReport.setExtendInfo("{\"checkPoint\":\"Test CheckPoint\",\"checkPointResult\":\"Test CheckPointResult\",\"omittedIssuesForRecord\":\"Test OmittedIssuesForRecord\"}"); when(bizReportService.selectReport(AcceptanceReportEnum.reportType.ONLINE, AcceptanceReportEnum.relationBizType.SPRINT, 1)).thenReturn(bizReport); OnlineReportCheckDTO result = onlineReportService.queryCheck(1); assertNotNull(result); assertEquals("Test CheckPoint", result.getCheckPoint()); assertEquals("Test CheckPointResult", result.getCheckPointResult()); assertEquals("Test OmittedIssuesForRecord", result.getOmittedIssuesForRecord()); } @Test public void updateCheckTest() { // Mock data BizSpaceSprint sprint = new BizSpaceSprint().setId(1).setSpaceId(1); BizSpace space = new BizSpace().setId(1).setKey("key"); OnlineReportCheckDTO onlineReportCheckDTO = new OnlineReportCheckDTO() .setCheckPoint("Test CheckPoint") .setCheckPointResult("Test CheckPointResult") .setOmittedIssuesForRecord("Test OmittedIssuesForRecord"); when(bizSpaceSprintService.getById(1)).thenReturn(sprint); when(bizSpaceService.getById(1)).thenReturn(space); when(onlineReportService.getOnlineReportBaseInfoDTO(eq(sprint), eq("key"))) .thenReturn(new OnlineReportBaseInfoDTO()); // Act onlineReportService.updateCheck(onlineReportCheckDTO, 1); // Verify verify(bizReportService, times(1)).saveOrUpdateOnlineReport(1, any(OnlineReportBaseInfoDTO.class)); } } 以下是onlineReportService对应类的代码:package com.jd.jacp.report.service.impl; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.jd.jacp.client.dto.CICDAppGrayscaleDeployInfo; import com.jd.jacp.client.dto.GetCiCdTaskQuery; import com.jd.jacp.client.service.ICicdClient; import com.jd.jacp.client.service.ICmdbClient; import com.jd.jacp.client.service.ItsmClientService; import com.jd.jacp.common.feishu.FeiShuMessageSender; import com.jd.jacp.common.service.UserHelper; import com.jd.jacp.common.vo.UserVO; import com.jd.jacp.common.vo.enums.YesOrNoEnum; import com.jd.jacp.demand.entity.BizDemandUser; import com.jd.jacp.demand.service.IBizDemandUserService; import com.jd.jacp.demand.vo.DemandUserTypeEnum; import com.jd.jacp.notify.entity.BizNotifyRule; import com.jd.jacp.notify.entity.BizNotifySetting; import com.jd.jacp.notify.enums.BizNotifySendWayEnum; import com.jd.jacp.notify.enums.BizNotifyTypeEnum; import com.jd.jacp.notify.service.IBizNotifyRuleService; import com.jd.jacp.notify.service.IBizNotifySettingService; import com.jd.jacp.report.dto.*; import com.jd.jacp.report.entity.BizReport; import com.jd.jacp.report.entity.BizReportItem; import com.jd.jacp.report.enums.AcceptanceReportEnum; import com.jd.jacp.report.service.IBizReportItemService; import com.jd.jacp.report.service.IBizReportService; import com.jd.jacp.report.service.IOnlineReportService; import com.jd.jacp.report.vo.SprintOnlineReportInfoVO; import com.jd.jacp.space.dto.CardQuery; import com.jd.jacp.space.dto.SubSystemByParamsDTO; import com.jd.jacp.space.entity.BizSpace; import com.jd.jacp.space.entity.BizSpaceCard; import com.jd.jacp.space.entity.BizSpaceSprint; import com.jd.jacp.space.service.IBizSpaceCardService; import com.jd.jacp.space.service.IBizSpaceService; import com.jd.jacp.space.service.IBizSpaceSettingService; import com.jd.jacp.space.service.IBizSpaceSprintService; import com.jd.jacp.space.service.impl.BizSpaceSettingServiceImpl; import com.jd.jacp.space.vo.DetailVO; import com.jd.jacp.space.vo.QueryReportVO; import com.jd.jacp.util.AssertUtil; import com.jd.jacp.util.EmailSender; import com.msxf.devops.common.PageResult; import com.msxf.fcid.xmsg.reponse.ChatInfoDataResp; import com.msxf.fcid.xmsg.sdk.response.FeishuMessageSendResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.InputStream; import java.io.StringWriter; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author ke.feng-n */ @Slf4j @Service public class OnlineReportServiceImpl implements IOnlineReportService { @Autowired private IBizSpaceSprintService bizSpaceSprintService; @Autowired private ItsmClientService itsmClientService; @Autowired private IBizReportService bizReportService; @Autowired private ICmdbClient cmdbClient; @Autowired private IBizSpaceService bizSpaceService; @Autowired private IBizNotifySettingService bizNotifySettingService; @Autowired private IBizNotifyRuleService bizNotifyRuleService; @Autowired private IBizSpaceCardService spaceCardService; @Autowired private IBizDemandUserService demandUserService; @Autowired private IBizReportItemService reportItemService; @Autowired private UserHelper userHelper; @Resource(name = "scriptEngineManager") private ScriptEngineManager scriptEngineManager; @Autowired private FeiShuMessageSender feiShuMessageSender; @Autowired private ICicdClient cicdClient; @Autowired private IBizSpaceSettingService spaceSettingService; @Value("${env.domain.name}") private String domain; @Resource EmailSender emailSender; @Override public SprintOnlineReportInfoVO selectOnlineReportInfo(Integer sprintId) { BizSpaceSprint sprint = bizSpaceSprintService.getById(sprintId); Assert.notNull(sprint, "迭代不存在"); BizSpace space = bizSpaceService.getById(sprint.getSpaceId()); Assert.notNull(space, "迭代所属子系统不存在"); //获取报告名称遗漏问题 OnlineReportBaseInfoDTO onlineReportBaseInfoDTO = getOnlineReportBaseInfoDTO(sprint, space.getKey()); SprintOnlineReportInfoVO reportInfoVO = new SprintOnlineReportInfoVO(); reportInfoVO.setOnlineReport(onlineReportBaseInfoDTO); //获取迭代的通知配置信息 BizNotifySetting sprintNotifySetting = getSprintNotifySetting(sprint); if (ObjectUtil.isEmpty(sprintNotifySetting)) { return reportInfoVO; } BizNotifyRule notifyRule = bizNotifyRuleService.getOneByNotifyId(sprintNotifySetting.getId()); NotifySettingDTO notifySetting = NotifySettingDTO.of(sprintNotifySetting, notifyRule); reportInfoVO.setNotifySetting(notifySetting); return reportInfoVO; } /** * 获取迭代的基础配置信息(报告名称,) * * @param sprint * @param spaceKey * @return */ public OnlineReportBaseInfoDTO getOnlineReportBaseInfoDTO(BizSpaceSprint sprint, String spaceKey) { BizReport bizReport = bizReportService.selectReport(AcceptanceReportEnum.reportType.ONLINE, AcceptanceReportEnum.relationBizType.SPRINT, sprint.getId()); OnlineReportBaseInfoDTO onlineReportBaseInfoDTO; if (ObjectUtil.isNotEmpty(bizReport) && StrUtil.isNotBlank(bizReport.getExtendInfo())) { onlineReportBaseInfoDTO = JSONUtil.toBean(bizReport.getExtendInfo(), OnlineReportBaseInfoDTO.class); } else { BizNotifySetting spaceNotifySetting = bizNotifySettingService.getOneBy(String.valueOf(sprint.getSpaceId()), BizNotifyTypeEnum.SPACE_SPRINT_ONLINE_REPORT.getCode()); onlineReportBaseInfoDTO = genDefaultOnlineReportName(sprint, spaceKey, ObjectUtil.isEmpty(spaceNotifySetting) ? null : spaceNotifySetting.getRelatedObjName()); } return onlineReportBaseInfoDTO; } @Override @Transactional(rollbackFor = Exception.class) public void saveSprintNotifySetting(SprintOnlineReportInfoVO param) { bizReportService.saveOrUpdateOnlineReport(param.getSprintId(), param.getOnlineReport()); Integer notifyId = bizNotifySettingService.saveOrUpdateNotifySetting(BizNotifyTypeEnum.SPRINT_ONLINE_REPORT, String.valueOf(param.getSprintId()), param.getNotifySetting(), null); bizNotifyRuleService.saveOrUpdateNotifyRule(notifyId, param.getNotifySetting().getSendTime()); } @Override @Transactional(rollbackFor = Exception.class) public void saveSpaceNotifySetting(SprintOnlineReportInfoVO param) { BizSpaceSprint sprint = bizSpaceSprintService.getById(param.getSprintId()); Assert.notNull(sprint, "迭代不存在"); Integer notifyId = bizNotifySettingService.saveOrUpdateNotifySetting(BizNotifyTypeEnum.SPACE_SPRINT_ONLINE_REPORT, String.valueOf(sprint.getSpaceId()), param.getNotifySetting(), param.getOnlineReport().getDepartment()); bizNotifyRuleService.saveOrUpdateNotifyRule(notifyId, param.getNotifySetting().getSendTime()); } @Override public PageResult<OnlineReportCardDTO> selectSprintCardPage(CardQuery query) { Page<BizSpaceCard> cardPage = spaceCardService.queryCardByCondition(query); List<OnlineReportCardDTO> cardDTOList = OnlineReportCardDTO.buildFromCardEntity(cardPage.getRecords()); if (CollectionUtil.isEmpty(cardDTOList)) { return PageResult.newEmptyPage(Long.valueOf(query.getPageNum()), Long.valueOf(query.getPageSize())); } //获取需求提报人列表 List<Integer> demandIds = cardDTOList.stream().map(OnlineReportCardDTO::getDemandId).distinct().collect(Collectors.toList()); List<BizDemandUser> bizDemandUsers = demandUserService.selectFeishuUserByDemandIds(demandIds, DemandUserTypeEnum.CONTACT_TYPE_BIZ.getId()); Map<Integer, List<BizDemandUser>> submitterMap = bizDemandUsers.stream().collect(Collectors.groupingBy(BizDemandUser::getDemandId)); List<String> cardErps = cardDTOList.stream() .flatMap(cardDTO -> Stream.of( cardDTO.getProductManagerErp(), cardDTO.getProcessorErp(), cardDTO.getTestLeaderErp() )).distinct() .collect(Collectors.toList()); Map<String, BizReport> reportMap = bizReportService.selectReportMap(Arrays.asList(AcceptanceReportEnum.reportType.UAT, AcceptanceReportEnum.reportType.GRADATION), AcceptanceReportEnum.relationBizType.SPRINT, query.getSprintId()); List<Integer> reportIds = reportMap.values().stream().map(BizReport::getId).collect(Collectors.toList()); //获取验收报告信息 List<String> acceptorErps = Collections.emptyList(); Map<Integer, Map<String, BizReportItem>> reportItemMap = new HashMap<>(); if(CollectionUtil.isNotEmpty(reportIds)) { List<BizReportItem> reportItems = reportItemService.listReportItemByReportIds(reportIds); acceptorErps = reportItems.stream().map(BizReportItem::getAccepters) .flatMap(erp -> JSONUtil.toList(erp, String.class).stream()) .filter(StrUtil::isNotBlank) .distinct() .collect(Collectors.toList()); //报告id-卡片id-报告项 reportItemMap = reportItems.stream().collect(Collectors.groupingBy(BizReportItem::getReportId, Collectors.toMap(BizReportItem::getRelationItemIdentifier, Function.identity(), (v1, v2) -> v1))); } cardErps.addAll(acceptorErps); Map<String, UserVO> userVOMap = userHelper.getUserVoMapWithFSNameByErps(cardErps.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList()), UserVO::getErp, Function.identity()); for (OnlineReportCardDTO cardDTO : cardDTOList) { //填充需求提报人 cardDTO.setSubmitter(BizDemandUser.buildUserVOList(submitterMap.get(cardDTO.getDemandId()))); //填充卡片相关人信息 cardDTO.setProductManager(userVOMap.get(cardDTO.getProductManagerErp())); cardDTO.setProcessor(userVOMap.get(cardDTO.getProcessorErp())); cardDTO.setTestLeader(userVOMap.get(cardDTO.getTestLeaderErp())); //填充UAT验收信息 BizReport uatReport = reportMap.get(AcceptanceReportEnum.reportType.UAT.name()); cardDTO.fillUATAcceptanceInfo(reportItemMap, uatReport, userVOMap); //填充灰度验收信息 BizReport gradationReport = reportMap.get(AcceptanceReportEnum.reportType.GRADATION.name()); cardDTO.fillGradationAcceptanceInfo(reportItemMap, gradationReport, userVOMap); } return PageResult.newInstance(cardDTOList, cardPage.getPages(), cardPage.getTotal(), cardPage.getCurrent(), cardPage.getSize()); } @Override public List<OnlineReportAppDTO> selectSprintAppList(Integer sprintId) { BizSpaceSprint sprint = bizSpaceSprintService.getById(sprintId); if (ObjectUtil.isEmpty(sprint)) { return Collections.emptyList(); } BizSpace space = bizSpaceService.getById(sprint.getSpaceId()); if (ObjectUtil.isEmpty(space)) { return Collections.emptyList(); } return this.selectSprintAppList(sprintId, space.getKey()); } @Override public List<OnlineReportAppDTO> selectSprintAppList(Integer sprintId, String spaceKey) { DetailVO itsmDetail = getSprintItsmOnlineDetail(sprintId, spaceKey); if (ObjectUtil.isEmpty(itsmDetail) || ObjectUtil.isEmpty(itsmDetail.getApplyCode())) { return Collections.emptyList(); } List<CICDAppGrayscaleDeployInfo> cicdAppGrayscaleDeployInfos = Collections.emptyList(); try { cicdAppGrayscaleDeployInfos = cicdClient.getTaskListByParam(GetCiCdTaskQuery.buildQueryProdTaskQuery(itsmDetail.getApplyCode())); } catch (Exception e) { log.warn("调用CICD接口查询迭代部署完成应用列表失败:", e); } return OnlineReportAppDTO.buildList(cicdAppGrayscaleDeployInfos); } @Override public void sendOnlineReportNow(SprintOnlineReportInfoVO param) { BizSpaceSprint sprint = bizSpaceSprintService.getById(param.getSprintId()); Assert.notNull(sprint, "迭代不存在"); boolean sendSwitch = this.selectSpaceSwitch(sprint.getSpaceId()); Assert.isTrue(sendSwitch, "空间未开启上线报告发送配置"); this.sendOnlineReportByNotifySetting(sprint, param.getNotifySetting(), param.getOnlineReport()); } /** * 查询迭代卡片列表 * * @param sprintId */ public List<OnlineReportCardDTO> selectSprintCardList(Integer sprintId) { CardQuery cardQuery = new CardQuery(); cardQuery.setSprintId(sprintId); cardQuery.setPageNum(1); cardQuery.setPageSize(10000); PageResult<OnlineReportCardDTO> sprintCardPage = this.selectSprintCardPage(cardQuery); return sprintCardPage.getRecords(); } /** * 生成默认的上线报告名称 * * @return */ public OnlineReportBaseInfoDTO genDefaultOnlineReportName(BizSpaceSprint sprint, String spaceKey, String department) { if (StrUtil.isBlank(department)) { SubSystemByParamsDTO subSystemByParamsDTO = cmdbClient.queryProjectByCode(spaceKey); department = ObjectUtil.isNotEmpty(subSystemByParamsDTO) ? subSystemByParamsDTO.getDepartment() : "暂无部门"; } //获取迭代上线流程信息 DetailVO detailVO = getSprintItsmOnlineDetail(sprint.getId(), spaceKey); String deployType = Optional.ofNullable(detailVO).map(DetailVO::getDeployType).orElse(""); String sprintEndDate = ObjectUtil.isNotEmpty(sprint.getEndDate()) ? DateUtil.format(sprint.getEndDate(), DatePattern.PURE_DATE_FORMAT) : ""; String reportName = "版本发布" + "-" + department + "-" + deployType + "-" + sprintEndDate; return new OnlineReportBaseInfoDTO().setReportName(reportName).setDepartment(department).setDeployType(deployType).setSprintEndDate(sprintEndDate); } /** * 获取迭代上线流程信息 * * @param sprintId * @param spaceKey * @return */ private DetailVO getSprintItsmOnlineDetail(Integer sprintId, String spaceKey) { QueryReportVO queryReport = itsmClientService.getQueryReport(sprintId, spaceKey); DetailVO detailVO = null; if (ObjectUtil.isNotEmpty(queryReport) && CollectionUtil.isNotEmpty(queryReport.getDetail())) { detailVO = queryReport.getDetail().get(0); } return detailVO; } @Override public String sprintDeployReportWK(SprintOnlineReportInfoDTO sprintOnlineReportInfoDTO, List<String> chats, boolean acceptanceReportEnable) { SprintDeployReportDTO dto = SprintDeployReportDTO.convertFromSprintOnlineReportInfoDTO(sprintOnlineReportInfoDTO, domain, BizNotifySendWayEnum.LARK.getCode(), acceptanceReportEnable); try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream( acceptanceReportEnable ? "templates/SprintDeployReport.json" : "templates/SprintDeployReport-NoAcceptance.json")) { String content = IOUtils.toString(inputStream); ScriptEngine engine = scriptEngineManager.getEngineByName("velocity"); JSONObject wkParam = JSON.parseObject(JSON.toJSONString(dto)); ScriptContext scriptContext = engine.getContext(); wkParam.keySet().forEach(key -> scriptContext.setAttribute(key, wkParam.get(key), ScriptContext.ENGINE_SCOPE)); scriptContext.setWriter(new StringWriter()); String contentText = engine.eval(content).toString(); FeishuMessageSendResponse response = feiShuMessageSender.withCustomTemplate(contentText, "global-template-notice", chats, null, null); AssertUtil.notNull(response, "no response"); AssertUtil.isTrue(Objects.equals(response.getCode(), "0"), response.getMsg()); AssertUtil.notEmpty(response.getData(), "wk message send fault"); return response.getData().get(0); } catch (Exception e) { log.error("sprint deploy report wk message send error", e); } return null; } @Override public void sendOnlineReportByNotifySetting(BizSpaceSprint sprint, NotifySettingDTO notifySetting, OnlineReportBaseInfoDTO reportBaseInfoDTO) { BizSpace space = bizSpaceService.getById(sprint.getSpaceId()); if (ObjectUtil.isEmpty(space)) { log.warn("【发送上线报告】迭代所属子系统不存在:{}", sprint.getSpaceId()); return; } if(ObjectUtil.isEmpty(reportBaseInfoDTO)) { reportBaseInfoDTO = this.getOnlineReportBaseInfoDTO(sprint, space.getKey()); } List<OnlineReportCardDTO> cardList = this.selectSprintCardList(sprint.getId()); List<OnlineReportAppDTO> appList = this.selectSprintAppList(sprint.getId(), space.getKey()); SprintOnlineReportInfoDTO reportInfoDTO = new SprintOnlineReportInfoDTO() .setSprintId(sprint.getId()) .setSprintName(sprint.getName()) .setSpaceKey(space.getKey()) .setOnlineReportBaseInfo(reportBaseInfoDTO) .setOnlineReportCardList(cardList) .setOnlineReportAppList(appList); List<String> sendWays = notifySetting.getSendWays(); boolean acceptanceReportEnable = spaceSettingService.acceptanceReportEnable(space.getId()); if (sendWays.contains(BizNotifySendWayEnum.LARK.getCode())) { List<String> chatIds = notifySetting.getLarks().stream().map(ChatInfoDataResp.ChatData::getChatId).filter(Objects::nonNull).distinct().collect(Collectors.toList()); this.sprintDeployReportWK(reportInfoDTO, chatIds, acceptanceReportEnable); } if (sendWays.contains(BizNotifySendWayEnum.EMAIL.getCode())) { this.sprintDeployReportEmail(reportInfoDTO, Arrays.asList(notifySetting.getEmails().split(",")), null, acceptanceReportEnable); } } @Override public NotifySettingDTO selectSpaceNotifySetting(Integer sprintId) { BizSpace space = bizSpaceSprintService.getSpaceBySprintId(sprintId); if (ObjectUtil.isEmpty(space)) { return null; } BizNotifySetting spaceNotifySetting = bizNotifySettingService.getOneBy(String.valueOf(space.getId()), BizNotifyTypeEnum.SPACE_SPRINT_ONLINE_REPORT.getCode()); if (ObjectUtil.isEmpty(spaceNotifySetting)) { return null; } BizNotifyRule notifyRule = bizNotifyRuleService.getOneByNotifyId(spaceNotifySetting.getId()); return NotifySettingDTO.of(spaceNotifySetting, notifyRule); } @Override public void sendOnlineReportForSprints(List<Integer> sprintIds) { List<BizSpaceSprint> sprints = bizSpaceSprintService.listByIds(sprintIds); for (BizSpaceSprint sprint : sprints) { if(!this.selectSpaceSwitch(sprint.getSpaceId())) { continue; } if (YesOrNoEnum.NO.getNumCode().equals(sprint.getArchived())) { continue; } BizNotifySetting notifySetting = getSprintNotifySetting(sprint); if (ObjectUtil.isEmpty(notifySetting)) { return; } this.sendOnlineReportByNotifySetting(sprint, NotifySettingDTO.of(notifySetting), null); } } @Override public void sprintDeployReportEmail(SprintOnlineReportInfoDTO sprintOnlineReportInfoDTO, List<String> receiver, List<String> carbon, boolean acceptanceReportEnable) { SprintDeployReportDTO dto = SprintDeployReportDTO.convertFromSprintOnlineReportInfoDTO(sprintOnlineReportInfoDTO, domain, BizNotifySendWayEnum.EMAIL.getCode(), acceptanceReportEnable); try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("templates/SprintDeployReport.html")) { String content = IOUtils.toString(inputStream); ScriptEngine engine = scriptEngineManager.getEngineByName("velocity"); JSONObject htmlParam = JSON.parseObject(JSON.toJSONString(dto)); ScriptContext scriptContext = engine.getContext(); htmlParam.keySet().forEach(key -> { scriptContext.setAttribute(key, htmlParam.get(key), ScriptContext.ENGINE_SCOPE); }); scriptContext.setAttribute("acceptance_report_enable", acceptanceReportEnable, ScriptContext.ENGINE_SCOPE); scriptContext.setWriter(new StringWriter()); String contentText = engine.eval(content).toString(); emailSender.dcpSendEmail(receiver, carbon, String.format("%s一上线报告", dto.getSprintTitle()), contentText); } catch (Exception e) { log.error("sprint deploy report email message send error", e); } } /** * 获取迭代可用的通知配置信息 * * @param sprint * @return */ @Override public BizNotifySetting getSprintNotifySetting(BizSpaceSprint sprint) { if(ObjectUtil.isEmpty(sprint)) { return null; } BizNotifySetting sprintNotifySetting = bizNotifySettingService.getOneBy(String.valueOf(sprint.getId()), BizNotifyTypeEnum.SPRINT_ONLINE_REPORT.getCode()); if (ObjectUtil.isEmpty(sprintNotifySetting)) { sprintNotifySetting = bizNotifySettingService.getOneBy(String.valueOf(sprint.getSpaceId()), BizNotifyTypeEnum.SPACE_SPRINT_ONLINE_REPORT.getCode()); } return sprintNotifySetting; } @Override public boolean selectSpaceSwitch(Integer spaceId) { return spaceSettingService.checkRequireKeyIsYesCode(spaceId, BizSpaceSettingServiceImpl.REQUIRED_SEND_REPORT_AFTER_SPRINT_ARCHIVED); } /** * 根据迭代id查询生产验证情况 * @param sprintId * @return */ @Override public OnlineReportCheckDTO queryCheck(Integer sprintId) { BizReport bizReport = bizReportService.selectReport(AcceptanceReportEnum.reportType.ONLINE, AcceptanceReportEnum.relationBizType.SPRINT, sprintId); OnlineReportBaseInfoDTO onlineReportBaseInfoDTO; OnlineReportCheckDTO onlineReportCheckDTO = new OnlineReportCheckDTO(); if (ObjectUtil.isNotEmpty(bizReport) && StrUtil.isNotBlank(bizReport.getExtendInfo())) { onlineReportBaseInfoDTO = JSONUtil.toBean(bizReport.getExtendInfo(), OnlineReportBaseInfoDTO.class); onlineReportCheckDTO.setCheckPoint(onlineReportBaseInfoDTO.getCheckPoint()); onlineReportCheckDTO.setCheckPointResult(onlineReportBaseInfoDTO.getCheckPointResult()); onlineReportCheckDTO.setOmittedIssuesForRecord(onlineReportBaseInfoDTO.getOmittedIssuesForRecord()); } return onlineReportCheckDTO; } /** * 更新生产验证情况 * @param onlineReportCheckDTO * @param sprintId */ @Override public void updateCheck(OnlineReportCheckDTO onlineReportCheckDTO, Integer sprintId) { BizSpaceSprint sprint = bizSpaceSprintService.getById(sprintId); Assert.notNull(sprint, "迭代不存在"); BizSpace space = bizSpaceService.getById(sprint.getSpaceId()); Assert.notNull(space, "迭代所属子系统不存在"); //获取报告名称遗漏问题 OnlineReportBaseInfoDTO onlineReportBaseInfoDTO = getOnlineReportBaseInfoDTO(sprint, space.getKey()); //设置数据 onlineReportBaseInfoDTO.setCheckPoint(onlineReportCheckDTO.getCheckPoint()); onlineReportBaseInfoDTO.setCheckPointResult(onlineReportCheckDTO.getCheckPointResult()); onlineReportBaseInfoDTO.setOmittedIssuesForRecord(onlineReportCheckDTO.getOmittedIssuesForRecord()); //如果有数据直接更新,没有生成新数据 bizReportService.saveOrUpdateOnlineReport(sprintId, onlineReportBaseInfoDTO); } } 当运行updateCheckTest时,报错:java.lang.NullPointerException at com.jd.jacp.report.service.impl.OnlineReportServiceImpl.getOnlineReportBaseInfoDTO(OnlineReportServiceImpl.java:163) at com.jd.jacp.unit.report.OnlineReportServiceImplTest.updateCheckTest(OnlineReportServiceImplTest.java:567) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55) Process finished with exit code -1
09-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值