package org.matrix.testNg;

import org.matrix.actuators.checkpoint.CheckPointResult;
import org.matrix.actuators.usecase.CaseActuator;
import org.matrix.actuators.usecase.TestCaseExecuteResult;
import org.matrix.database.entity.TestCase;
import org.matrix.database.service.ITestCaseService;
import org.matrix.exception.GlobalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.*;

import java.util.Iterator;
import java.util.Map;

/**
 * @author mry
 */
@SpringBootTest
public class TestPigeon extends AbstractTestNGSpringContextTests {

    String sql;
    Long envId;
    Long projectId;

    @Autowired
    private ITestCaseService caseService;

    @Parameters({"sql", "envId", "projectId"})
    @BeforeClass
    public void beforeClass(String sql, Long envId, Long projectId) {
        this.sql = sql;
        this.envId = envId;
        this.projectId = projectId;
    }

    /**
     * XML中的SQL决定了执行什么用例, 执行多少条用例, SQL的搜索结果为需要测试的测试用例
     */
    @DataProvider(name = "testData")
    private Iterator<Object[]> getData() {
        return new DataProviderForDb(TestConfig.DB_IP, TestConfig.DB_PORT,
                TestConfig.DB_BASE_NAME, TestConfig.DB_USERNAME, TestConfig.DB_PASSWORD, sql);
    }


    @Test(dataProvider = "testData")
    public void test(Map<String, String> data) {
        long caseId = Long.parseLong(data.get("id"));
        CaseActuator caseActuator = new CaseActuator(envId, projectId);
        TestCase testCase = java.util.Optional.of(caseService.getById(caseId))
                .orElseThrow(() -> new GlobalException(String.format("没有找到id = %d 的TestCase", caseId)));
        TestCaseExecuteResult testCaseExecuteResult = caseActuator.executeTestCase(testCase);
        CheckPointResult checkPointResult = testCaseExecuteResult.getCheckPointResult();
        Reporter.log(checkPointResult.toString());
    }

    @AfterMethod
    public void afterMethod(ITestResult result, Object[] objs) {
        System.out.println("正在运行的方法:" + result.getName());
    }

}
