集成flowable的单测

package com.insgeek.platform.flow.service.test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.insgeek.boot.web.vo.ResponseVO;
import com.insgeek.platform.flow.pojo.dto.*;
import com.insgeek.platform.flow.redis.RedisService;
import com.insgeek.platform.flow.test.config.FlowTestContextConfiguration;
import com.insgeek.platform.flow.utils.test.FlowTestUtils;
import com.insgeek.protocol.platform.data.client.ConditionClient;
import com.insgeek.protocol.platform.data.client.DataClient;
import com.insgeek.protocol.platform.data.dto.ComputedDto;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;

import com.insgeek.boot.web.auth.dto.IdentityDto;
import com.insgeek.boot.web.context.IdentityContext;
import com.insgeek.platform.flow.aggservice.ExtensionAggService;
import com.insgeek.platform.flow.aggservice.FlowDataAggService;
import com.insgeek.platform.flow.aggservice.FlowMetadataAggService;
import com.insgeek.platform.flow.enums.ElementTypeEnum;
import com.insgeek.platform.flow.service.ExtensionService;
import com.insgeek.platform.flow.service.ProcessModelService;
import com.insgeek.platform.flow.service.ProcessService;
import com.insgeek.protocol.flow.dto.TaskActionEnum;
import com.insgeek.protocol.flow.dto.TaskActionRequestDto;
import org.springframework.boot.test.mock.mockito.MockBean;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Slf4j
@FlowTestContextConfiguration
public class FlowTest {

    @Autowired
    private ProcessService processService;
    @Autowired
    private ProcessModelService processModelService;
    @Autowired
    private ExtensionAggService extensionAggService;
    @Autowired
    private ExtensionService extensionService;
    @Autowired
    private FlowMetadataAggService flowMetadataAggService;
    @Autowired
    private FlowDataAggService flowDataAggService;
    @MockBean
    private RedisService redisService;
    @Resource
    private ConditionClient conditionClient;
    @Resource
    private DataClient dataClient;
    @Resource
    private DataSource dataSource;

    public static final String BUSINESS_TYPE = "vipCase";
    private static final String DESCRIPTION = "测试流程_Holley";
    private static final String ENTITY_KEY = "ig_claim_list";
    private static final String NAME = "name:test_holley";
    private static final int PROCESS_TYPE = 0;
    private static final int SEQ_NO = 0;


    public static final Long DATA_ID = 8000002L;

    @BeforeEach
    public void beforeClass() throws Exception {
//        Connection connection = dataSource.getConnection();
//        try {
//            ClassPathResource classPathResource = new ClassPathResource("ig_platform_flow.sql");
//            connection = dataSource.getConnection();
//            ScriptRunner runner = new ScriptRunner(connection);
//            runner.setErrorLogWriter(null);
//            runner.setLogWriter(null);
//            // 执行SQL脚本
//            runner.runScript(new InputStreamReader(classPathResource.getInputStream(), "utf-8"));
//            // 关闭连接
//            connection.close();
//            // 若成功,打印提示信息
//            System.out.println("====== SUCCESS ======");
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        } finally {
//            if (connection != null) {
//                connection.close();
//            }
//        }
        IdentityDto identity = new IdentityDto();
        identity.setUserId(1997l);
        identity.setTenantId(2014l);
        IdentityContext.setIdentity(identity);
    }


