代码结构优化,用例时间统计,断言跳出执行用例

Signed-off-by: taoshunli <taoshunli@huawei.com>
This commit is contained in:
taoshunli
2022-08-10 10:22:05 +08:00
parent 1574b053f2
commit 053202db34
6 changed files with 126 additions and 150 deletions
+33 -68
View File
@@ -13,89 +13,54 @@
* limitations under the License.
*/
import Core from './src/core'
import {DEFAULT, TestType, Size, Level} from './src/Constant'
import DataDriver from './src/module/config/DataDriver'
import ExpectExtend from './src/module/assert/ExpectExtend'
import OhReport from './src/module/report/OhReport'
import SysTestKit from './src/module/kit/SysTestKit'
import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from './src/interface'
import Core from './src/core';
import {DEFAULT, TestType, Size, Level} from './src/Constant';
import DataDriver from './src/module/config/DataDriver';
import ExpectExtend from './src/module/assert/ExpectExtend';
import OhReport from './src/module/report/OhReport';
import SysTestKit from './src/module/kit/SysTestKit';
import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from './src/interface';
import {MockKit, when} from './src/module/mock/MockKit';
import ArgumentMatchers from './src/module/mock/ArgumentMatchers';
function dryRun(core, testParameters, abilityDelegator) {
if (testParameters['dryRun'] === 'true') {
let testSuitesObj = {}
let suitesArray = []
const suiteService = core.getDefaultService('suite')
for (const suiteItem of suiteService.rootSuite.childSuites) {
let itArray = []
let suiteName = suiteItem['description']
for (const itItem of suiteItem['specs']) {
itArray.push({'itName': itItem['description']})
}
let obj = {}
obj[suiteName] = itArray
suitesArray.push(obj)
}
testSuitesObj['suites'] = suitesArray
let strJson = JSON.stringify(testSuitesObj)
let strLen = strJson.length
let maxLen = 500
let maxCount = Math.floor(strLen / maxLen)
for (let count = 0; count <= maxCount; count++) {
abilityDelegator.print(strJson.substring(count * maxLen, (count + 1) * maxLen))
}
console.info('dryRun print success')
abilityDelegator.finishTest('dry run finished!!!', 0, () => { })
return true
}
return false
}
class Hypium {
static setData(data) {
const core = Core.getInstance()
const dataDriver = new DataDriver({data})
core.addService('dataDriver', dataDriver)
const core = Core.getInstance();
const dataDriver = new DataDriver({data});
core.addService('dataDriver', dataDriver);
}
static hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) {
const core = Core.getInstance()
const core = Core.getInstance();
const expectExtend = new ExpectExtend({
'id': 'extend'
})
core.addService('expect', expectExtend)
});
core.addService('expect', expectExtend);
const ohReport = new OhReport({
'delegator': abilityDelegator
})
SysTestKit.delegator = abilityDelegator
core.addService('report', ohReport)
core.init()
core.subscribeEvent('spec', ohReport)
core.subscribeEvent('suite', ohReport)
core.subscribeEvent('task', ohReport)
const configService = core.getDefaultService('config')
let testParameters = configService.translateParams(abilityDelegatorArguments.parameters)
console.info('parameters:' + JSON.stringify(testParameters))
configService.setConfig(testParameters)
testsuite()
if (dryRun(core, testParameters, abilityDelegator)) {
return
}
});
SysTestKit.delegator = abilityDelegator;
core.addService('report', ohReport);
core.init();
core.subscribeEvent('spec', ohReport);
core.subscribeEvent('suite', ohReport);
core.subscribeEvent('task', ohReport);
const configService = core.getDefaultService('config');
let testParameters = configService.translateParams(abilityDelegatorArguments.parameters);
console.info('parameters:' + JSON.stringify(testParameters));
configService.setConfig(testParameters);
testsuite();
if (Object.prototype.hasOwnProperty.call(globalThis, 'setupUiTestEnvironment')) {
globalThis.setupUiTestEnvironment().then(() => {
console.info('UiTestKit::after run uitest setup, start run testcases')
core.execute()
console.info('UiTestKit::after run uitest setup, start run testcases');
core.execute(abilityDelegator);
}).catch((error) => {
console.error('UiTestKit:: call setupUiTestEnvironment failure:' + error)
core.execute()
})
console.error('UiTestKit:: call setupUiTestEnvironment failure:' + error);
core.execute(abilityDelegator);
});
} else {
console.info('UiTestKit:: no need to setup uitest, start run testcases')
core.execute()
console.info('UiTestKit:: no need to setup uitest, start run testcases');
core.execute(abilityDelegator);
}
}
}
@@ -114,4 +79,4 @@ export {
describe, beforeAll, beforeEach, afterEach, afterAll, it, expect,
MockKit, when,
ArgumentMatchers
}
};
+3 -38
View File
@@ -23,38 +23,6 @@ import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from '
import {MockKit, when} from './src/module/mock/MockKit';
import ArgumentMatchers from './src/module/mock/ArgumentMatchers';
function dryRun(core, testParameters, abilityDelegator) {
if (testParameters['dryRun'] === 'true') {
let testSuitesObj = {};
let suitesArray = [];
const suiteService = core.getDefaultService('suite');
for (const suiteItem of suiteService.rootSuite.childSuites) {
let itArray = [];
let suiteName = suiteItem['description'];
for (const itItem of suiteItem['specs']) {
itArray.push({'itName': itItem['description']});
}
let obj = {};
obj[suiteName] = itArray;
suitesArray.push(obj);
}
testSuitesObj['suites'] = suitesArray;
let strJson = JSON.stringify(testSuitesObj);
let strLen = strJson.length;
let maxLen = 500;
let maxCount = Math.floor(strLen / maxLen);
for (let count = 0; count <= maxCount; count++) {
abilityDelegator.print(strJson.substring(count * maxLen, (count + 1) * maxLen));
}
console.info('dryRun print success');
abilityDelegator.finishTest('dry run finished!!!', 0, () => { });
return true;
}
return false;
}
class Hypium {
static setData(data) {
const core = Core.getInstance();
@@ -82,20 +50,17 @@ class Hypium {
console.info('parameters:' + JSON.stringify(testParameters));
configService.setConfig(testParameters);
testsuite();
if (dryRun(core, testParameters, abilityDelegator)) {
return;
}
if (Object.prototype.hasOwnProperty.call(globalThis, 'setupUiTestEnvironment')) {
globalThis.setupUiTestEnvironment().then(() => {
console.info('UiTestKit::after run uitest setup, start run testcases');
core.execute();
core.execute(abilityDelegator);
}).catch((error) => {
console.error('UiTestKit:: call setupUiTestEnvironment failure:' + error);
core.execute();
core.execute(abilityDelegator);
});
} else {
console.info('UiTestKit:: no need to setup uitest, start run testcases');
core.execute();
core.execute(abilityDelegator);
}
}
}
+7 -2
View File
@@ -141,9 +141,14 @@ class Core {
}
}
execute() {
execute(abilityDelegator) {
const suiteService = this.getDefaultService('suite');
suiteService.execute();
if (suiteService.dryRun(abilityDelegator)) {
return;
}
setTimeout(() => {
suiteService.execute();
}, 10);
}
}
+12 -10
View File
@@ -21,6 +21,16 @@ class ConfigService {
this.supportAsync = false;
this.random = false;
this.filterValid = [];
this.filter = 0;
this.flag = false;
this.suite = null;
this.itName = null;
this.testType = null;
this.level = null;
this.size = null;
this.class = null;
this.notClass = null;
this.timeout = null;
}
init(coreContext) {
@@ -106,6 +116,7 @@ class ConfigService {
this.level = params.level;
this.size = params.size;
this.timeout = params.timeout;
this.dryRun = params.dryRun;
this.filterParam = {
testType: {
'function': 1,
@@ -135,16 +146,7 @@ class ConfigService {
};
this.parseParams();
} catch (err) {
this.filter = 0;
this.flag = false;
this.suite = null;
this.itName = null;
this.testType = null;
this.level = null;
this.size = null;
this.class = null;
this.notClass = null;
this.timeout = null;
console.info('setConfig error: ' + err.message);
}
}
+9 -11
View File
@@ -38,7 +38,7 @@ class OhReport {
message += ', Error: ' + summary.error;
message += ', Pass: ' + summary.pass;
message += '\n' + 'OHOS_REPORT_CODE: ' + (summary.failure > 0 ? -1 : 0) + '\n';
message += 'OHOS_REPORT_STATUS: consuming=' + summary.duration + '\n';
message += 'OHOS_REPORT_STATUS: taskconsuming=' + summary.duration + '\n';
this.delegator.print(message).then(() => {
console.info('report print success');
this.delegator.finishTest('your test finished!!!', 0, () => {
@@ -56,28 +56,26 @@ class OhReport {
}
suiteStart() {
let suiteService = this.coreContext.getDefaultService('suite');
var message = '\n' + 'OHOS_REPORT_SUM: ' + suiteService.getCurrentRunningSuite().getSpecsNum();
message += '\n' + 'OHOS_REPORT_STATUS: class=' + suiteService.getCurrentRunningSuite().description + '\n';
var message = '\n' + 'OHOS_REPORT_SUM: ' + this.suiteService.getCurrentRunningSuite().getSpecsNum();
message += '\n' + 'OHOS_REPORT_STATUS: class=' + this.suiteService.getCurrentRunningSuite().description + '\n';
this.delegator.print(message).then(() => {
console.info(suiteService.getCurrentRunningSuite().description + ' print success');
console.info(this.suiteService.getCurrentRunningSuite().description + ' print success');
});
}
suiteDone() {
var message = '\n' + 'OHOS_REPORT_STATUS: class=' + this.suiteService.getCurrentRunningSuite().description;
message += '\n' + 'OHOS_REPORT_STATUS: consuming=' + this.suiteService.getCurrentRunningSuite().duration + '\n';
message += '\n' + 'OHOS_REPORT_STATUS: suiteconsuming=' + this.suiteService.getCurrentRunningSuite().duration + '\n';
this.delegator.print(message).then(() => {
console.info(suiteService.getCurrentRunningSuite().description + ' print success');
console.info(this.suiteService.getCurrentRunningSuite().description + ' print success');
});
}
specStart() {
let suiteService = this.coreContext.getDefaultService('suite');
var message = '\n' + 'OHOS_REPORT_STATUS: class=' + suiteService.getCurrentRunningSuite().description;
var message = '\n' + 'OHOS_REPORT_STATUS: class=' + this.suiteService.getCurrentRunningSuite().description;
message += '\n' + 'OHOS_REPORT_STATUS: current=' + (++this.index);
message += '\n' + 'OHOS_REPORT_STATUS: id=JS';
message += '\n' + 'OHOS_REPORT_STATUS: numtests=' + suiteService.getSummary().total;
message += '\n' + 'OHOS_REPORT_STATUS: numtests=' + this.suiteService.getSummary().total;
message += '\n' + 'OHOS_REPORT_STATUS: stream=';
message += '\n' + 'OHOS_REPORT_STATUS: test=' + this.specService.currentRunningSpec.description;
message += '\n' + 'OHOS_REPORT_STATUS_CODE: 1' + '\n';
@@ -102,7 +100,7 @@ class OhReport {
} else if (this.specService.currentRunningSpec.result) {
if (this.specService.currentRunningSpec.result.failExpects.length > 0) {
this.specService.currentRunningSpec.result.failExpects.forEach(failExpect => {
emsg = failExpect.message || ('expect ' + failExpect.actualValue + ' ' + failExpect.checkFunc + ' ' + (failExpect.expectValue || ''));
emsg = failExpect.message || ('expect ' + failExpect.actualValue + ' ' + failExpect.checkFunc + ' ' + (failExpect.expectValue));
});
message += '\n' + 'OHOS_REPORT_STATUS: stack=' + emsg;
message += '\n' + 'OHOS_REPORT_STATUS: stream=';
+62 -21
View File
@@ -12,6 +12,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class AssertException extends Error {
constructor() {
super();
this.name = "AssertException";
}
}
function processFunc(coreContext, func) {
let argNames = ((func || '').toString()
@@ -39,11 +45,10 @@ function processFunc(coreContext, func) {
function done() {
resolve();
}
let funcType = func(done);
if (funcType instanceof Promise) {
funcType.catch(err => {
reject(err);
});
funcType.catch(err => {reject(err);});
}
});
};
@@ -59,9 +64,7 @@ function processFunc(coreContext, func) {
let funcType = func(done, paramItem);
if (funcType instanceof Promise) {
funcType.catch(err => {
reject(err);
});
funcType.catch(err => {reject(err);});
}
});
};
@@ -157,6 +160,45 @@ class SuiteService {
this.coreContext = coreContext;
}
dryRun(abilityDelegator) {
let configService = this.coreContext.getDefaultService('config');
if (configService['dryRun'] !== 'true') {
return false;
}
let testSuitesObj = {};
let suitesArray = [];
for (const suiteItem of this.rootSuite.childSuites) {
let itArray = [];
let suiteName = suiteItem['description'];
for (const itItem of suiteItem['specs']) {
let itName = itItem['description'];
let filter = itItem['fi'];
if (!configService.filterDesc(suiteName, itName, filter, this.coreContext)) {
itArray.push({'itName': itItem['description']});
}
}
if (!configService.filterSuite(suiteName) && (itArray.length > 0)) {
let obj = {};
obj[suiteName] = itArray;
suitesArray.push(obj);
}
}
testSuitesObj['suites'] = suitesArray;
let strJson = JSON.stringify(testSuitesObj);
let strLen = strJson.length;
let maxLen = 500;
let maxCount = Math.floor(strLen / maxLen);
for (let count = 0; count <= maxCount; count++) {
abilityDelegator.print(strJson.substring(count * maxLen, (count + 1) * maxLen));
}
console.info('dryRun print success');
abilityDelegator.finishTest('dry run finished!!!', 0, () => { });
return true;
}
execute() {
if (this.coreContext.getDefaultService('config').filterValid.length !== 0) {
this.coreContext.fireEvents('task', 'incorrectFormat');
@@ -425,7 +467,7 @@ SpecService.Spec = class {
specService.setCurrentRunningSpec(this);
this.startTime = new Date().getTime();
const config = coreContext.getDefaultService('config');
const timeout = +(config.timeout === undefined ? 5000 : config.timeout);
const timeout = + (config.timeout === undefined ? 5000 : config.timeout);
return new Promise(async resolve => {
coreContext.fireEvents('spec', 'specStart', this);
@@ -439,9 +481,7 @@ SpecService.Spec = class {
let dataDriver = coreContext.getServices('dataDriver');
if (typeof dataDriver === 'undefined') {
const p = Promise.race([this.fn(), timeoutPromise()]);
await p.then(() => {
this.setResult();
});
await p.then(() => {this.setResult();});
} else {
let suiteParams = dataDriver.dataDriver.getSuiteParams();
let specParams = dataDriver.dataDriver.getSpecParams();
@@ -449,25 +489,24 @@ SpecService.Spec = class {
console.info('[spec params] ' + JSON.stringify(specParams));
if (this.fn.length === 0) {
const p = Promise.race([this.fn(), timeoutPromise()]);
await p.then(() => {
this.setResult();
});
await p.then(() => {this.setResult();});
} else if (specParams.length === 0) {
const p = Promise.race([this.fn(suiteParams), timeoutPromise()]);
await p.then(() => {
this.setResult();
});
await p.then(() => {this.setResult();});
} else {
for (const paramItem of specParams) {
const p = Promise.race([this.fn(Object.assign({}, paramItem, suiteParams)), timeoutPromise()]);
await p.then(() => {
this.setResult();
});
const p = Promise.race([this.fn(Object.assign({}, paramItem, suiteParams)),
timeoutPromise()]);
await p.then(() => {this.setResult();});
}
}
}
} catch (e) {
this.error = e;
if (e instanceof AssertException) {
this.fail = e;
} else {
this.error = e;
}
}
coreContext.fireEvents('spec', 'specDone', this);
resolve();
@@ -485,6 +524,7 @@ SpecService.Spec = class {
this.result.passExpects.push(expectResult);
} else {
this.result.failExpects.push(expectResult);
throw new AssertException(expectResult);
}
}
};
@@ -595,6 +635,7 @@ class ReportService {
taskStart() {
this.sleep(50);
this.taskStartTime = new Date().getTime();
console.info('[start] start run suites');
}