分布式测试框架,提供在客户端调用服务端接口并在服务端执行相应操作的能力
remoteHelper
1.将需要调用的类名、方法名、参数等信息写入apiMessage对象,apiMessage对象可传输以下数据
let message = new ApiMessage("openHarmony","testApi","add"," ",["number","number"],[String(a),String(b)]," ");
var messageParcel = rpc.MessageParcel.create();
// 读取message中的信息并将之写入MessageParcel
messageParcel.writeSequenceable(message);
实例化apiMessage对象构造函数需要的参数:
let message = new ApiMessage(deviceName, className, methodName, apiSession, parameterTypes, parameters, apiResult);
2.使用sendRequest将数据传输到服务端,并接受其返回的数据
await this.gIRemoteObject.sendRequest(CODE_INVOKE, messageParcel, messageParcelreply, option);
var ret = new ApiMessage(null, null, null, null, null, null,null);
// 将返回的数据写入apiMessage对象ret中
messageParcelreply.readSequenceable(ret);
messageParcelreply为返回的数据
3.解析ret中的执行结果,并返回给用例层
results = JSON.parse(ret._apiResult);
return results._result;
Service
1.监听传输数据
onRemoteRequest(code, data, reply, option)
data为客户端传输过来的数据,执行结果会赋值给参数reply,传递回客户端
2.解析客户端发送的信息,并将之写在一个新的apiMessage对象中
let testBundle = new ApiMessage(null, null, null, null, null, null, null);
data.readSequenceable(testBundle)
// 此时的testBundle为
// testBundle == new ApiMessage("openHarmony","testApi","add"," ",["number","number"],[String(a),String(b)]," ")
3.将解析完毕的信息发送至testBundleManager
let testBundleManager = new TestBundleManager();
testBundleManager.invoke(testBundle);
4.将执行的结果赋值给参数reply
// invoke将会分析testBundle中的信息,去执行对应类中的对应函数并将结果写在apiResult对象中返回
let testBundleResult = testBundleManager.invoke(testBundle)
// 将返回的apiResult赋值给testBundle的最后一个属性
testBundle._apiResult=JSON.stringify(testBundleResult)
// 将testBundle的信息写入reply
reply.writeSequenceable(testBundle)
testBundleManager
invoke()将会分析testBundle中的内容,了解到要执行哪个类中的哪个方法,要传入的参数并调用对应类中的对应函数,并返回对应结果
invoke(testBundle) {
this._classname = testBundle._className;
this._methodName = testBundle._methodName;
this._parameterTypes = testBundle._parameterTypes;
this._parameters = testBundle._parameters;
let result = new ApiResult();
if(this._methodName == "add") {
let test = new TestApi();
let resultNum = test.add(this._parameters[0], this._parameters[1]);
console.log(logTag+"_methodName invoke success,result is "+resultNum);
result._resultCode = true;
result._result = resultNum;
return result;
}
}
testApi
要执行的函数,会将执行结果返回
add(a,b) {
console.log(logTag+"_methodName is add");
return Number(a)+Number(b);
}
其大致流程为:用例层调用remoteHelper函数将要执行的方法,要传入的参数等信息传输至服务,服务端接受到之后经过解析,执行对应函数并将结果返回给remoteHelper,之后remoteHelper将结果返回给用例。
遗留问题:
- 该框架中的客户端和服务端传输信息主要使用的是rpc服务,在传输过程中将会把所有信息都转换成String类型,因此需要在服务收到信息并解析之后再做相应的类型转换,从而导致传递对象,数组等较复杂类型的内容会在服务端转换失败,产生意料之外的错误。
- 服务端的组件执行的基本都为同步方法,因此如果想在服务端执行异步函数会导致同步方法中获取不到异步函数执行结果的问题。
由于invoke是同步函数,所以在执行异步函数时不可以加await(await 只能用在异步函数中),尝试过使用callback回调方法,generator函数 generator+promise调用,结果都没有获取到想要的结果。