    @Test
    public void testCreateProcessAndModel() {
        ResponseVO<Map<String, Object>> response2VO = new ResponseVO<Map<String, Object>>();
        response2VO.setData(new HashMap<String,Object>());
        response2VO.getData().put("id", FlowTest.DATA_ID);
        response2VO.getData().put("business_type", FlowTest.BUSINESS_TYPE);
        response2VO.getData().put("tenant_id", ProcessServiceTest.TENANT_ID);
        Mockito.when(dataClient.getDataById(Mockito.any(),  Mockito.argThat(new DataIdMatcher()))).thenReturn(response2VO);

        Mockito.when(redisService.setNx(Mockito.anyString(), Mockito.any(), Mockito.anyLong())).thenReturn(true);
        //创建process
        Long processId = createProcessTest();
        System.out.println("流程头信息id===" + processId);
        //创建流程实体
        Long modelId = createModelTest(processId);
        System.out.println("流程实体id===" + modelId);
        // 发布流程
        boolean deploymentTest = deploymentTest(modelId);
        System.out.println("是否发布成功:" + deploymentTest);
        Assert.assertTrue(deploymentTest);
        // 计算条件
        ResponseVO<List<ComputedDto>> computedResultVo = new ResponseVO<>();
        List<ComputedDto> computedResult = new ArrayList<>();
        ComputedDto computedDto = new ComputedDto();
        // 非重开
        computedDto.setId(839L);
        computedDto.setValue(Boolean.TRUE);
        computedResult.add(computedDto);
        ComputedDto computedDto2 = new ComputedDto();
        // 重开
        computedDto2.setId(840L);
        computedDto2.setValue(Boolean.FALSE);
        computedResult.add(computedDto2);
        // 审核通过 (TPA后网关)
        ComputedDto computedDto3 = new ComputedDto();
        computedDto3.setId(876L);
        computedDto3.setValue(Boolean.TRUE);
        computedResult.add(computedDto3);
        // 【审核通过】垫付-非转化 (初审+理算后网关)
        ComputedDto computedDto4 = new ComputedDto();
        computedDto4.setId(866L);
        computedDto4.setValue(Boolean.TRUE);
        computedResult.add(computedDto4);
        computedResultVo.setData(computedResult);
        Mockito.when(conditionClient.batchComputeByConditionIds(Mockito.argThat(new DataIdMatcher()),Mockito.any())).thenReturn(computedResultVo);
        // 提交流程
        ProcessModelDto findProcessModel = processModelService.findProcessModel(modelId);
        System.out.println(findProcessModel.getDefinitionId());
        submitTest();
        // 获取下一节点信息
//        TaskWithCandidateUserDto nextTask = extensionAggService.getNextTask(modelId, "a8daed57-3a95-11eb-9388-5405db0ee29c", "", DATA_ID);
//        System.out.println(nextTask);
        // 推进节点
        TaskActionRequestDto taskActionRequestDto = new TaskActionRequestDto();
        taskActionRequestDto.setDataId(DATA_ID);
        taskActionRequestDto.setEntityKey(ENTITY_KEY);
        taskActionRequestDto.setAssigner(1l);
        forwordTest(taskActionRequestDto);
        // 撤回
        withdrawTest();

    }

    /**
     * 创建流程
     */
    public Long createProcessTest() {
        ProcessDto processDto = new ProcessDto();
        processDto.setBusinessType(BUSINESS_TYPE);
        processDto.setDescription(DESCRIPTION);
        processDto.setEntityKey(ENTITY_KEY);
        processDto.setName(NAME);
        processDto.setProcessType(PROCESS_TYPE);
        processDto.setSeqNo(SEQ_NO);
        Long processId = processService.createProcess(processDto);
        return processId;
    }

    /**
     * 创建流程实体
     */
    public Long createModelTest(Long processId) {
        ProcessModelDto processModelDto = new ProcessModelDto();
        processModelDto.setProcessId(processId);
        processModelDto.setName(NAME);
        processModelDto.setBusinessType(BUSINESS_TYPE);
        processModelDto.setDescription(DESCRIPTION);
        processModelDto.setEntityKey(ENTITY_KEY);
        String json = FlowTestUtils.readJsonFile(FlowTestUtils.VIP_CASE_JSON_PATH);
        FlowConfigDto flowConfig = FlowTestUtils.getFlowConfigDto(json);
        processModelDto.setModelEditorJson(flowConfig.getBpmnJson().toString());
        Long modelId = processModelService.createProcessModel(processModelDto);
        //更新流程实例
        boolean res = flowMetadataAggService.updateModel(modelId, flowConfig);
        Assert.assertTrue(res);
        return modelId;
    }


    /**
     * 创建配置信息
     */
    public void createModelConfig(Long modelId) {
        // 创建扩展信息
        ExtensionConfigDto extensionConfig = new ExtensionConfigDto();

        // 顺序流配置
        List<ExtensionSequenceFlowDto> sequenceFlows = new ArrayList<ExtensionSequenceFlowDto>();

        ExtensionSequenceFlowDto extensionSequenceFlowDto1 = new ExtensionSequenceFlowDto();
        extensionSequenceFlowDto1.setConditionId(1l);
        extensionSequenceFlowDto1.setElementId("element_id");
        extensionSequenceFlowDto1.setElementType(ElementTypeEnum.EXCLUSIVE_GATEWAY.getValue());
        extensionSequenceFlowDto1.extensionElementModel(modelId);
        sequenceFlows.add(extensionSequenceFlowDto1);

        extensionConfig.setSequenceFlows(sequenceFlows);
        // 用户任务配置
        List<ExtensionUserTaskDto> userTasks = new ArrayList<ExtensionUserTaskDto>();

        extensionConfig.setUserTasks(userTasks);
        // 服务任务配置
        List<ExtensionServiceTaskDto> serviceTasks = new ArrayList<ExtensionServiceTaskDto>();

        extensionConfig.setServiceTasks(serviceTasks);

        // 事件配置
        ExtensionModelConfigDto modelConfig = new ExtensionModelConfigDto();

        extensionConfig.setModelConfig(modelConfig);

        extensionService.upsertExtensionConfig(modelId, extensionConfig);
    }

    /**
     * 发布测试
     */
    public boolean deploymentTest(Long modelId) {
        return flowMetadataAggService.enableModel(modelId);
    }

    /**
     * 创建流程实例 提交阶段没有流程实例,根据dataId及entityKey启动流程实例
     */
    public void submitTest() {
        TaskActionRequestDto taskAction = new TaskActionRequestDto();
        taskAction.setDataId(DATA_ID);
        taskAction.setEntityKey(ENTITY_KEY);
        // 提交 TaskActionMappingEnum.valueOf(0) == SUBMIT
        taskAction.setActionType(TaskActionEnum.SUBMIT.getValue());
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("days", 4);
        taskAction.setVariables(variables);
        flowDataAggService.complete(taskAction);
    }

    /**
     * 审批测试:提交下一节点
     */
    public void forwordTest(TaskActionRequestDto taskAction) {
        // TaskActionMappingEnum.valueOf(1) == AGREE
        taskAction.setActionType(TaskActionEnum.AGREE.getValue());
        flowDataAggService.complete(taskAction);
    }

    /**
     * 回退测试
     */
    public void taskRejectTest(TaskActionRequestDto taskAction) {
        taskAction.setActionType(TaskActionEnum.REJECT.getValue());// TaskActionMappingEnum.valueOf(2) == REJECT
        flowDataAggService.complete(taskAction);
    }

    /**
     * 撤回测试
     */
    public void withdrawTest() {
        TaskActionRequestDto taskAction = new TaskActionRequestDto();
        taskAction.setDataId(DATA_ID);
        taskAction.setEntityKey(ENTITY_KEY);
        taskAction.setActionType(TaskActionEnum.WITHDRAW.getValue());
        // WITHDRAW
        flowDataAggService.complete(taskAction);
    }


    /**
     * 单步撤回测试
     */
    public void withdrawStepTest(String definitionId) {
        TaskActionRequestDto taskAction = new TaskActionRequestDto();
        taskAction.setDataId(DATA_ID);
//        taskAction.setDefinitionId(definitionId);
        taskAction.setEntityKey(ENTITY_KEY);
        taskAction.setActionType(4);// TaskActionMappingEnum.valueOf(4) ==
        // WITHDRAW_STEP
        flowDataAggService.complete(taskAction);
    }

    /**
     * 挂起测试
     */
    public void suspendTest(TaskActionRequestDto taskAction) {
        taskAction.setActionType(TaskActionEnum.SUSPEND.getValue());// TaskActionMappingEnum.valueOf(5) ==
        // SUSPEND
        flowDataAggService.complete(taskAction);
    }

    /**
     * 激活测试
     */
    public void activeTest(TaskActionRequestDto taskAction) {
        taskAction.setActionType(TaskActionEnum.ACTIVE.getValue());// TaskActionMappingEnum.valueOf(6) ==
        // ACTIVE
        flowDataAggService.complete(taskAction);
    }

    /**
     * 转办/委托测试DELEGATE
     */
    public void delegateTest(TaskActionRequestDto taskAction) {
        taskAction.setActionType(TaskActionEnum.DELEGATE.getValue());// TaskActionMappingEnum.valueOf(7) ==
        // ACTIVE
        flowDataAggService.complete(taskAction);
    }

    /**
     * 加签PLUS_SIGN
     */
    public void plussignTest(TaskActionRequestDto taskAction) {
        taskAction.setActionType(TaskActionEnum.PLUS_SIGN.getValue());// TaskActionMappingEnum.valueOf(8) ==
        // PLUS_SIGN
        flowDataAggService.complete(taskAction);
    }

    /**
     * 终止TERMINATE
     */
    public void terminalTest(TaskActionRequestDto taskAction) {
        taskAction.setActionType(TaskActionEnum.TERMINATE.getValue());// TaskActionMappingEnum.valueOf(9) ==
        // TERMINATE
        flowDataAggService.complete(taskAction);
    }

    // 匹配对应的dataId
    class DataIdMatcher implements ArgumentMatcher<Long> {
        @Override
        public boolean matches(Long arg0) {
            return DATA_ID.equals(arg0);
        }
    }

    /**
       * 单测执行成功后清除数据库
    **/
    @AfterEach
    public void cleanH2() {
        try{
            Connection connection = dataSource.getConnection();//获取连接
            //获取表名
//            ResultSet tables = connection.getMetaData().getTables(null, null, null, new String[]{"TABLE"});
//            while(tables.next()){
//                //若是测试类的测试方法超过7,java.sql.Connection无法获取连接导致死循环
//                PreparedStatement preparedStatement = connection.prepareStatement("Drop Table " + tables.getObject("TABLE_NAME"));
//                preparedStatement.execute();
//            }
            connection.prepareStatement("SHUTDOWN ").execute();
            log.info("关闭数据库");
            //记得关闭连接,或者使用连接池
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

集成flowable时,数据表分为两种:

  1.flowable自身需要的表结构

  2.自定义表结构

使用内存式数据库进行单测时,设置flowable自动创建自身需要的表结构,通过执行sql初始化自定义的表结构

flowable的配置

flowable:
  idm.enabled: false
  form.enabled: false
  cmmn.enabled: false
  dmn.enabled: false
  database-schema-update: create-drop
  db-history-used: true
  database-schema: PUBLIC
  rest-api-enabled: false
  async-executor-activate: false

  自定义表结构的sql

/******************************************/
/*   流程定义   */
/******************************************/
DROP TABLE IF EXISTS `p_process`;
CREATE TABLE `p_process`
(
    `id`            bigint(20)  NOT NULL AUTO_INCREMENT COMMENT 'id',
    `name`          varchar(256)        NOT NULL COMMENT '名称',
    `entity_key`    varchar(128)        NOT NULL COMMENT '关联的实体apiKey',
    `business_type` VARCHAR(50)         DEFAULT '' COMMENT '业务类型',
    `description`   VARCHAR(4000)       DEFAULT '' COMMENT '描述',
    `seq_no`        tinyint(2)          DEFAULT '1' COMMENT '顺序号',
    `process_type`  tinyint(2)          DEFAULT '1' COMMENT '流程类型, 1-工作流 2-审批流',
    `tenant_id`     bigint(20)          NOT NULL COMMENT '租户主键',
    `created_by`    bigint(20)          NOT NULL COMMENT '创建⼈',
    `updated_by`    bigint(20)          COMMENT '更新⼈',
    `created_at`    timestamp           DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at`    timestamp           COMMENT '更新时间'
);


/******************************************/
/*   流程版本   */
/******************************************/
DROP TABLE IF EXISTS `p_process_model`;
CREATE TABLE `p_process_model`
(
    `id`                bigint(20)  NOT NULL AUTO_INCREMENT COMMENT 'id',
    `name`              varchar(256)        NOT NULL COMMENT '名称',
    `process_id`        bigint(20)          NOT NULL COMMENT '关联的流程定义主键',
    `entity_key`        varchar(128)        NOT NULL COMMENT '关联的实体apiKey',
    `business_type`     VARCHAR(50)         DEFAULT '' COMMENT '业务类型',
    `definition_id`     VARCHAR(100)        DEFAULT '' COMMENT 'flowable中流程定义的主键',
    `deployment_id`     VARCHAR(100)        DEFAULT '' COMMENT 'flowable中流程部署的主键',
    `definition_key`    VARCHAR(100)        DEFAULT '' COMMENT 'flowable中流程定义的key',
    `description`       VARCHAR(4000)       DEFAULT '' COMMENT '描述',
    `model_editor_json` LONGTEXT COMMENT '模型设计json',
    `thumbnail`         LONGBLOB COMMENT '',
    `status`            tinyint(2)          DEFAULT '0' COMMENT '状态, 0-设计中 1-启用 2-禁用',
    `version`           tinyint(4)          DEFAULT '1' COMMENT '版本',
    `withdraw_type`     tinyint(1)          DEFAULT '1' COMMENT '撤回类型, 0-不支持 1-支持 2-支持单步',
    `tenant_id`         bigint(20)          NOT NULL COMMENT '租户主键',
    `created_by`        bigint(20)          NOT NULL COMMENT '创建⼈',
    `updated_by`        bigint(20)          COMMENT '更新⼈',
    `created_at`        timestamp           DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at`        timestamp           COMMENT '更新时间'
);

/******************************************/
/*   事件映射   */
/******************************************/
DROP TABLE IF EXISTS `p_extension_event`;
CREATE TABLE `p_extension_event`
(
    `id`           bigint(20)  NOT NULL AUTO_INCREMENT COMMENT 'id',
    `element_id`   varchar(256)        NOT NULL COMMENT '节点id',
    `model_id`     bigint(20)          NOT NULL COMMENT '关联的流程版本主键',
    `event_id`     bigint(20)          NOT NULL COMMENT '关联的事件主键',
    `condition_id` bigint(20)          DEFAULT NULL COMMENT '关联的条件主键',
    `button_id`    bigint(20)          DEFAULT NULL COMMENT '关联的按钮主键',
    `action_type`  tinyint(2)          DEFAULT '0' COMMENT '动作类型',
    `timing_type`  tinyint(2)          DEFAULT '0' COMMENT '时机类型 0-前事件  1-后事件',
    `tenant_id`    bigint(20)          NOT NULL COMMENT '租户主键',
    `created_by`   bigint(20)          NOT NULL COMMENT '创建⼈',
    `updated_by`   bigint(20)          COMMENT '更新⼈',
    `created_at`   timestamp           DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at`   timestamp           COMMENT '更新时间'
);

/******************************************/
/*   任务按钮   */
/******************************************/
DROP TABLE IF EXISTS `p_extension_button`;
CREATE TABLE `p_extension_button`
(
    `id`                         bigint(20)          NOT NULL AUTO_INCREMENT COMMENT 'id',
    `name`                       varchar(256)        NOT NULL COMMENT '按钮名称',
    `element_id`                 varchar(256)        NOT NULL COMMENT '节点id',
    `model_id`                   bigint(20)          NOT NULL COMMENT '关联的流程版本主键',
    `action_type`                tinyint(2)          DEFAULT '0' COMMENT '动作类型',
    `reject_action`              tinyint(2)          DEFAULT '0' COMMENT '拒绝后动作',
    `reject_task_definition_key` varchar(256)        DEFAULT NULL COMMENT '拒绝后目标节点id',
    `definition_id`              varchar(256)        DEFAULT NULL COMMENT '流程定义id',
    `tenant_id`                  bigint(20)          NOT NULL COMMENT '租户主键',
    `created_by`                 bigint(20)          NOT NULL COMMENT '创建⼈',
    `updated_by`                 bigint(20)          COMMENT '更新⼈',
    `created_at`                 timestamp           DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at`                 timestamp           COMMENT '更新时间'
);

/******************************************/
/*   选人策略   */
/******************************************/
DROP TABLE IF EXISTS `p_extension_assignment`;
CREATE TABLE `p_extension_assignment`
(
    `id`               bigint(20)          NOT NULL AUTO_INCREMENT COMMENT 'id',
    `element_id`       varchar(256)        NOT NULL COMMENT '节点id',
    `model_id`         bigint(20)          NOT NULL COMMENT '关联的流程版本主键',
    `candidate_type`   tinyint(2)          DEFAULT '0' COMMENT '选人类型',
    `candidate_detail` varchar(256)        DEFAULT NULL COMMENT '选人详情',
    `tenant_id`        bigint(20)          NOT NULL COMMENT '租户主键',
    `created_by`       bigint(20)          NOT NULL COMMENT '创建⼈',
    `updated_by`       bigint(20)          COMMENT '更新⼈',
    `created_at`       timestamp           DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at`       timestamp           COMMENT '更新时间'
);

/******************************************/
/*   扩展元素   */
/******************************************/
DROP TABLE IF EXISTS `p_extension_element`;
CREATE TABLE `p_extension_element`
(
    `id`             bigint(20)          NOT NULL AUTO_INCREMENT COMMENT 'id',
    `element_id`     varchar(256)        NOT NULL COMMENT '节点id',
    `model_id`       bigint(20)          NOT NULL COMMENT '关联的流程版本主键',
    `element_type`   tinyint(2)          DEFAULT '0' COMMENT '节点元素类型',
    `extension_json` varchar(2000)       NOT NULL COMMENT '扩展属性',
    `tenant_id`      bigint(20)          NOT NULL COMMENT '租户主键',
    `created_by`     bigint(20)          NOT NULL COMMENT '创建⼈',
    `updated_by`     bigint(20)          COMMENT '更新⼈',
    `created_at`     timestamp           DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at`     timestamp           COMMENT '更新时间'
);

-- 1.事件表
DROP TABLE IF EXISTS `p_event`;
CREATE TABLE `p_event`
(
    `id`              bigint(20)         NOT NULL COMMENT '主键',
    `name`            varchar(50)        NOT NULL COMMENT '事件名称',
    `type`            tinyint(5)         NOT NULL COMMENT '事件类型 1-短信,2-微信,3-邮件,4-业务',
    `type_mapping_id` bigint(20)         DEFAULT NULL COMMENT '消息id/交互业务id',
    `tenant_id`       bigint(20)         NOT NULL COMMENT '组织id',
    `entity_key`      varchar(128)       NOT NULL COMMENT '业务对象主键',
    `business_type`   varchar(128)       NOT NULL COMMENT '业务对象类型',
    `delete_flg`      tinyint(5)         NOT NULL COMMENT '删除标识',
    `description`     varchar(200)       NOT NULL COMMENT '说明',
    `created_by`      bigint(20)         NOT NULL COMMENT '创建人',
    `created_at`      timestamp          DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_by`      bigint(20)         DEFAULT NULL COMMENT '更新人',
    `updated_at`      timestamp          COMMENT '更新时间'
);

-- 2.消息接收人表
DROP TABLE IF EXISTS `p_message_receiver`;
CREATE TABLE `p_message_receiver`
(
    `id`         bigint(20)         NOT NULL COMMENT '主键',
    `tenant_id`  bigint(20)         NOT NULL COMMENT '组织id',
    `event_id`   bigint(20)         NOT NULL COMMENT '事件id',
    `type`       tinyint(5)         NOT NULL COMMENT '接受人类型 1-对象字段指定,2-流程相关用户,3-指定用户',
    `expression` varchar(200)       NOT NULL COMMENT '取值表达式',
    `created_by` bigint(20)         NOT NULL COMMENT '创建人',
    `created_at` timestamp          DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_by` bigint(20)         COMMENT '更新人',
    `updated_at` timestamp          DEFAULT NULL COMMENT '更新时间'
);

-- 3.消息字段映射表 改为字段映射表
DROP TABLE IF EXISTS `p_item_mapping`;
CREATE TABLE `p_item_mapping`
(
    `id`         bigint(20)        NOT NULL COMMENT '主键',
    `tenant_id`  bigint(20)        NOT NULL COMMENT '组织id',
    `event_id`   bigint(20)        NOT NULL COMMENT '事件id',
    `item_name`  varchar(200)      NOT NULL COMMENT '字段名',
    `item_value` varchar(200)      NOT NULL COMMENT '字段值',
    `type`       tinyint(5)        NOT NULL COMMENT '字段值类型:1-实际值、2-数据中心表达式、3-流程中心表达式',
    `created_by` bigint(20)        NOT NULL COMMENT '创建人',
    `created_at` timestamp         DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_by` bigint(20)        COMMENT '更新人',
    `updated_at` timestamp         DEFAULT NULL COMMENT '更新时间'
);

-- 4.执行事件日志表
DROP TABLE IF EXISTS `p_event_log`;
CREATE TABLE `p_event_log`
(
    `id`             bigint(20)         NOT NULL COMMENT '主键',
    `tenant_id`      bigint(20)         NOT NULL COMMENT '组织id',
    `event_id`       bigint(20)         NOT NULL COMMENT '事件id',
    `data_id`        bigint(20)         NOT NULL COMMENT '数据id',
    `request`        text               NOT NULL COMMENT '传入参数',
    `response`       text               NOT NULL COMMENT '传出参数',
    `failure_reason` varchar(250)       NOT NULL COMMENT '失败原因',
    `result`         boolean            NOT NULL COMMENT '执行结果',
    `request_time`   timestamp          NOT NULL COMMENT '请求时间',
    `created_by`     bigint(20)         NOT NULL COMMENT '创建人',
    `created_at`     timestamp          DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_by`     bigint(20)         COMMENT '更新人',
    `updated_at`     timestamp          DEFAULT NULL COMMENT '更新时间'
);

-- 5.交互业务表
DROP TABLE IF EXISTS `p_interact_business`;
CREATE TABLE `p_interact_business`
(
    `id`              bigint(20)            NOT NULL COMMENT '主键',
    `name`            varchar(100)          NOT NULL COMMENT '交互业务名称',
    `type`            tinyint(5)            NOT NULL COMMENT '交互业务类型1-事件',
    `schema`          tinyint(5)            NOT NULL COMMENT '协议1-http,2-https',
    `domain`          varchar(100)          NOT NULL COMMENT '域',
    `path`            varchar(200)          NOT NULL COMMENT '路径',
    `method`          varchar(50)           NOT NULL COMMENT '请求方式',
    `request_schema`  varchar(50)           COMMENT '请求协议(暂无处理)',
    `response_schema` varchar(50)           COMMENT '响应协议(暂无处理)',
    `tenant_id`       bigint(20)            NOT NULL COMMENT '所属租户',
    `created_by`      bigint(20)            NOT NULL COMMENT '创建人',
    `created_at`      timestamp             DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_by`      bigint(20)            COMMENT '更新人',
    `updated_at`      timestamp             DEFAULT NULL COMMENT '更新时间'
);


/**
    添加事件执行流水记录表
 */
DROP TABLE IF EXISTS `p_event_record`;

CREATE TABLE `p_event_record` (
                                  `id` bigint(20)  NOT NULL AUTO_INCREMENT COMMENT '主键',
                                  `tenant_id` bigint(20) NOT NULL COMMENT '组织id',
                                  `action_type` tinyint(2) NOT NULL COMMENT '操作类型',
                                  `event_id` bigint(20) NOT NULL COMMENT '事件id',
                                  `event_type` tinyint(5) NOT NULL COMMENT '事件类型',
                                  `event_name` varchar(50)  COMMENT '事件名称',
                                  `timing_type` tinyint(5)  COMMENT '事件执行边界',
                                  `execute_type` tinyint(5)  COMMENT '事件执行方式,异步/同步',
                                  `retry_count` int(11)  COMMENT '事件重试次数',
                                  `entity_key` varchar(50)  COMMENT '实体id',
                                  `data_id` bigint(20)  COMMENT '数据id',
                                  `condition_id` bigint(20)  COMMENT '事件执行条件id',
                                  `condition_result` tinyint(1) DEFAULT '0' COMMENT '事件条件执行结果',
                                  `condition_status` tinyint(5) DEFAULT NULL COMMENT '条件执行状态',
                                  `process_instance_id` varchar(100)  COMMENT '流程实例id',
                                  `process_definition_id` varchar(100)  COMMENT '流程定义Id',
                                  `task_definition_key` varchar(100)  COMMENT '任务节点id',
                                  `next_task_definition_key` varchar(100) DEFAULT NULL COMMENT '下一节点taskKey',
                                  `task_name` varchar(50) DEFAULT NULL COMMENT '任务节点名称',
                                  `mq_message_tag` varchar(50) COMMENT '事件报文在mq上的messageTag',
                                  `send_message_status` tinyint(5) DEFAULT '2' COMMENT '事件报文发送状态',
                                  `mq_message_id` varchar(50) DEFAULT NULL COMMENT '事件消息在mq上的id',
                                  `event_execute_status` tinyint(5) DEFAULT '0' COMMENT '事件执行状态',
                                  `result` varchar(200) DEFAULT NULL COMMENT '事件执行结果',
                                  `created_by` bigint(20)  COMMENT '创建人',
                                  `created_at` timestamp  DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                  `updated_by` bigint(20) DEFAULT NULL COMMENT '更新人',
                                  `updated_at` timestamp  DEFAULT NULL COMMENT '更新时间'
);



DROP TABLE IF EXISTS `p_event_record_detail`;
CREATE TABLE `p_event_record_detail` (
                                         `id` bigint(20)                        NOT NULL COMMENT '主键',
                                         `tenant_id` bigint(20)                 NOT NULL COMMENT '组织id',
                                         `record_id` bigint(20)                 NOT NULL COMMENT '流水记录id:p_event_record:id',
                                         `event_id` bigint(20)                  NOT NULL COMMENT '事件id',
                                         `event_type` tinyint(5)                NOT NULL COMMENT '事件类型',
                                         `event_name` varchar(50)               COMMENT '事件名称',
                                         `timing_type` tinyint(5)               DEFAULT NULL  COMMENT '事件执行边界',
                                         `execute_type` tinyint(5)              COMMENT '事件执行方式,异步/同步',
                                         `fail_rollback` tinyint(5)             NOT NULL DEFAULT 1 COMMENT '同步事件回滚标记:0:回滚;1:不回滚',
                                         `retry_count` int(11)                  COMMENT '事件重试次数',
                                         `condition_id` bigint(20)              COMMENT '事件执行条件id',
                                         `condition_status` tinyint(5)          DEFAULT NULL COMMENT '条件执行状态  0:未执行;1:执行异常;2:执行成功',
                                         `mq_message_tag` varchar(50)           COMMENT '异步事件报文在mq上的messageTag',
                                         `mq_message_id` varchar(64)            DEFAULT NULL COMMENT '事件消息在mq上的id',
                                         `execute_required` tinyint(1)          NOT NULL DEFAULT 1 COMMENT '是否需要执行该事件',
                                         `event_execute_status` tinyint(5)      DEFAULT '0' COMMENT '事件执行状态',
                                         `event_execute_result` varchar(1000)   DEFAULT NULL COMMENT '事件执行结果',
                                         `created_by` bigint(20)                COMMENT '创建人',
                                         `created_at` timestamp                DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                         `updated_by` bigint(20)               DEFAULT NULL COMMENT '更新人',
                                         `updated_at` timestamp                DEFAULT NULL COMMENT '更新时间'
);
--添加事件执行方式
ALTER TABLE `p_event` ADD (
    execute_type tinyint(1) NOT NULL DEFAULT 2 COMMENT '事件执行方式:1:异步执行;2同步执行',
    fail_rollback tinyint(1) NOT NULL DEFAULT 1 COMMENT '同步事件失败回滚标记:0:回滚;1:不回滚',
    delay_delivery_time int(11) NOT NULL DEFAULT 0 COMMENT '事件延迟执行时间(单位秒)'
    );


ALTER TABLE `p_event` ADD (request_source tinyint(5) NOT NULL DEFAULT 0 COMMENT '事件请求来源:0.普通事件,1.流程事件',execute_order int(3) NOT NULL DEFAULT 0 COMMENT '执行顺序:数字越小,优先级越高');

ALTER TABLE `p_event_log` ADD request_source tinyint(5) NOT NULL DEFAULT 0 COMMENT '事件请求来源:0.普通事件,1.流程事件';

ALTER TABLE `p_event_record` ADD request varchar(1000) NOT NULL DEFAULT '' COMMENT '普通事件的参数';

ALTER TABLE `p_event_record_detail` ADD request_source tinyint(5) NOT NULL DEFAULT 0 COMMENT '事件请求来源:0.普通事件,1.流程事件';

 配置内存数据库H2

  

import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

/**
 * @author jiangliangyou
 * @date 2020-07-08
 */
@Slf4j
@Configuration
@Profile("test")
public class TestBeanConfig {

	@Bean
	public DataSource dataSource() {
		return new EmbeddedDatabaseBuilder()
				.setName("ig_platform_flow;MODE=MySQL;DATABASE_TO_UPPER=true;")
				.setType(EmbeddedDatabaseType.H2)
				.addScript("classpath:custom_flow.sql")
				.build();
	}
}

 

注意:当有多个单测时,每测试一个类就会重新初始化数据库及配置,此时需要在单测中,添加执行后方法,用来关闭内存数据库,不然在执行下一个单测的初始化时,会报错(表结构xxxx已存在,不能创建xxxx) 

原文地址:https://www.cnblogs.com/zhlblogs/p/14805970.html