update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai 2021-06-02 00:45:00 +08:00
parent cabddaf5c8
commit 76c1a12a36
93 changed files with 1453 additions and 5902 deletions

15
.gitattributes vendored Normal file
View File

@ -0,0 +1,15 @@
*.tgz filter=lfs diff=lfs merge=lfs -text
*.trp filter=lfs diff=lfs merge=lfs -text
*.apk filter=lfs diff=lfs merge=lfs -text
*.jar filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.asm filter=lfs diff=lfs merge=lfs -text
*.8svn filter=lfs diff=lfs merge=lfs -text
*.9svn filter=lfs diff=lfs merge=lfs -text
*.dylib filter=lfs diff=lfs merge=lfs -text
*.exe filter=lfs diff=lfs merge=lfs -text
*.a filter=lfs diff=lfs merge=lfs -text
*.so filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.dll filter=lfs diff=lfs merge=lfs -text

View File

@ -18,7 +18,6 @@ This module allows you to develop new test cases for new features, or modify exi
developertest/
├── aw # Static libraries of the test framework
│ ├── cxx # C++ libraries
│ ├── java # Java libraries
│ └── python # Python libraries
├── config # Test framework configuration
│ ├── build_config.xml # Test case build configuration
@ -158,20 +157,17 @@ The Python environment is required.
```
- Configure the developers test module.
- Configure the developers test module in the configuration file **developertest/config/user\_config.xml**.
1. Modify basic configuration parameters of the test framework.
Configuration file: **developertest/config/user\_config.xml**
1. Modify basic configuration parameters.
\[build\] \# Set build parameters of the test case.
\[build\] \# Configure build parameters of the test case.
```
<build>
<example>false</example>
<version>false</version>
<testcase>true</testcase>
... ...
...
</build>
```
@ -192,7 +188,7 @@ The Python environment is required.
</device>
```
3. For devices that support serial port connection only, modify the configuration file as follows:
3. For devices that only support the serial port connection, modify the configuration file as follows:
\[board\_info\] \# Configure development board information.
@ -211,7 +207,7 @@ The Python environment is required.
>**board\_product**: target product. The default value is **ipcamera**.
>**build\_command**: command used for building the test version and test case. The default value is **hb build**.
\[device\] \# Configure the serial port information with the **"ipcamera"** attribute, including the COM port and baud rate. For example:
\[device\] \# Configure the serial port information with the **"ipcamera"** attribute, including the COM port and baud rate.
```
<device type="com" label="ipcamera">
@ -227,11 +223,8 @@ The Python environment is required.
```
- \(Optional\) Modify the configuration of the **developertest** module. If a test case has been compiled, specify the compilation output directory of the test case. In this case, the test platform will not recompile the test case.
Configuration file: **config/user\_config.xml**
1. Specify the output directory of the test case, that is, the compilation output directory between the **<test\_cases\>** tags. Example:
- \(Optional\) Modify the configuration file **config/user\_config.xml** of the **developertest** module. If a test case has been compiled, specify the compilation output directory of the test case. In this case, the test platform will not recompile the test case.
1. Specify the output directory of the test case, that is, the compilation output directory between the **<test\_cases\>** tags.
```
<test_cases>
@ -250,7 +243,7 @@ The Python environment is required.
- Prepare the test environment. \(Check that the test environment is ready if the tested device only supports serial port connection.\)
- The system image and file system have been burnt into a development board and are running properly on the development board. In system mode, for example, the device prompt **OHOS\#** is displayed during shell login.
- The system image and file system have been burnt into a development board and are running properly on the development board. For example, in system mode, device prompt **OHOS\#** is displayed during shell login, indicating that the system is running properly.
- The development host has been connected to the serial port of the development board and the network port.
- The IP addresses of the development host and development board are in the same network segment and can ping each other.
- An empty directory is created on the development host for mounting test cases through the NFS, and the NFS service is started properly.

View File

@ -18,7 +18,6 @@
developertest/
├── aw # 测试框架的静态库
│ ├── cxx # 支持C++
│ ├── java # 支持Java
│ └── python # 支持Python
├── config # 测试框架配置
│ ├── build_config.xml # 用例编译配置

0
aw/cxx/distributed/distributed.h Executable file → Normal file
View File

94
aw/cxx/distributed/distributed_agent.cpp Executable file → Normal file
View File

@ -79,7 +79,9 @@ int DistributedAgent::InitAgentServer()
int num = 1;
if (setsockopt(serverSockFd, SOL_SOCKET, SO_REUSEADDR, &num, sizeof(num)) != 0) {
return -1;
close(serverSockFd);
serverSockFd = -1;
return serverSockFd;
}
struct sockaddr_in addr;
@ -102,7 +104,9 @@ int DistributedAgent::InitAgentServer()
if (listen(serverSockFd, 1) < 0) {
HiLog::Error(DistributedAgent::LABEL, "%s agent listen error.\n", agentIpAddr_.c_str());
return -1;
close(serverSockFd);
serverSockFd = -1;
return serverSockFd;
}
HiLog::Info(DistributedAgent::LABEL, "listen %s .......", agentIpAddr_.c_str());
mpthCmdProcess_ = std::make_unique<std::thread>([=]() {
@ -125,6 +129,7 @@ int DistributedAgent::DoCmdServer(int serverSockFd)
sinSize = sizeof(struct sockaddr_in);
bzero(&clientAddr, sizeof(clientAddr));
receiveLen = DistributedAgent::RECE_LEN;
while (receiveLen > 0) {
HiLog::Info(DistributedAgent::LABEL, "wait client .......\n");
if ((clientSockFd = accept(serverSockFd, (struct sockaddr *)&clientAddr, &sinSize)) > 0) {
@ -158,24 +163,34 @@ int DistributedAgent::DoCmdServer(int serverSockFd)
pcline->len = ntohs(pcline->len);
HiLog::Info(DistributedAgent::LABEL, "test agent get message type:%d .\n", pcline->cmdTestType);
if (pcline->len > 0 && static_cast<unsigned long>(pcline->len) <= (MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN)) {
receiveLen = recv(clientSockFd_, pcline->alignmentCmd, pcline->len, 0);
receiveLen = recv(clientSockFd_, pcline->alignmentCmd, static_cast<size_t>(pcline->len), 0);
HiLog::Info(DistributedAgent::LABEL, "agent get message cmd=%s .\n", pcline->alignmentCmd);
switch (pcline->cmdTestType) {
case DST_COMMAND_CALL: {
int cmdLen = ntohs(*reinterpret_cast<int *>(pcline->alignmentCmd));
errno_t ret = EOK;
unsigned int cmdLen = ntohs(*reinterpret_cast<int *>(pcline->alignmentCmd));
rlen = sizeof(int);
// check cmdLen length < 100, copy command + args data ;
char *pAlignmentCmd = new char[cmdLen + 1];
memcpy_s(pAlignmentCmd, cmdLen + 1, pcline->alignmentCmd + rlen, cmdLen);
ret = memcpy_s(pAlignmentCmd, cmdLen + 1, pcline->alignmentCmd + rlen, cmdLen);
if (ret != EOK) {
delete []pAlignmentCmd;
return -1;
}
pAlignmentCmd[cmdLen] = '\0';
rlen += cmdLen + 1;
int eValueLen = ntohs(*reinterpret_cast<int *>(pcline->alignmentCmd + rlen));
unsigned int eValueLen = ntohs(*reinterpret_cast<int *>(pcline->alignmentCmd + rlen));
rlen += sizeof(int);
char *pszEValue = new char[eValueLen + 1];
memcpy_s(pszEValue, eValueLen + 1, pcline->alignmentCmd + rlen, eValueLen);
ret = memcpy_s(pszEValue, eValueLen + 1, pcline->alignmentCmd + rlen, eValueLen);
if (ret != EOK) {
delete []pAlignmentCmd;
delete []pszEValue;
return -1;
}
pszEValue[eValueLen] = '\0';
int nresult = OnProcessCmd(pAlignmentCmd, cmdLen, pszEValue, eValueLen);
memset_s(returnValue, MAX_BUFF_LEN, 0, MAX_BUFF_LEN);
(void)memset_s(returnValue, MAX_BUFF_LEN, 0, MAX_BUFF_LEN);
auto pclinereturn = reinterpret_cast<DistributedMsg *>(returnValue);
pclinereturn->no = pcline->no;
pclinereturn->cmdTestType = htons(DST_COMMAND_CALL);
@ -184,14 +199,14 @@ int DistributedAgent::DoCmdServer(int serverSockFd)
pclinereturn->len = htons(rlen);
HiLog::Info(DistributedAgent::LABEL, "agent get message :%s .\n",
pclinereturn->alignmentCmd);
send(clientSockFd_, pclinereturn, rlen + DST_COMMAND_HEAD_LEN, 0);
send(clientSockFd_, pclinereturn, static_cast<size_t>(rlen + DST_COMMAND_HEAD_LEN), 0);
delete []pAlignmentCmd;
delete []pszEValue;
break;
}
case DST_COMMAND_MSG: {
int nresult = 0;
memset_s(returnValue, MAX_BUFF_LEN, 0, MAX_BUFF_LEN);
(void)memset_s(returnValue, MAX_BUFF_LEN, 0, MAX_BUFF_LEN);
auto pclinereturn = reinterpret_cast<DistributedMsg *>(returnValue);
pclinereturn->no = pcline->no;
pclinereturn->cmdTestType = htons(DST_COMMAND_MSG);
@ -199,12 +214,13 @@ int DistributedAgent::DoCmdServer(int serverSockFd)
std::string resultcmd = pclinereturn->alignmentCmd;
nresult = OnProcessMsg(pcline->alignmentCmd, pcline->len, resultcmd, pclinereturn->len);
if (resultcmd == "") {
strcpy_s(pclinereturn->alignmentCmd, pclinereturn->len, "agent return message");
} else {
strcpy_s(pclinereturn->alignmentCmd, pclinereturn->len, resultcmd.c_str());
resultcmd = "agent return message";
}
if (strcpy_s(pclinereturn->alignmentCmd, pclinereturn->len, resultcmd.c_str()) != EOK) {
return -1;
}
pclinereturn->len = htons(nresult);
send(clientSockFd_, pclinereturn, nresult + DST_COMMAND_HEAD_LEN, 0);
send(clientSockFd_, pclinereturn, static_cast<size_t>(nresult + DST_COMMAND_HEAD_LEN), 0);
break;
}
case DST_COMMAND_NOTIFY: {
@ -227,14 +243,13 @@ int DistributedAgent::DoCmdServer(int serverSockFd)
void DistributedAgent::OnNotifyImf(DistributedMsg *pcline)
{
int nresult = 0;
char alignmentCmd[DistributedAgent::CMD_LENGTH];
char szMsg[MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH];
int cmdNo = 0;
memset_s(alignmentCmd, DistributedAgent::CMD_LENGTH, 0, DistributedAgent::CMD_LENGTH);
memset_s(szMsg,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH, 0,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH);
(void)memset_s(alignmentCmd, DistributedAgent::CMD_LENGTH, 0, DistributedAgent::CMD_LENGTH);
(void)memset_s(szMsg,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH, 0,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH);
for (cmdNo = 0; cmdNo < DistributedAgent::CMD_LENGTH; cmdNo++) {
if (pcline->alignmentCmd[cmdNo] == ':') {
break;
@ -243,10 +258,17 @@ void DistributedAgent::OnNotifyImf(DistributedMsg *pcline)
if (cmdNo >= DistributedAgent::CMD_LENGTH) {
HiLog::Error(DistributedAgent::LABEL, "error command.\n");
} else {
memcpy_s(alignmentCmd, DistributedAgent::CMD_LENGTH, pcline->alignmentCmd, cmdNo);
memcpy_s(szMsg, MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH,
pcline->alignmentCmd + cmdNo + 1, pcline->len - cmdNo - 1);
nresult = OnNotify(alignmentCmd, szMsg, pcline->len - cmdNo);
errno_t ret = EOK;
ret = memcpy_s(alignmentCmd, DistributedAgent::CMD_LENGTH, pcline->alignmentCmd, cmdNo);
if (ret != EOK) {
return;
}
ret = memcpy_s(szMsg, MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH,
pcline->alignmentCmd + cmdNo + 1, pcline->len - cmdNo - 1);
if (ret != EOK) {
return;
}
OnNotify(alignmentCmd, szMsg, pcline->len - cmdNo);
}
}
@ -288,10 +310,11 @@ int DistributedAgent::OnProcessCmd(const std::string &strCommand, int cmdLen,
char alignmentCmd[DistributedAgent::CMD_LENGTH];
char szArgs[MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH];
int cmdNo = 0;
memset_s(alignmentCmd, DistributedAgent::CMD_LENGTH, 0, DistributedAgent::CMD_LENGTH);
memset_s(szArgs,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH, 0,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH);
(void)memset_s(alignmentCmd, DistributedAgent::CMD_LENGTH, 0, DistributedAgent::CMD_LENGTH);
(void)memset_s(szArgs,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH, 0,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH);
for (cmdNo = 0; cmdNo < DistributedAgent::CMD_LENGTH; cmdNo++) {
if (strCommand[cmdNo] == ':') {
break;
@ -302,9 +325,20 @@ int DistributedAgent::OnProcessCmd(const std::string &strCommand, int cmdLen,
nresult = -1;
return nresult;
}
memcpy_s(alignmentCmd, DistributedAgent::CMD_LENGTH, strCommand.c_str(), cmdNo);
memcpy_s(szArgs, MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH,
strCommand.c_str() + cmdNo + 1, cmdLen - cmdNo - 1);
errno_t ret = EOK;
ret = memcpy_s(alignmentCmd, DistributedAgent::CMD_LENGTH, strCommand.c_str(), cmdNo);
if (ret != EOK) {
return -1;
}
ret = memcpy_s(szArgs,
MAX_BUFF_LEN / DistributedAgent::HALF_NUM - DistributedAgent::CMD_LENGTH,
strCommand.c_str() + cmdNo + 1,
cmdLen - cmdNo - 1);
if (ret != EOK) {
return -1;
}
nresult = OnProcessCmd(alignmentCmd, cmdNo, szArgs, cmdLen - cmdNo, strExpectValue, expectValueLen);
return nresult;
}

0
aw/cxx/distributed/distributed_agent.h Executable file → Normal file
View File

0
aw/cxx/distributed/distributed_cfg.cpp Executable file → Normal file
View File

0
aw/cxx/distributed/distributed_cfg.h Executable file → Normal file
View File

45
aw/cxx/distributed/distributed_major.cpp Executable file → Normal file
View File

@ -44,11 +44,11 @@ namespace {
const int CMD_LENGTH = 50;
}
DistributeTestEnvironment::DistributeTestEnvironment()
DistributeTestEnvironment::DistributeTestEnvironment() : serverPort_(DEFAULT_AGENT_PORT)
{
}
DistributeTestEnvironment::DistributeTestEnvironment(std::string cfgInfo)
DistributeTestEnvironment::DistributeTestEnvironment(std::string cfgInfo) : serverPort_(DEFAULT_AGENT_PORT)
{
Init(cfgInfo);
}
@ -60,8 +60,8 @@ void DistributeTestEnvironment::Init(std::string fileName)
if (!clientCfg_.GetCfgVal("agentlist", iplist)) {
return;
}
size_t posend;
int pos = 0;
std::string::size_type posend = 0;
std::string::size_type pos = 0;
do {
std::string ipaddr;
posend = iplist.find(",", pos);
@ -71,6 +71,9 @@ void DistributeTestEnvironment::Init(std::string fileName)
ipaddr = iplist.substr(pos);
}
AddClient(ipaddr);
if (posend >= iplist.length()) {
break;
}
pos = posend + 1;
} while (posend != std::string::npos);
std::string strPort;
@ -185,7 +188,7 @@ bool DistributeTestEnvironment::SendToAgent(size_t devNo, int cmdType, void *pst
pCmdTest->no = globalCommandNo;
pCmdTest->cmdTestType = htons(cmdType);
pCmdTest->len = htons(len);
int rlen = send(clientList_[devNo].fd, pCmdTest, len + DST_COMMAND_HEAD_LEN, 0);
int rlen = send(clientList_[devNo].fd, pCmdTest, static_cast<size_t>(len + DST_COMMAND_HEAD_LEN), 0);
if (rlen <= 0) {
HiLog::Error(LABEL, "agent socket is closed.");
return breturn;
@ -201,6 +204,10 @@ bool DistributeTestEnvironment::SendToAgent(size_t devNo, int cmdType, void *pst
auto pCmdTest = reinterpret_cast<DistributedMsg *>(szrbuf);
pCmdTest->cmdTestType = ntohs(pCmdTest->cmdTestType);
pCmdTest->len = ntohs(pCmdTest->len);
if (pCmdTest->len <= 0) {
times--;
continue;
}
recv(clientList_[devNo].fd, pCmdTest->alignmentCmd, pCmdTest->len, 0);
HiLog::Info(LABEL, "recv agent data : No.%d command type :%d length :%d",
pCmdTest->no, pCmdTest->cmdTestType, pCmdTest->len);
@ -243,7 +250,8 @@ bool DistributeTestEnvironment::RunTestCmd(size_t devNo, const std::string &strC
char szbuf[MAX_BUFF_LEN];
bool breturn = false;
size_t lenptr = 0;
memset_s(szbuf, MAX_BUFF_LEN, 0, MAX_BUFF_LEN);
errno_t ret = EOK;
(void)memset_s(szbuf, MAX_BUFF_LEN, 0, MAX_BUFF_LEN);
// add 2 '\0'
size_t rlen = cmdLen + expectValueLen + DST_COMMAND_HEAD_LEN + sizeof(int)*HALF_BUF_LEN + HALF_BUF_LEN;
@ -257,13 +265,19 @@ bool DistributeTestEnvironment::RunTestCmd(size_t devNo, const std::string &strC
lenptr = 0;
*reinterpret_cast<int *>(pCmdTest->alignmentCmd + lenptr) = htons(cmdLen);
lenptr += sizeof(int);
memcpy_s(pCmdTest->alignmentCmd + lenptr, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN - lenptr,
ret = memcpy_s(pCmdTest->alignmentCmd + lenptr, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN - lenptr,
strCommand.c_str(), cmdLen);
if (ret != EOK) {
return breturn;
}
lenptr += cmdLen + 1;
*reinterpret_cast<int *>(pCmdTest->alignmentCmd + lenptr) = htons(expectValueLen);
lenptr += sizeof(int);
memcpy_s(pCmdTest->alignmentCmd + lenptr, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN - lenptr,
ret = memcpy_s(pCmdTest->alignmentCmd + lenptr, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN - lenptr,
strExpectValue.c_str(), expectValueLen);
if (ret != EOK) {
return breturn;
}
lenptr += expectValueLen + 1;
pCmdTest->len = lenptr;
breturn = SendToAgent(devNo, DST_COMMAND_CALL, pCmdTest, pCmdTest->len, onProcessReturn);
@ -281,7 +295,10 @@ bool DistributeTestEnvironment::SendMessage(size_t devNo, const std::string &str
char szbuf[MAX_BUFF_LEN] = {0};
auto pCmdTest = reinterpret_cast<DistributedMsg *>(szbuf);
pCmdTest->cmdTestType = DST_COMMAND_MSG;
memcpy_s(pCmdTest->alignmentCmd, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN, strMsg.c_str(), msgLen);
errno_t ret = memcpy_s(pCmdTest->alignmentCmd, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN, strMsg.c_str(), msgLen);
if (ret != EOK) {
return breturn;
}
pCmdTest->len = msgLen;
breturn = SendToAgent(devNo, DST_COMMAND_MSG, pCmdTest, msgLen, onProcessReturnMsg);
} else {
@ -292,12 +309,20 @@ bool DistributeTestEnvironment::SendMessage(size_t devNo, const std::string &str
bool DistributeTestEnvironment::Notify(size_t devNo, const std::string &strMsg, int msgLen)
{
int dstMax = MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN;
if (msgLen < 0 || msgLen >= dstMax) {
return false;
}
bool breturn = false;
if ((msgLen + DST_COMMAND_HEAD_LEN) <= MAX_BUFF_LEN) {
char szbuf[MAX_BUFF_LEN] = {0};
auto pCmdTest = reinterpret_cast<DistributedMsg *>(szbuf);
pCmdTest->cmdTestType = DST_COMMAND_NOTIFY;
memcpy_s(pCmdTest->alignmentCmd, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN, strMsg.c_str(), msgLen);
errno_t ret = memcpy_s(pCmdTest->alignmentCmd, dstMax, strMsg.c_str(), msgLen);
if (ret != EOK) {
return breturn;
}
pCmdTest->alignmentCmd[msgLen] = 0;
pCmdTest->len = msgLen;
breturn = SendToAgent(devNo, DST_COMMAND_NOTIFY, pCmdTest, msgLen, nullptr);

0
aw/cxx/distributed/distributed_major.h Executable file → Normal file
View File

0
aw/cxx/distributed/utils/csv_transform_xml.h Executable file → Normal file
View File

View File

@ -27,6 +27,6 @@ ohos_static_library("performance_test_static") {
"//third_party/googletest:gtest",
"//utils/native/base:utils",
]
aosp_deps = [ "shared_library:libxml2" ]
public_deps = [ "//third_party/libxml2:libxml2" ]
public_configs = [":performance_test_config"]
}

0
aw/cxx/hwext/perf.cpp Executable file → Normal file
View File

0
aw/cxx/hwext/perf.h Executable file → Normal file
View File

View File

@ -1,38 +0,0 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/config/ohos/rules.gni")
java_library("distribute_testfwk_java") {
java_files = [
"./src/ohos/junit/distribute/CommonUtil.java",
"./src/ohos/junit/distribute/DeviceEnum.java",
"./src/ohos/junit/distribute/DistributeConsts.java",
"./src/ohos/junit/distribute/DistributeCmd.java",
"./src/ohos/junit/distribute/DistributeCfg.java",
"./src/ohos/junit/distribute/ICallBack.java",
"./src/ohos/junit/distribute/ISocketObserver.java",
"./src/ohos/junit/distribute/ISocketObservable.java",
"./src/ohos/junit/distribute/ClientObserver.java",
"./src/ohos/junit/distribute/DistributeMajor.java",
"./src/ohos/junit/distribute/DistributeAgent.java",
]
final_jar_path = "$root_out_dir/test_platform/libs/distribute_testfwk.jar"
deps = [
"//third_party/easymock:easymock_java",
"//third_party/junit:junit_java",
]
}
group("java_test_tools") {
deps = [ ":distribute_testfwk_java" ]
}

View File

@ -1,280 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
import ohos.junit.distribute.DistributeConsts.DistributeDataType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* client for distribute test framework
*/
public class ClientObserver implements ISocketObserver {
private static final String LOG_CLIENT_NAME = "ClientObserver";
private Socket clientSocket = null;
private PrintWriter printWriter = null;
private BufferedReader bufferedReader = null;
private boolean isConnect = false;
private String ipAddress = DistributeConsts.EMPTY_STR;
private int port = 0;
private boolean isStart = false;
private int tryTime = 0;
/**
* construct client
*
* @param ipAddress ip
* @param port port
*/
public ClientObserver(String ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
/**
* send message
*
* @apiNote send message
* @param message message
* @param expectValue expected value
* @return result code
*/
public int sendMessage(String message, String expectValue) {
if ((message.length() + expectValue.length()) < DistributeConsts.MAX_DATA_LENGTH) {
return sendMsgToAgent(
new DistributeCmd(DistributeConsts.DistributeDataType.DATA_MSG, message, "", expectValue), null);
}
return DistributeConsts.FAILED_CODE;
}
/**
* send message contains callback
*
* @apiNote send message contains callback
*
* @param message message
* @param expectValue expected value
* @param callback callback
* @return result code
*/
public int sendMessage(String message, String expectValue, ICallBack callback) {
if ((message.length() + expectValue.length()) < DistributeConsts.MAX_DATA_LENGTH) {
return sendMsgToAgent(
new DistributeCmd(DistributeConsts.DistributeDataType.DATA_MSG, message, "", expectValue), callback);
}
return DistributeConsts.FAILED_CODE;
}
/**
* send command to agent
*
* @apiNote send command to agent
*
* @param command command
* @param cmdParam param
* @param expectValue expected value
* @return result code
*/
public int runCommandOnAgent(String command, String cmdParam, String expectValue) {
return sendMsgToAgent(
new DistributeCmd(DistributeConsts.DistributeDataType.DATA_CMD, command, cmdParam, expectValue), null);
}
/**
* send command to agent contains callback
*
* @apiNote send command to agent contains callback
*
* @param command command
* @param cmdParam param
* @param expectValue expected value
* @param callback callback
* @return result code
*/
public int runCommandOnAgent(String command, String cmdParam, String expectValue, ICallBack callback) {
return sendMsgToAgent(
new DistributeCmd(DistributeConsts.DistributeDataType.DATA_CMD, command, cmdParam, expectValue), callback);
}
private int sendMsgToAgent(DistributeCmd formatCmd, ICallBack callback) {
if (formatCmd != null) {
try {
this.printWriter.println(CommonUtil.getInstance().serializeToStr(formatCmd));
this.printWriter.flush();
} catch (IOException e) {
CommonUtil.getInstance().info(LOG_CLIENT_NAME,
"sendMsgToAgent serializeToStr failed." + e.getMessage());
return DistributeConsts.FAILED_CODE;
}
Object readObj = null;
String info = null;
try {
info = bufferedReader.readLine();
while (this.isConnect && info != null) {
readObj = CommonUtil.getInstance().deserializeToObj(info);
if (readObj instanceof DistributeCmd) {
DistributeCmd result = (DistributeCmd) readObj;
return commonHandleCmd(formatCmd, result, callback);
}
}
} catch (IOException e) {
CommonUtil.getInstance().info(LOG_CLIENT_NAME, "sendMsgToAgent IOException." + e.getMessage());
}
}
return DistributeConsts.FAILED_CODE;
}
private int commonHandleCmd(DistributeCmd sourceCmd, DistributeCmd returnCmd, ICallBack callback) {
if (callback != null) {
return callback.processDistCmd(returnCmd);
}
if (returnCmd == null) {
return DistributeConsts.FAILED_CODE;
}
if (!returnCmd.getExpectValue().isEmpty()) {
if (sourceCmd.getExpectValue().equals(returnCmd.getExpectValue())) {
return 0;
}
}
return DistributeConsts.FAILED_CODE;
}
@Override
public boolean initEnvironment() {
try {
this.clientSocket = new Socket(this.ipAddress, this.port);
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
this.printWriter = new PrintWriter(new OutputStreamWriter(this.clientSocket.getOutputStream()));
} catch (UnknownHostException e) {
CommonUtil.getInstance().info(LOG_CLIENT_NAME, "client socket UnknownHostException." + e.getMessage());
return false;
} catch (IOException e) {
CommonUtil.getInstance().info(LOG_CLIENT_NAME, "client socket IOException." + e.getMessage());
return false;
}
this.isConnect = true;
return true;
}
@Override
public void updateSocket(String command) {
switch (String.valueOf(command)) {
case DistributeConsts.START_CMD:
startCommand();
break;
case DistributeConsts.STOP_CMD:
releaseEnvironment();
break;
default:
CommonUtil.getInstance().info(LOG_CLIENT_NAME, "command not found.");
}
}
private void startCommand() {
if (!isStart) {
isStart = true;
while (!initEnvironment()) {
if (this.tryTime < DistributeConsts.RETRY_TIME) {
try {
Thread.sleep(DistributeConsts.WAIT_TIME);
} catch (InterruptedException e1) {
CommonUtil.getInstance().info(LOG_CLIENT_NAME,
"client socket sleep InterruptedException." + e1.getMessage());
}
this.tryTime++;
} else {
break;
}
}
}
}
@Override
public void releaseEnvironment() {
sendMsgToAgent(new DistributeCmd(DistributeDataType.DATA_NOTIFY, DistributeConsts.STOP_CMD), null);
if (this.clientSocket != null) {
try {
this.clientSocket.close();
} catch (IOException e) {
CommonUtil.getInstance().info(LOG_CLIENT_NAME, "close client socket failed." + e.getMessage());
}
}
if (this.bufferedReader != null) {
try {
this.bufferedReader.close();
} catch (IOException e) {
CommonUtil.getInstance().info(LOG_CLIENT_NAME, "close client outputStream failed." + e.getMessage());
}
}
if (this.printWriter != null) {
this.printWriter.close();
}
}
public boolean isConnect() {
return isConnect;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isStart() {
return isStart;
}
public void setStart(boolean isStarted) {
this.isStart = isStarted;
}
public int getTryTime() {
return tryTime;
}
public void setTryTime(int tryTime) {
this.tryTime = tryTime;
}
public void setConnect(boolean isConnected) {
this.isConnect = isConnected;
}
}

View File

@ -1,167 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* common method
*/
public class CommonUtil {
private static final String SEP_CHAR = ": ";
private static final String LOG_UTIL_NAME = "CommonUtil";
private String rootPath = "";
/**
* singleton
*/
private static class SingletonHolder {
private static final CommonUtil INSTANCE = new CommonUtil();
}
private CommonUtil() {
}
/**
* util instance
*
* @return singleton
*/
public static CommonUtil getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* get current workspace path
*
* @apiNote get current workspace path
*
* @return current workspace path
*/
public String getCurrentPath() {
if (rootPath.isEmpty()) {
File curFile = new File("");
try {
rootPath = curFile.getCanonicalPath();
} catch (IOException e) {
CommonUtil.getInstance().info(LOG_UTIL_NAME, "get rootpath failed." + e.getMessage());
}
}
return rootPath;
}
/**
* whether is file and exist
*
* @apiNote whether file is and exists
*
* @param fileObj input object
* @return file and exist-true,else-false
*/
public boolean isFileAndExist(File fileObj) {
return fileObj.isFile() && fileObj.exists();
}
/**
* whether string is null or empty
*
* @apiNote whether string is null or empty
*
* @param input input string
* @return string is null or empty-true,else-false
*/
public boolean isNullOrEmpty(String input) {
if (input == null || input.isEmpty()) {
return true;
}
return false;
}
/**
* start thread
*
* @apiNote start thread
*
* @param runnable thread
*/
public void startThread(Runnable runnable) {
Thread agentThread = new Thread(runnable);
agentThread.currentThread().setName("test_agent");
agentThread.start();
agentThread.setUncaughtExceptionHandler((Thread thread, Throwable exception) -> {
System.out.println(thread.getName() + "_" + exception.getMessage());
CommonUtil.getInstance().info(
LOG_UTIL_NAME, thread.getName() + "_" + exception.getMessage());
});
}
/**
* serialize object to string,only ISO-8859-1 is available
*
* @param object source object
* @return serialize string
* @throws IOException serial exception
*/
public String serializeToStr(Object object) throws IOException {
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ObjectOutputStream objOutput = new ObjectOutputStream(byteOutput);
objOutput.writeObject(object);
String returnStr = byteOutput.toString("ISO-8859-1");
byteOutput.close();
objOutput.close();
return returnStr;
}
/**
* deserialize string to object, only ISO-8859-1 is available
*
* @param inputStr input string
* @return target object
* @throws IOException serial exception
*/
public Object deserializeToObj(String inputStr) throws IOException {
if (isNullOrEmpty(inputStr)) {
return "";
}
ByteArrayInputStream byteInput = new ByteArrayInputStream(inputStr.getBytes("ISO-8859-1"));
ObjectInputStream objInput = new ObjectInputStream(byteInput);
Object object = null;
try {
object = objInput.readObject();
} catch (ClassNotFoundException e) {
CommonUtil.getInstance().info(LOG_UTIL_NAME, "ClassNotFoundException." + e.getMessage());
}
byteInput.close();
objInput.close();
return object;
}
/**
* print info level log
*
* @param name current class or function name
* @param content content string
*/
public final void info(String name, String content) {
System.out.println(name + SEP_CHAR + content);
}
}

View File

@ -1,76 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
/**
* device enum
*/
public enum DeviceEnum {
/**
* first agent device
*/
DEVICE_FIRST(1),
/**
* second agent device
*/
DEVICE_SECOND(2),
/**
* third agent device
*/
DEVICE_THIRD(3),
/**
* fourth agent device
*/
DEVICE_FOURTH(4),
/**
* fifth agent device
*/
DEVICE_FIFTH(5),
/**
* sixth agent device
*/
DEVICE_SIXTH(6),
/**
* seventh agent device
*/
DEVICE_SEVENTH(7),
/**
* eighth agent device
*/
DEVICE_EIGHTH(8),
/**
* ninth agent device
*/
DEVICE_NINTH(9);
private final int value;
DeviceEnum(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}

View File

@ -1,366 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
import ohos.junit.distribute.DistributeConsts.DistributeDataType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
/**
* distribute test agent
*/
public abstract class DistributeAgent {
private static final String LOG_AGENT_NAME = "DistributeAgent";
/**
* default construct
*/
public DistributeAgent() {
}
/**
* test agent initialization, implemented by subclasses
*/
public abstract void setUpDistribute();
/**
* test agent environment cleanup, implemented by subclasses
*/
public abstract void tearDownDistribute();
/**
* process command from major device to agent device, implemented by subclasses
*
* @param command command to send agent device
* @param cmdParam command param
* @param expectValue expect return value
* @return DistributeCmd object after processing the command
*/
public abstract DistributeCmd onProcessCmd(String command, String cmdParam,
String expectValue);
/**
* process message from major device to agent device, implemented by subclasses
*
* @param message command to send agent device
* @return DistributeCmd object after processing the command
*/
public abstract DistributeCmd onProcessMsg(String message);
/**
* start distribute test agent
*
* @apiNote start distribute test agent
*
* @return success-true,failed-false
*/
public boolean startDistributeAgent() {
DistributeCfg distributeCfg = new DistributeCfg();
distributeCfg.readDistributeCfg("agent.desc");
if (distributeCfg != null) {
for (String ipAddress : distributeCfg.getIpList()) {
SocketServer socketServer = new SocketServer(ipAddress,
distributeCfg.getPort());
CommonUtil.getInstance().startThread(socketServer);
}
}
return false;
}
private DistributeCmd onProcessMessage(String message) {
return onProcessMsg(message);
}
private DistributeCmd onProcessCommand(String command, String cmdParam,
String expectValue) {
return onProcessCmd(command, cmdParam, expectValue);
}
private DistributeCmd onNotify(String notify) {
return new DistributeCmd(DistributeDataType.DATA_NOTIFY,
DistributeConsts.STOP_CMD);
}
private DistributeCmd processDistributeCmd(DistributeCmd distributeCmd) {
if (distributeCmd == null) {
return new DistributeCmd(DistributeDataType.DATA_MSG,
DistributeConsts.EMPTY_STR);
} else {
String cmdType = distributeCmd.getCmdType().toString();
if (DistributeDataType.DATA_CMD.toString().equals(cmdType)) {
return onProcessCommand(distributeCmd.getCommand(),
distributeCmd.getParam(), distributeCmd.getExpectValue());
} else if (DistributeDataType.DATA_MSG.toString().equals(cmdType)) {
return onProcessMessage(distributeCmd.getCommand());
} else if (DistributeDataType.DATA_NOTIFY.toString().equals(cmdType)) {
return onNotify(distributeCmd.getCommand());
} else {
CommonUtil.getInstance().info(LOG_AGENT_NAME, "unknown command.");
return new DistributeCmd(DistributeDataType.DATA_MSG,
DistributeConsts.EMPTY_STR);
}
}
}
/**
* agent socket
*/
class SocketServer implements Runnable {
private String ipAddress = DistributeConsts.EMPTY_STR;
private int port = 0;
private ServerSocket serverSocket = null;
private Socket agentSocket = null;
private PrintWriter printWriter = null;
private BufferedReader bufferedReader = null;
private boolean isStart = false;
private volatile boolean isTimeout = false;
private volatile long startTime = 0L;
private Timer checkTimeout = null;
private CheckTimeout checkTimeoutTask = null;
/**
* agent socket
*
* @param ipAddress ip
* @param port port
*/
SocketServer(String ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
@Override
public void run() {
setUpDistribute();
initSocketAgent();
Object receiveObj = null;
String info = "";
while (isStart) {
if (isTimeout || (printWriter == null)) {
isStart = false;
break;
}
try {
info = bufferedReader.readLine();
if (info == null) {
break;
}
startTime = System.currentTimeMillis();
receiveObj = CommonUtil.getInstance().deserializeToObj(info);
if (receiveObj == null) {
continue;
}
if (receiveMessage(receiveObj)) {
continue;
} else {
break;
}
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"bufferedReader readLine failed." + e.getMessage());
isStart = false;
break;
}
}
receiveObj = null;
releaseResource();
tearDownDistribute();
}
private boolean receiveMessage(Object receiveObj) {
DistributeCmd tempCmd = null;
if (receiveObj instanceof DistributeCmd) {
tempCmd = processDistributeCmd((DistributeCmd) receiveObj);
if (tempCmd != null) {
return dealReceiveMsg(tempCmd);
} else {
handleNullCmd();
}
}
return true;
}
private void handleNullCmd() {
try {
printWriter.println(CommonUtil.getInstance()
.serializeToStr(new DistributeCmd(
DistributeDataType.DATA_NOTIFY,
DistributeConsts.EMPTY_STR,
DistributeConsts.EMPTY_STR,
DistributeConsts.DEFAULT_RESULT)));
printWriter.flush();
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"serializeToStr failed." + e.getMessage());
}
}
private boolean dealReceiveMsg(DistributeCmd tempCmd) {
if (tempCmd.getCmdType() == DistributeDataType.DATA_NOTIFY) {
if (DistributeConsts.STOP_CMD.equals(tempCmd.getCommand())) {
return false;
}
} else {
try {
printWriter.println(CommonUtil.getInstance()
.serializeToStr(tempCmd));
printWriter.flush();
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"serializeToStr failed." + e.getMessage());
}
}
return true;
}
private void initSocketAgent() {
try {
checkTimeout = new Timer();
checkTimeoutTask = new CheckTimeout();
checkTimeout.schedule(new CheckTimeout(),
DistributeConsts.WAIT_TIME, DistributeConsts.WAIT_TIME);
} catch (Throwable e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"create check timeout thread failed." + e.getMessage());
}
startTime = System.currentTimeMillis();
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(this.ipAddress,
this.port));
serverSocket.setSoTimeout(DistributeConsts.TIME_OUT);
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"Get ServerSocket failed." + e.getMessage());
isStart = false;
return;
}
try {
agentSocket = serverSocket.accept();
agentSocket.setSoTimeout(DistributeConsts.TIME_OUT);
printWriter = new PrintWriter(new OutputStreamWriter(
agentSocket.getOutputStream()));
InputStreamReader inputStreamReader = new InputStreamReader(agentSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"Get output or input stream failed." + e.getMessage());
isStart = false;
return;
}
isStart = true;
}
private void releaseResource() {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"close objInputStream failed." + e.getMessage());
}
}
if (printWriter != null) {
printWriter.close();
}
if (checkTimeoutTask != null) {
try {
agentSocket.close();
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"close agentSocket failed." + e.getMessage());
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
CommonUtil.getInstance()
.info(LOG_AGENT_NAME,
"close serverSocket failed." + e.getMessage());
}
}
if (checkTimeout != null) {
checkTimeout.cancel();
}
if (checkTimeoutTask != null) {
checkTimeoutTask.cancel();
}
}
/**
* check timeout
*/
class CheckTimeout extends TimerTask {
@Override
public void run() {
if ((System.currentTimeMillis() - startTime) > DistributeConsts.TIME_OUT) {
isTimeout = true;
releaseResource();
}
}
}
}
}

View File

@ -1,127 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* distribute configuration
*/
public class DistributeCfg {
private static final String LOG_CFG_NAME = "DistributeCfg";
/**
* agent port
*/
private int port = 0;
/**
* agent ipAddress
*/
private List<String> ipList = new ArrayList<String>();
/**
* create configuration
*
*/
public DistributeCfg() {
}
public List<String> getIpList() {
return this.ipList;
}
/**
* add ipAddress
*
* @apiNote add ipAddress
*
* @param ipAddress ipAddress
*/
public void addIpAddress(String ipAddress) {
if (ipAddress == null || ipAddress.isEmpty()) {
CommonUtil.getInstance().info(LOG_CFG_NAME, "ipAddress is null.");
} else {
this.ipList.add(ipAddress);
}
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
/**
* read distribute configuration info
*
* @param fileName configuration
*/
public void readDistributeCfg(String fileName) {
if (fileName == null || fileName.isEmpty()) {
CommonUtil.getInstance().info(LOG_CFG_NAME, "configuration file not exists.");
} else {
File cfgFile = new File(CommonUtil.getInstance().getCurrentPath() + File.separator + fileName);
CommonUtil.getInstance().info(LOG_CFG_NAME, "cfg path=" + cfgFile.getAbsolutePath());
if (CommonUtil.getInstance().isFileAndExist(cfgFile)) {
try (InputStreamReader reader =
new InputStreamReader(new FileInputStream(cfgFile), DistributeConsts.DEFAULT_ENCODING)) {
try (BufferedReader bufferReader = new BufferedReader(reader)) {
handleConfigInfo(bufferReader);
} catch (IOException e) {
CommonUtil.getInstance().info(LOG_CFG_NAME, "read configuration failed." + e.getMessage());
}
} catch (IOException e1) {
CommonUtil.getInstance().info(LOG_CFG_NAME, "read configuration failed." + e1.getMessage());
}
}
}
}
private void handleConfigInfo(BufferedReader bufferReader) throws IOException {
String cfgInfo = null;
while ((cfgInfo = bufferReader.readLine()) != null) {
if (cfgInfo.contains(DistributeConsts.COLON_SIGLE)) {
String[] readInfo = cfgInfo.split(DistributeConsts.COLON_SIGLE);
switch (readInfo[0]) {
case DistributeConsts.IP_CFG_KEY:
if (readInfo[1].contains(DistributeConsts.DOT_SIGLE)) {
String[] ipAddressList = readInfo[1].split(DistributeConsts.DOT_SIGLE);
for (String ipAddress : ipAddressList) {
this.ipList.add(ipAddress);
}
} else {
this.ipList.add(readInfo[1]);
}
break;
case DistributeConsts.PORT_CFG_KEY:
this.port = Integer.valueOf(readInfo[1]);
break;
default:
CommonUtil.getInstance().info(LOG_CFG_NAME, "error configuration.");
}
}
}
}
}

View File

@ -1,114 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
import ohos.junit.distribute.DistributeConsts.DistributeDataType;
import java.io.Serializable;
/**
* command structure
*/
public class DistributeCmd implements Serializable {
/**
* serial num
*/
private static final long serialVersionUID = 1L;
/**
* command type
*/
private DistributeDataType cmdType = DistributeDataType.DATA_NOTIFY;
/**
* command between client and server
*/
private String command = "";
/**
* command params
*/
private String param = "";
/**
* expect return value
*/
private String expectValue = "";
/**
* create distribute command
*
* @param distributeDataType command type
* @param command command
*/
public DistributeCmd(DistributeDataType distributeDataType, String command) {
this.cmdType = distributeDataType;
this.command = command;
}
/**
* create distribute command
*
* @param cmdType command type
* @param command command
* @param param param
* @param expectValue return value
*/
public DistributeCmd(DistributeDataType cmdType, String command, String param, String expectValue) {
this.cmdType = cmdType;
this.command = command;
this.param = param;
this.expectValue = expectValue;
}
public DistributeDataType getCmdType() {
return cmdType;
}
public void setCmdType(DistributeDataType cmdType) {
this.cmdType = cmdType;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public String getExpectValue() {
return expectValue;
}
public void setExpectValue(String expectValue) {
this.expectValue = expectValue;
}
@Override
public String toString() {
return "DistributeCmd{cmdType=" + cmdType + ", command=" + command + ", param=" + param + ", expectValue="
+ expectValue + "}";
}
}

View File

@ -1,139 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
/**
* distribute constant
*/
public class DistributeConsts {
/**
* default encode format
*/
public static final String DEFAULT_ENCODING = "UTF-8";
/**
* separator for ipAddress
*/
public static final String DOT_SIGLE = ",";
/**
* separator for ipAddress and port
*/
public static final String COLON_SIGLE = ":";
/**
* device ipAddress list
*/
public static final String IP_CFG_KEY = "agentlist";
/**
* device ports
*/
public static final String PORT_CFG_KEY = "agentport";
/**
* empty string
*/
public static final String EMPTY_STR = "";
/**
* start command for testing
*/
public static final String START_CMD = "start";
/**
* stop command for testing
*/
public static final String STOP_CMD = "stop";
/**
* maximum message length
*/
public static final int MAX_DATA_LENGTH = 1024;
/**
* failed code
*/
public static final int FAILED_CODE = -1;
/**
* retry times
*/
public static final int RETRY_TIME = 3;
/**
* time for once waiting
*/
public static final int WAIT_TIME = 3000;
/**
* timeout times
*/
public static final int TIMEOUT_TIME = 60;
/**
* connection timeout between client and server
*/
public static final int TIME_OUT = WAIT_TIME * TIMEOUT_TIME;
/**
* default return value
*/
public static final String DEFAULT_RESULT = "SUCCESS";
/**
* data type enum
*/
public enum DistributeDataType {
/**
* send command from client to server
*/
DATA_CMD("DATA_CMD"),
/**
* send message string
*/
DATA_MSG("DATA_MSG"),
/**
* send notify
*/
DATA_NOTIFY("DATA_NOTIFY");
private String value = "";
/**
* default type name
*
* @param name data type name
*/
DistributeDataType(String name) {
this.value = name;
}
/**
* toString
*
* @return string
*/
public String toString() {
return this.value;
}
}
private DistributeConsts() {
}
}

View File

@ -1,181 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* distribute test major
*/
public abstract class DistributeMajor implements ISocketObservable {
/**
* use map structure to determine device
*/
private Map<Integer, ISocketObserver> clientMap = new HashMap<Integer, ISocketObserver>();
private DistributeCfg distributeCfg = null;
private int coutClient = 0;
/**
* default construct
*/
public DistributeMajor() {
}
/**
* send message from major device to agent device
*
* @param devNo device num
* @param message message to send agent device
* @param expectValue expect return value
* @return 0-success,-1-failed
*/
public int sendMessage(DeviceEnum devNo, String message, String expectValue) {
if (clientMap != null) {
ISocketObserver curClient = clientMap.get(devNo.getValue());
if (curClient instanceof ClientObserver) {
return ((ClientObserver) curClient).sendMessage(message, expectValue);
}
}
return DistributeConsts.FAILED_CODE;
}
/**
* send message from major device to agent device, contains callback
*
* @param devNo device num
* @param message message to send agent device
* @param expectValue expect return value
* @param callback callback to handle the return value
* @return 0-success,-1-failed
*/
public int sendMessage(DeviceEnum devNo, String message, String expectValue, ICallBack callback) {
if (clientMap != null) {
ISocketObserver curClient = clientMap.get(devNo.getValue());
if (curClient instanceof ClientObserver) {
return ((ClientObserver) curClient).sendMessage(message, expectValue, callback);
}
}
return DistributeConsts.FAILED_CODE;
}
/**
* send command from major device to agent device
*
* @param devNo device num
* @param command command to send agent device
* @param cmdParam command param
* @param expectValue expect return value
* @return 0-success,-1-failed
*/
public int runCommandOnAgent(DeviceEnum devNo, String command, String cmdParam, String expectValue) {
if (clientMap != null) {
ISocketObserver curClient = clientMap.get(devNo.getValue());
if (curClient instanceof ClientObserver) {
return ((ClientObserver) curClient).runCommandOnAgent(command, cmdParam, expectValue);
}
}
return DistributeConsts.FAILED_CODE;
}
/**
* send command from major device to agent device, contains callback
*
* @param devNo device num
* @param command command to send agent device
* @param cmdParam command param
* @param expectValue expect return value
* @param callback callback to handle the return value
* @return 0-success,-1-failed
*/
public int runCommandOnAgent(DeviceEnum devNo, String command, String cmdParam, String expectValue,
ICallBack callback) {
if (clientMap != null) {
ISocketObserver curClient = clientMap.get(devNo.getValue());
if (curClient instanceof ClientObserver) {
return ((ClientObserver) curClient).runCommandOnAgent(command, cmdParam, expectValue, callback);
}
}
return DistributeConsts.FAILED_CODE;
}
@Override
public void addObserverSocket(ISocketObserver clientSocket) {
if (clientSocket instanceof ClientObserver) {
clientMap.put(DeviceEnum.DEVICE_FIRST.getValue() + coutClient, clientSocket);
}
coutClient++;
}
@Override
public void deleteObserverSocket(ISocketObserver clientSocket) {
clientSocket.updateSocket(DistributeConsts.STOP_CMD);
if (clientMap != null) {
clientMap.remove(clientSocket);
}
coutClient--;
}
@Override
public void notifyObservers(String message) {
if (clientMap != null) {
Collection<ISocketObserver> allSockets = clientMap.values();
for (ISocketObserver clientSocket : allSockets) {
clientSocket.updateSocket(message);
}
}
}
@Override
public boolean initEnvironment() {
distributeCfg = new DistributeCfg();
distributeCfg.readDistributeCfg("major.desc");
if (distributeCfg != null) {
for (String ipAddress : distributeCfg.getIpList()) {
ClientObserver clientObserver = new ClientObserver(ipAddress, distributeCfg.getPort());
addObserverSocket(clientObserver);
}
notifyObservers(DistributeConsts.START_CMD);
return true;
}
return false;
}
@Override
public boolean releaseEnvironment() {
notifyObservers(DistributeConsts.STOP_CMD);
if (clientMap != null) {
Collection<ISocketObserver> allSockets = clientMap.values();
for (ISocketObserver clientSocket : allSockets) {
clientMap.remove(clientSocket);
}
clientMap.clear();
return true;
}
return false;
}
public Map<Integer, ISocketObserver> getClientMap() {
return clientMap;
}
public void setClientMap(Map<Integer, ISocketObserver> clientMap) {
this.clientMap = clientMap;
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
/**
* call back for processing the distribute message
*/
public interface ICallBack {
/**
* process distribute message
*
* @apiNote process distribute message
*
* @param distCmd distribute message
* @return result
*/
int processDistCmd(DistributeCmd distCmd);
}

View File

@ -1,66 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
/**
* socket observable
*/
public interface ISocketObservable {
/**
* init environment
*
* @apiNote init environment
*
* @return true-success,false-failed
*/
boolean initEnvironment();
/**
* release environment
*
* @apiNote release environment
*
* @return true-success,false-failed
*/
boolean releaseEnvironment();
/**
* add socket observer
*
* @apiNote add socket observer
*
* @param observerSocket socket observer
*/
void addObserverSocket(ISocketObserver observerSocket);
/**
* remove socket observer
*
* @apiNote remove socket observer
*
* @param observerSocket socket observer
*/
void deleteObserverSocket(ISocketObserver observerSocket);
/**
* notify observer
*
* @apiNote notify observer
*
* @param message message
*/
void notifyObservers(String message);
}

View File

@ -1,65 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.junit.distribute;
/**
* Client for distributed socket
*/
public interface ISocketObserver {
/**
* init test resources
*
* @apiNote init test resources
*
* @return whether init is successful
*/
boolean initEnvironment();
/**
* update all socket messages
*
* @apiNote update all socket messages
*
* @param command processed command
*/
void updateSocket(String command);
/**
* release test resources
*
* @apiNote release test resources
*
*/
void releaseEnvironment();
/**
* get ipAddress
*
* @apiNote get ipAddress
*
* @return ipAddress
*/
String getIpAddress();
/**
* get port
*
* @apiNote get port
*
* @return port
*/
int getPort();
}

View File

@ -21,8 +21,6 @@ import time
import platform
import subprocess
from test_adapter_tools import TestAdapterTools
##############################################################################
##############################################################################
@ -32,7 +30,7 @@ if platform.system() != 'Windows':
QUOTATION_MARKS = "'"
else:
QUOTATION_MARKS = "\""
USB_TOOLS = TestAdapterTools.USB_TOOLS_CONST
USB_TOOLS = "hdc"
HDC_TOOLS = "hdc"

View File

@ -17,10 +17,6 @@
#
import os
import time
import json
import shutil
import zipfile
import tempfile
from abc import ABCMeta
from abc import abstractmethod
@ -32,20 +28,6 @@ from core.config.resource_manager import ResourceManager
##############################################################################
DEVICE_TEST_PATH = "/%s/%s/" % ("data", "test")
INSTRUMENT_HAP_FILE_SUFFIX = '_ad.hap'
TIME_OUT = 900 * 1000
class ZunitConst(object):
z_unit_app = "ohos.unittest.App"
output_dir = "OUTPUT_DIR="
output_file = "OUTPUT_FILE="
test_class = "TEST_CLASS="
exec_class = "EXEC_CLASS="
exec_method = "EXEC_METHOD="
exec_level = "EXEC_LEVEL="
jtest_status_filename = "jtest_status.txt"
remote_command_dir = "commandtmp"
def get_level_para_string(level_string):
@ -60,65 +42,6 @@ def get_level_para_string(level_string):
return level_para_string
def get_java_test_para(testcase, testlevel):
exec_class = "*"
exec_method = "*"
exec_level = ""
if "" != testcase and "" == testlevel:
pos = testcase.rfind(".")
if pos != -1:
exec_class = testcase[0:pos]
exec_method = testcase[pos + 1:]
exec_level = ""
else:
exec_class = "*"
exec_method = testcase
exec_level = ""
elif "" == testcase and "" != testlevel:
exec_class = "*"
exec_method = "*"
exec_level = get_level_para_string(testlevel)
return exec_class, exec_method, exec_level
def get_execute_java_test_files(suite_file):
java_test_file = ""
test_info_file = suite_file[:suite_file.rfind(".")] + ".info"
if not os.path.exists(test_info_file):
return java_test_file
try:
with open(test_info_file, "r") as file_desc:
lines = file_desc.readlines()
for line in lines:
class_name, _ = line.split(',', 1)
class_name = class_name.strip()
if not class_name.endswith("Test"):
continue
java_test_file += class_name + ","
except(IOError, ValueError) as err_msg:
print("Error to read info file: ", err_msg)
if java_test_file != "":
java_test_file = java_test_file[:-1]
return java_test_file
def get_dex_test_para(filename, suite_file):
exec_info = get_java_test_para("", "")
java_test_file = get_execute_java_test_files(suite_file)
exec_class, exec_method, exec_level = exec_info
dex_test_para = "%s %s%s %s%s %s%s %s%s %s%s %s%s" % (
ZunitConst.z_unit_app, ZunitConst.output_dir,
DEVICE_TEST_PATH,
ZunitConst.output_file, filename,
ZunitConst.test_class, java_test_file,
ZunitConst.exec_class, exec_class,
ZunitConst.exec_method, exec_method,
ZunitConst.exec_level, exec_level)
return dex_test_para
def make_long_command_file(command, longcommand_path, filename):
sh_file_name = '%s.sh' % filename
file_path = os.path.join(longcommand_path, sh_file_name)
@ -130,81 +53,6 @@ def make_long_command_file(command, longcommand_path, filename):
return sh_file_name, file_path
##################################################################
##################################################################
def get_package_and_ability_name(hap_filepath):
package_name = ""
ability_name = ""
if os.path.exists(hap_filepath):
filename = os.path.basename(hap_filepath)
# unzip the hap file
hap_bak_path = os.path.abspath(os.path.join(
os.path.dirname(hap_filepath),
"%s.bak" % filename))
zf_desc = zipfile.ZipFile(hap_filepath)
try:
zf_desc.extractall(path=hap_bak_path)
except RuntimeError as error:
print(error)
zf_desc.close()
# verify config.json file
app_profile_path = os.path.join(hap_bak_path, "config.json")
if not os.path.exists(app_profile_path):
print("file %s not exists" % app_profile_path)
return package_name, ability_name
if os.path.isdir(app_profile_path):
print("%s is a folder, and not a file" % app_profile_path)
return package_name, ability_name
# get package_name and ability_name value.
load_dict = {}
with open(app_profile_path, 'r') as load_f:
load_dict = json.load(load_f)
profile_list = load_dict.values()
for profile in profile_list:
package_name = profile.get("package")
if not package_name:
continue
abilities = profile.get("abilities")
for abilitie in abilities:
abilities_name = abilitie.get("name")
if abilities_name.startswith("."):
ability_name = package_name + abilities_name[
abilities_name.find("."):]
else:
ability_name = abilities_name
break
break
# delete hap_bak_path
if os.path.exists(hap_bak_path):
shutil.rmtree(hap_bak_path)
else:
print("file %s not exists" % hap_filepath)
return package_name, ability_name
def get_hap_test_para(filename, suite_file):
if not filename.endswith(INSTRUMENT_HAP_FILE_SUFFIX):
exec_class, exec_method, exec_level = get_java_test_para("", "")
java_test_file = get_execute_java_test_files(suite_file)
junit_test_para = "%s%s#%s%s#%s%s#%s%s" % (
ZunitConst.test_class, java_test_file,
ZunitConst.exec_class, exec_class,
ZunitConst.exec_method, exec_method,
ZunitConst.exec_level, exec_level)
else:
junit_test_para = get_execute_java_test_files(suite_file)
return junit_test_para
##############################################################################
##############################################################################
@ -258,183 +106,6 @@ class CppTestDriver(ITestDriver):
return self.device.shell(sh_command)
class DexTestDriver(ITestDriver):
def __init__(self, device):
self.device = device
def execute(self, suite_file, background=False):
filename = os.path.basename(suite_file)
target_test_path = DEVICE_TEST_PATH
junit_test_para = get_dex_test_para(filename, suite_file)
long_command_path = tempfile.mkdtemp(prefix="long_command_",
dir=os.path.join(os.environ.get('PYTEST_RESULTPATH'), "temp"))
command = "cd %s; rm -rf %s.xml; chmod +x *;" \
" export BOOTCLASSPATH=%s%s:$BOOTCLASSPATH;" \
" app_process %s%s %s" % \
(target_test_path,
filename,
target_test_path,
filename,
target_test_path,
filename,
junit_test_para)
print("command: %s" % command)
sh_file_name, file_path = make_long_command_file(command,
long_command_path,
filename)
# push resource files
resource_manager = ResourceManager()
resource_data_dic, resource_dir = \
resource_manager.get_resource_data_dic(suite_file)
resource_manager.process_preparer_data(resource_data_dic, resource_dir,
self.device)
self.device.push_file(file_path, DEVICE_TEST_PATH)
if background:
sh_command = "nohup sh %s 2>&1 &" % (
os.path.join(DEVICE_TEST_PATH, sh_file_name))
else:
sh_command = "sh %s" % (
os.path.join(DEVICE_TEST_PATH, sh_file_name))
return self.device.shell(sh_command)
class HapTestDriver(ITestDriver):
def __init__(self, device):
self.device = device
self.ability_name = ""
self.package_name = ""
self.activity_name = ""
self.target_result_dir = ""
def execute(self, suite_file, background=False):
self.package_name, self.ability_name = get_package_and_ability_name(
suite_file)
self.activity_name = "%s.MainAbilityShellActivity" % self.package_name
self.target_result_dir = "/data/data/%s/files/test/result/" % (
self.package_name)
# push resource files
resource_manager = ResourceManager()
resource_data_dic, resource_dir = \
resource_manager.get_resource_data_dic(suite_file)
resource_manager.process_preparer_data(resource_data_dic, resource_dir,
self.device)
filename = os.path.basename(suite_file)
junit_test_para = get_hap_test_para(filename, suite_file)
install_result = self.install_hap(filename)
if install_result:
self._execute_suitefile_junittest(filename,
junit_test_para,
self.target_result_dir,
background)
self.move_result_file(filename)
self.unistall_hap(self.package_name)
else:
print("Error: install hap failed.")
def _execute_suitefile_junittest(self, filename,
testpara,
target_test_path,
background):
self.device.unlock_screen()
self.device.unlock_device()
try:
if not filename.endswith(INSTRUMENT_HAP_FILE_SUFFIX):
command = "am start -S -n %s/%s --es param '%s'" % (
self.package_name,
self.activity_name,
testpara)
else:
command = "aa start -p %s -n %s -s AbilityTestCase %s" \
" -w %s" % (
self.package_name,
self.ability_name,
testpara,
str(TIME_OUT))
print("command: %s" % command)
long_command_path = tempfile.mkdtemp(prefix="long_command_",
dir=os.path.join(os.environ.get('PYTEST_RESULTPATH'), "temp"))
sh_file_name, file_path = make_long_command_file(command,
long_command_path,
filename)
self.device.push_file(file_path, DEVICE_TEST_PATH)
if background:
sh_command = "nohup sh %s 2>&1 &" % (
os.path.join(DEVICE_TEST_PATH, sh_file_name))
else:
sh_command = "sh %s" % (
os.path.join(DEVICE_TEST_PATH, sh_file_name))
return_message = self.device.shell(sh_command)
time.sleep(1)
if not filename.endswith(INSTRUMENT_HAP_FILE_SUFFIX):
print("HAP Testcase is executing, please wait a moment...")
if return_message:
self._check_hap_finished(target_test_path)
except (ExecuteTerminate, DeviceError) as exception:
return_message = str(exception.args)
print("return_message")
self.device.lock_screen()
def _check_hap_finished(self, target_test_path):
run_timeout = True
sleep_duration = 3
target_file = os.path.join(target_test_path,
ZunitConst.jtest_status_filename)
for _ in range(int(TIME_OUT / (1000 * sleep_duration))):
check_value = self.device.is_file_exist(target_file)
if not check_value:
time.sleep(sleep_duration)
continue
run_timeout = False
break
if run_timeout:
return_code = False
print("HAP Testcase executed timeout or exception.")
else:
return_code = True
print("HAP Testcase executed finished")
return return_code
def move_result_file(self, filename):
remote_result_file = os.path.join(self.target_result_dir,
"testcase_result.xml")
self.device.shell("mv %s %s.xml" % (remote_result_file,
os.path.join(DEVICE_TEST_PATH, filename)))
def install_hap(self, filename):
message = self.device.shell_with_output("bm install -p %s" %
os.path.join(DEVICE_TEST_PATH, filename))
message = str(message).rstrip()
if message != "":
print(message)
if message == "" or "Success" in message:
return_code = True
else:
return_code = False
time.sleep(1)
return return_code
def unistall_hap(self, package_name):
result = self.device.shell("pm uninstall %s" % package_name)
time.sleep(1)
return result
##############################################################################
##############################################################################

View File

@ -1,45 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2021 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<TestFileConfig>
<testfile_name>
<phone>
<item></item>
</phone>
<ivi>
<item></item>
</ivi>
<wearable>
<item></item>
</wearable>
<intellitv>
<item></item>
</intellitv>
</testfile_name>
<subsystem_name>
<phone>
<item></item>
</phone>
<ivi>
<item></item>
</ivi>
<wearable>
<item></item>
</wearable>
<intellitv>
<item></item>
</intellitv>
</subsystem_name>
</TestFileConfig>
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2021 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<TestFileConfig>
<testfile_name>
<phone>
<item></item>
</phone>
<ivi>
<item></item>
</ivi>
<wearable>
<item></item>
</wearable>
<intellitv>
<item></item>
</intellitv>
</testfile_name>
<subsystem_name>
<phone>
<item></item>
</phone>
<ivi>
<item></item>
</ivi>
<wearable>
<item></item>
</wearable>
<intellitv>
<item></item>
</intellitv>
</subsystem_name>
</TestFileConfig>

View File

@ -14,25 +14,13 @@
limitations under the License.
-->
<user_config>
<common>
<!-- reserved field to distinguish device form -->
<doublefwk>false</doublefwk>
</common>
<build>
<!-- whether compile test demo case, default false -->
<example>false</example>
<!-- whether compile test version, default false -->
<version>false</version>
<!-- whether compile test case, default false -->
<testcase>false</testcase>
<paramter>
<!-- reserved field, os name -->
<target_os>ohos</target_os>
<!-- reserved field, cpu type -->
<target_cpu>arm64</target_cpu>
<!-- reserved field, version type, default debug -->
<variant>debug</variant>
</paramter>
<testcase>true</testcase>
<board_info>
<!-- board series, default hispark -->
<board_series>hispark</board_series>

View File

@ -17,8 +17,6 @@ ohos_subsystem("subsystem_examples") {
subsystem_packages = [
"calculator:calculator",
"detector:detector",
"string_utils:string_utils_maple_java",
"string_utils:string_app_maple_java",
"calculator:calculator_static",
]
}
@ -28,6 +26,7 @@ ohos_subsystem_test("subsystem_examples_test") {
test_packages = [
"calculator/test:unittest",
"detector/test:unittest",
"distributedb/test:distributedtest",
"sleep/test:performance",
]
}

0
examples/calculator/include/calculator.h Executable file → Normal file
View File

0
examples/calculator/src/calculator.cpp Executable file → Normal file
View File

View File

View File

View File

View File

0
examples/detector/include/detector.h Executable file → Normal file
View File

0
examples/detector/src/detector.cpp Executable file → Normal file
View File

View File

View File

View File

View File

@ -0,0 +1,93 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/test.gni")
module_output_path = "subsystem_examples/distributedb"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"//utils/native/base/include",
"//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include",
"//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/include",
"//test/developertest/aw/distributed",
]
# link library
#ldflags = [ "-llog" ]
# library path
lib_dirs = [
"//foundation/appexecfwk/libs",
]
}
ohos_distributedtest("DistributeDemo") {
module_out_path = module_output_path
sources = [ "//test/developertest/examples/distributedb/test/distributedtest/common/distribute_demo.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"hilog:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest",
"//utils/native/base:utils",
]
}
ohos_distributedtest("DistributeDemoAgent") {
module_out_path = module_output_path
sources = [ "//test/developertest/examples/distributedb/test/distributedtest/common/distribute_demo_agent.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"hilog:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/:app_distributeddata",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest",
"//utils/native/base:utils",
]
}
###############################################################################
group("distributedtest") {
testonly = true
deps = [
":DistributeDemo",
":DistributeDemoAgent",
]
}
###############################################################################

View File

@ -0,0 +1,255 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "distributed_major.h"
#include "app_types.h"
#include "refbase.h"
#include "app_kvstore.h"
#include "app_distributed_kv_data_manager.h"
#include "hilog/log.h"
using namespace std;
using namespace OHOS;
using namespace testing::ext;
using namespace OHOS::DistributeSystemTest;
using namespace OHOS::HiviewDFX;
using namespace OHOS::AppDistributedKv;
namespace {
constexpr HiLogLabel LABEL = {LOG_CORE, 0, "DistributeDemo"};
const int SYNC_REC_TIME = 3;
const int MSG_LENGTH = 100;
const int EXPECT_RETURN_VALUE = 111;
const int EXPECT_ADD_TEST_SUM = 500;
const int SLEEP_TIME = 100000;
}
class DistributeDemo : public DistributeTest {
public:
DistributeDemo() = default;
~DistributeDemo() = default;
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
virtual void SetUp() {};
virtual void TearDown() {};
};
/**
* @tc.name: msgsendtest_001
* @tc.desc: Verify the distributed test framework interface SendMessage.
* @tc.type: FUNC
* @tc.require: AR000CQGMV
*/
HWTEST_F(DistributeDemo, msgsendtest_001, TestSize.Level0)
{
char msgbuf[MSG_LENGTH] = "I am testcase 1.";
EXPECT_TRUE(SendMessage(AGENT_NO::ONE, msgbuf, MSG_LENGTH));
};
/**
* @tc.name: msgsendtest_002
* @tc.desc: Verify the distributed test framework interface SendMessage, Maximum data length.
* @tc.type: FUNC
* @tc.require: AR000CQGMV
*/
HWTEST_F(DistributeDemo, msgsendtest_002, TestSize.Level0)
{
char msgbuf[MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN] = "I am testcase 2.";
EXPECT_TRUE(SendMessage(AGENT_NO::ONE, msgbuf, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN));
};
/**
* @tc.name: msgsendtest_003
* @tc.desc: Verify the distributed test framework interface SendMessage,
* Verify the data maximum length of the sent message interface .
* @tc.type: FUNC
* @tc.require: AR000CQGMV
*/
HWTEST_F(DistributeDemo, msgsendtest_003, TestSize.Level0)
{
char msgbuf[MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN + 1] = "too big message.";
EXPECT_FALSE(SendMessage(AGENT_NO::ONE, msgbuf, MAX_BUFF_LEN - DST_COMMAND_HEAD_LEN + 1));
};
/**
* @tc.name: msgsendtest_004
* @tc.desc: Verify the distributed test framework interface SendMessage, constains callback.
* @tc.type: FUNC
* @tc.require: AR000CQGMV
*/
HWTEST_F(DistributeDemo, msgsendtest_004, TestSize.Level0)
{
std::string msgBuf = "recall function message test.";
int ret = SendMessage(AGENT_NO::ONE, msgBuf, MSG_LENGTH,
[&](const std::string &szreturnbuf, int rlen)->bool {
std::string szbuf = "I get recall message.";
EXPECT_TRUE(szbuf == szreturnbuf);
HiLog::Info(LABEL, "msgsendtest_004 strncmp=%s", szbuf.c_str());
return true;
});
EXPECT_TRUE(ret > 0);
};
/**
* @tc.name: runcmdonagent_001
* @tc.desc: Verify the distributed test framework interface RunCmdOnAgent.
* @tc.type: FUNC
* @tc.require: AR000CQGMV
*/
HWTEST_F(DistributeDemo, runcmdonagent_001, TestSize.Level0)
{
std::string command = "query_command";
std::string cmdArgs = "query a name?";
std::string expectValue = "111";
RunCmdOnAgent(AGENT_NO::ONE, command, cmdArgs, expectValue);
EXPECT_EQ(GetReturnVal(), EXPECT_RETURN_VALUE);
};
/**
* @tc.name: runcmdonagent_002
* @tc.desc: Verify the distributed test framework interface RunCmdOnAgent, Using command map.
* @tc.type: FUNC
* @tc.require: AR000CQGMV
*/
HWTEST_F(DistributeDemo, runcmdonagent_002, TestSize.Level0) {
std::string command = "add_for_two_int";
std::string cmdArgs = "200 300";
std::string expectValue = "500";
RunCmdOnAgent(AGENT_NO::ONE, command, cmdArgs, expectValue);
EXPECT_EQ(GetReturnVal(), EXPECT_ADD_TEST_SUM);
};
/**
* @tc.name: getkvstore_001
* @tc.desc: Verify distributed data read and write and synchronization.
* @tc.type: FUNC
* @tc.require: AR000CQGMV
*/
HWTEST_F(DistributeDemo, getkvstore_001, TestSize.Level0) {
/**
* @tc.steps: step1.init appkvstore, Get the kvstore pointer for the specified appId and storeId
*/
static std::shared_ptr<AppDistributedKvDataManager> manager;
Options options;
options.createIfMissing = true;
options.encrypt = false;
options.persistant = true;
std::string appId = "com.ohos.nb.service.user1_test";
std::string storeId = "student_1";
manager = AppDistributedKvDataManager::GetInstance(appId, "/data/test");
std::unique_ptr<AppKvStore> kvStorePtr;
Status status = manager->GetKvStore(options, storeId, [&](std::unique_ptr<AppKvStore> kvStore) {
kvStorePtr = std::move(kvStore);
});
if (!kvStorePtr) {
HiLog::Error(LABEL, "client get kvStorePtr error.");
}
ASSERT_TRUE(kvStorePtr != nullptr);
/**
* @tc.steps: step2.Write specific K and V values to the database
*/
if (status == Status::SUCCESS) {
WriteOptions writeOptions;
writeOptions.local = false;
Key key("student_name_user1");
Value value = "good boy.";
kvStorePtr->Put(writeOptions, key, value);
}
/**
* @tc.steps: step3.Synchronize data to a specific remote device
*/
std::vector<std::string> deviceIdList;
deviceIdList.push_back("192.168.43.200");
std::map<std::string, Status> sync_map;
Status syncinfo = kvStorePtr->Sync(deviceIdList, SyncMode::PUSH,
[&](const std::map<std::string, Status> &syncMapinfo){
sync_map = std::move(syncMapinfo);
});
if (syncinfo == Status::SUCCESS) {
HiLog::Info(LABEL, "agent sync success");
}
/**
* @tc.steps: step4.Judge if the data is successfully synchronized to the remote device
*/
int n = 0;
while (n < SYNC_REC_TIME) {
std::string id = "";
for (auto mapstatus: sync_map) {
HiLog::Info(LABEL, "client map_id==%s", mapstatus.first.c_str());
if (mapstatus.second == Status::SUCCESS) {
id = mapstatus.first;
HiLog::Info(LABEL, "real client Sync success.");
} else {
HiLog::Info(LABEL, "mapstatus.second=%d.", (int)mapstatus.second);
}
n++;
}
if (id != "") {
break;
}
usleep(SLEEP_TIME);
}
if (syncinfo == Status::SUCCESS) {
HiLog::Info(LABEL, "client sync success.");
}
/**
* @tc.steps: step5.Query whether the value inserted in the local database is correct
*/
std::string command = "getkvstore";
std::string cmdArgs = "student_name_user1";
std::string expectValue = "good boy.";
ReadOptions readOptions;
readOptions.local = false;
Key key(cmdArgs);
Value getValue;
Status getTstatus = kvStorePtr->Get(readOptions, key, getValue);
if (getTstatus == Status::SUCCESS) {
HiLog::Info(LABEL, "Get Value SUCCESS, key=%s.", key.ToString().c_str());
} else {
HiLog::Error(LABEL, "Get Value Failed.");
}
/**
* @tc.steps: step6.Send a command to the remote device to query the database with parameters and
* expected return values
*/
RunCmdOnAgent(AGENT_NO::ONE, command, cmdArgs, expectValue);
/**
* @tc.steps: step7.Judge the return value
* @tc.expected: step7. The remote device queried the data successfully.
*/
EXPECT_TRUE(GetReturnVal() == EXPECT_RETURN_VALUE);
};
int main(int argc, char *argv[])
{
g_pDistributetestEnv = new DistributeTestEnvironment("major.desc");
testing::AddGlobalTestEnvironment(g_pDistributetestEnv);
testing::GTEST_FLAG(output) = "xml:./";
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -0,0 +1,232 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "distributed_agent.h"
#include <string>
#include <iostream>
#include "app_types.h"
#include "refbase.h"
#include "app_kvstore.h"
#include "app_distributed_kv_data_manager.h"
#include "hilog/log.h"
using namespace testing;
using namespace OHOS;
using namespace OHOS::DistributeSystemTest;
using namespace OHOS::HiviewDFX;
using namespace OHOS::AppDistributedKv;
namespace {
constexpr HiLogLabel LABEL = {LOG_CORE, 0, "DistributeDemoAgent"};
std::shared_ptr<AppDistributedKvDataManager> g_manager;
std::string g_appId = "com.ohos.nb.service.user1_test";
std::string g_storeId = "student_1";
std::unique_ptr<AppKvStore> g_kvStorePtr;
const int CMD_LEN = 4;
const int RETURN_HALF = 2;
const int MSG_CALL_LEN = 6;
const int CMD_RETURN_TWO = 111;
}
class DistributeDemoAgent : public DistributedAgent {
public:
DistributeDemoAgent();
~DistributeDemoAgent();
virtual bool SetUp();
virtual bool TearDown();
virtual int OnProcessMsg(const std::string &strMsg, int len, std::string &strReturnValue, int returnBufLen);
virtual int OnProcessCmd(const std::string &strCommand, int cmdLen, const std::string &strArgs, int argsLen,
const std::string &strExpectValue, int expectValueLen);
int GetKvValue(const std::string &strArgs, int argsLen, const std::string &strExpectValue,
int expectValueLen);
int AddTwoValue(const std::string &strArgs, int argsLen, const std::string &strExpectValue,
int expectValueLen);
int ProcessByUseMap(const std::string &strCommand, int cmdLen, const std::string &strArgs, int argsLen,
const std::string &strExpectValue, int expectValueLen);
private:
typedef int (DistributeDemoAgent::*self_func)(const std::string &, int, const std::string &, int);
std::map<std::string, self_func> cmdFunMap_;
};
DistributeDemoAgent::DistributeDemoAgent()
{
}
DistributeDemoAgent::~DistributeDemoAgent()
{
}
bool DistributeDemoAgent::SetUp()
{
/**
* @tc.setup: Initialize test agent, start data management service
*/
cmdFunMap_["getkvstore"] = &DistributeDemoAgent::GetKvValue;
cmdFunMap_["add_for_two_int"] = &DistributeDemoAgent::AddTwoValue;
g_manager = AppDistributedKvDataManager::GetInstance(g_appId, "/data/test");
Options options;
options.createIfMissing = true;
options.encrypt = false;
options.persistant = true;
std::string storeId = g_storeId;
Status status = g_manager->GetKvStore(options, storeId, [&](std::unique_ptr<AppKvStore> kvStore) {
g_kvStorePtr = std::move(kvStore);
});
if (status == Status::SUCCESS) {
return true;
}
return false;
}
bool DistributeDemoAgent::TearDown()
{
/**
* @tc.teardown: Recovery test agent device environment
*/
return true;
}
// The entry of handlingthe major test case message
int DistributeDemoAgent::OnProcessMsg(const std::string &strMsg, int len,
std::string &strReturnValue, int returnValueLen)
{
int nret = 0;
std::string returnStr = "agent return message.";
if ((len > CMD_LEN) && (strMsg.find("\0\1\0\1") == 1)) {
for (int i = 0; i < returnValueLen; i++) {
strReturnValue += std::to_string((i + 1) % RETURN_HALF);
}
nret = returnValueLen;
} else {
HiLog::Info(LABEL, "receive message=%s.", strMsg.c_str());
if (strncmp(strMsg.c_str(), "recall", MSG_CALL_LEN) == 0) {
returnStr = "I get recall message.";
int ptrlen = returnStr.size();
if (ptrlen > returnValueLen) {
ptrlen = returnValueLen - 1;
}
strReturnValue = returnStr;
nret = ptrlen;
} else {
nret = DistributedAgent::OnProcessMsg(strMsg, len, strReturnValue, returnValueLen);
}
}
return nret;
}
// The entry of handling the major test case command
int DistributeDemoAgent::OnProcessCmd(const std::string &strCommand, int cmdLen, const std::string &strArgs,
int argsLen, const std::string &strExpectValue, int expectValueLen)
{
if (strCommand == "query_command") {
if (strArgs == "query a name?") {
return CMD_RETURN_TWO;
}
}
return DistributeDemoAgent::ProcessByUseMap(strCommand, cmdLen, strArgs, argsLen, strExpectValue, expectValueLen);
}
// Handling major test case command: getkvstore
int DistributeDemoAgent::GetKvValue(const std::string &strArgs, int argsLen, const std::string &strExpectValue,
int expectValueLen)
{
if (!g_kvStorePtr || (int)strArgs.length() > argsLen) {
HiLog::Error(LABEL, "[ohos-test-fm]agent ERROR.");
return -1;
}
ReadOptions readOptions;
readOptions.local = false;
Key key(strArgs);
Value getValue;
Status status = g_kvStorePtr->Get(readOptions, key, getValue);
if (status == Status::SUCCESS) {
HiLog::Info(LABEL, "Get Value SUCCESS, key=%s.", key.ToString().c_str());
} else {
HiLog::Error(LABEL, "Get Value Failed.");
}
std::vector<Entry> allEntry;
Status entryStatus = g_kvStorePtr->GetEntries("", allEntry);
if (entryStatus == Status::SUCCESS) {
HiLog::Info(LABEL, "GetEntries SUCCESS.");
for (auto entry : allEntry) {
HiLog::Info(LABEL, "GetEntries key= %s.", entry.key.ToString().c_str());
}
}
if (getValue.ToString() == strExpectValue) {
if (expectValueLen < (int)getValue.ToString().length()) {
HiLog::Error(LABEL, "[ohos-test-fm]agent end xxx.");
return -1;
}
HiLog::Error(LABEL, "[ohos-test-fm]agent end 200.");
return CMD_RETURN_TWO;
}
return -1;
}
// Handling major test case command: add_for_two_int
int DistributeDemoAgent::AddTwoValue(const std::string &strArgs, int argsLen, const std::string &strExpectValue,
int expectValueLen)
{
int val1 = 0;
int val2 = 0;
int val3 = 0;
sscanf_s(strArgs.c_str(), "%d %d", &val1, &val2);
sscanf_s(strExpectValue.c_str(), "%d", &val3);
EXPECT_TRUE(val3 == (val1 + val2));
return val1 + val2;
}
// Handling major test cases through already registered commands and function mappings
int DistributeDemoAgent::ProcessByUseMap(const std::string &strCommand, int cmdLen, const std::string &strArgs,
int argsLen, const std::string &strExpectValue, int expectValueLen)
{
std::map<std::string, self_func>::iterator ite = cmdFunMap_.find(strCommand);
if (ite != cmdFunMap_.end()) {
self_func callProcCmd = cmdFunMap_[strCommand];
if (callProcCmd != nullptr) {
return (this->*callProcCmd)(strArgs, argsLen, strExpectValue, expectValueLen);
} else {
return DistributedAgent::OnProcessCmd(strCommand,
cmdLen,
strArgs,
argsLen,
strExpectValue,
expectValueLen);
}
}
return -1;
}
int main()
{
// Test agent main function
DistributeDemoAgent obj;
if (obj.SetUp()) {
obj.Start("agent.desc");
obj.Join();
} else {
HiLog::Error(LABEL, "Init environment failed.");
}
if (obj.TearDown()) {
return 0;
} else {
HiLog::Error(LABEL, "Clear environment failed.");
return -1;
}
}

0
examples/lite/c_demo/include/calc_multi.h Executable file → Normal file
View File

0
examples/lite/c_demo/source/calc_multi.c Executable file → Normal file
View File

View File

View File

View File

@ -10,7 +10,8 @@
"test_list": [
"//test/developertest/examples/calculator/test:unittest",
"//test/developertest/examples/detector/test:unittest",
"//test/developertest/examples/sleep/test:performance"
"//test/developertest/examples/sleep/test:performance",
"//test/developertest/examples/distributedb/test:distributedtest"
]
}
}

0
examples/sleep/include/sleep_ex.h Executable file → Normal file
View File

0
examples/sleep/src/sleep_ex.cpp Executable file → Normal file
View File

View File

View File

@ -22,4 +22,4 @@
<testcase message="" time="" name="method_name/py_name" result="true/false" status="run/disabled/ignored" classname="class_name"/>
<testcase message="" time="" name="method_name/py_name" result="true/false" status="run/disabled/ignored" classname="class_name"/>
</testsuite>
</testsuites>
</testsuites>

View File

@ -1,38 +0,0 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/config/ohos/rules.gni")
java_library("string_utils_java") {
java_files = [ "src/com/ohos/utils/StringUtils.java" ]
}
ohos_maple_java("string_utils_maple_java") {
deps = [ ":string_utils_java" ]
so_name = "string_utils_maple_java"
subsystem_name = "subsystem_examples"
}
java_library("string_app_java") {
java_files = [ "src/com/ohos/app/Application.java" ]
deps = [ ":string_utils_java" ]
}
ohos_maple_java("string_app_maple_java") {
deps = [ ":string_app_java" ]
so_name = "string_app_maple_java"
subsystem_name = "subsystem_examples"
}

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ohos.app;
import com.ohos.utils.StringUtils;
/**
* test string method
*/
public class Application {
public static void main(String[] args) {
String input = "abcDeFGhJk";
System.out.println("input: " + input);
System.out.println("toLowerCase: " + StringUtils.toLowerCase(input));
System.out.println("toUpperCase: " + StringUtils.toUpperCase(input));
System.out.println("reverse: " + StringUtils.reverse(input));
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ohos.utils;
import java.util.Locale;
/**
* handle string method
*/
public class StringUtils {
private static String EMPTY_STRING = "";
/**
* change string to lower case
*
* @param str input string
* @return lower case string
*/
public static String toLowerCase(String str) {
if (str == null) {
return EMPTY_STRING;
}
return str.toLowerCase(Locale.getDefault());
}
/**
* change string to upper case
*
* @param str input string
* @return upper case string
*/
public static String toUpperCase(String str) {
if (str == null) {
return EMPTY_STRING;
}
return str.toUpperCase(Locale.getDefault());
}
/**
* change string to reverse
*
* @param str input string
* @return reverse string
*/
public static String reverse(String str) {
if (str == null) {
return EMPTY_STRING;
}
return new StringBuffer(str).reverse().toString();
}
}

View File

@ -1,90 +0,0 @@
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/config/ohos/rules.gni")
java_library("base_test_framework_java") {
emma_never_instrument = true
java_files = [
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/runner/TestRunner.java",
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/runner/notification/MyRunListener.java",
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/runner/notification/MyCaseListener.java",
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/runner/record/ReportGenerater.java",
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/runner/record/TestCaseInfo.java",
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/runner/record/TestClassInfo.java",
]
final_jar_path = "$root_out_dir/test_platform/libs/base_test_framework.jar"
deps = [
":unittest_utils_parts_java",
"//third_party/easymock:easymock_java",
"//third_party/junit:junit_java",
]
if (emma_coverage) {
deps += [ "//third_party/jacoco:jacocoagent_java" ]
}
}
java_library("test_executor_java") {
emma_never_instrument = true
java_files = [
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/App.java",
"//test/developertest/libs/jtr/executor/java/src/ohos/unittest/runner/UtTestRunner.java",
]
final_jar_path = "$root_out_dir/test_platform/libs/test_executor.jar"
deps = [ ":base_test_framework_java" ]
}
java_library("unittest_utils_parts_java") {
emma_never_instrument = true
java_files = [
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/CaseLevel.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/Level.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/CaseType.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/TestTarget.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/Type.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/log/LogFile.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/log/Logger.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/BaseLine.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/PerfVerify.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/BaseLineParser.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/VerifySingleton.java",
]
final_jar_path = "$root_out_dir/test_platform/libs/unittest_utils_parts.jar"
deps = [ "//third_party/junit:junit_java" ]
}
java_library("perf_test_framework_java") {
emma_never_instrument = true
java_files = [
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/BaseLine.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/PerfVerify.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/BaseLineParser.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/perf/VerifySingleton.java",
]
final_jar_path = "$root_out_dir/test_platform/libs/perf_test_framework.jar"
deps = [
":test_logger_java",
"//third_party/junit:junit_java",
]
}
java_library("test_logger_java") {
emma_never_instrument = true
java_files = [
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/log/LogFile.java",
"//test/developertest/libs/jtr/common/java/src/ohos/unittest/log/Logger.java",
]
final_jar_path = "$root_out_dir/test_platform/libs/test_logger.jar"
deps = []
}

View File

@ -1,30 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* CaseLevel annotation definition
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface CaseLevel {
Level level() default Level.DEFAULT;
}

View File

@ -1,30 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* CaseType annotation definition
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface CaseType {
Type type() default Type.DEFAULT;
}

View File

@ -1,23 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest;
/**
* Case level definition
*/
public enum Level {
DEFAULT, LEVEL_0, LEVEL_1, LEVEL_2, LEVEL_3, LEVEL_4
}

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestTarget {
String className();
String methodName();
}

View File

@ -1,32 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest;
/**
* Test Type definition
FUNC, ----- functionality test
PERF, ----- performance test
RELI, ----- reliability test
COMP, ----- compatibility test
USAB, ----- usability test
SERV, ----- serviceability test
SECU, ----- security test
*
*/
public enum Type {
DEFAULT, FUNC, PERF, RELI, COMP, USAB, SERV, SECU
}

View File

@ -1,174 +0,0 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.log;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
/**
* Log File
*/
public class LogFile {
/**
* LogFile instance
*/
private static LogFile instance = null;
/**
* Log file path
*/
private String logFilePath;
/**
* LogFile Constructor
*/
private LogFile() {
}
/**
* get LogFile single Instance
*
* @return LogFile Instance
*/
public static LogFile getInstance() {
if (instance == null) {
instance = new LogFile();
}
return instance;
}
/**
* Print log information in file
*
* @param content log content
*/
public void println(String content) {
if (content == null) {
return;
}
writeFile(content);
}
/**
* Create log File
*
* @param filePath log file Path
*/
public void createLogFile(String filePath) {
File file = new File(filePath);
if (file.exists() && !file.isDirectory()) {
file.delete();
}
try {
file.createNewFile();
this.logFilePath = filePath;
} catch (IOException e) {
e.printStackTrace();
}
}
public String getLogFilePath() {
return this.logFilePath;
}
public void setLogFilePath(String logFilePath) {
this.logFilePath = logFilePath;
}
/**
* Create File and write content in it
*
* @param filePath file Path
* @param fileData file Data
*/
public static void createFileAndWriteData(String filePath,
List<String> fileData) {
FileWriter writer = null;
try {
File file = new File(filePath);
if (file.exists() && !file.isDirectory()) {
file.delete();
}
file.createNewFile();
writer = new FileWriter(file);
for (String content : fileData) {
writer.write(content + System.lineSeparator());
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Write File with content
*
* @param content log information
*/
private void writeFile(String content) {
FileWriter writer = null;
try {
if ((this.logFilePath == null) || "".equals(this.logFilePath)) {
return;
}
File file = new File(this.logFilePath);
if (file.isDirectory()) {
return;
}
if (!file.exists()) {
file.createNewFile();
}
writer = new FileWriter(file, true);
writer.write(content + System.lineSeparator());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -1,57 +0,0 @@
/*
* Copyright (c) 2020 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.log;
/**
* Logger
*/
public final class Logger {
/**
* LogFile instance
*/
private static LogFile logFile = LogFile.getInstance();
/**
* Logger Constructor
*/
private Logger() {
}
/**
* createLogFile
*
* @apiNote createLogFile
* @param filePath Log File path
*/
public static void createLogFile(String filePath) {
if (logFile != null) {
logFile.createLogFile(filePath);
}
}
/**
* Record log information
*
* @apiNote info
* @param content log information
*/
public static void info(String content) {
System.out.println(content);
if (logFile != null) {
logFile.println(content);
}
}
}

View File

@ -1,63 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.perf;
import ohos.unittest.log.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* BaseLine
*/
public class BaseLine {
private BaseLineParser baseLineParser = new BaseLineParser();
/**
* BaseLine construction
*
* @param filePath config FilePath
*/
public BaseLine(String filePath) {
baseLineParser = new BaseLineParser();
if (baseLineParser != null) {
baseLineParser.loadConfig(filePath);
}
}
public BaseLineParser getBaseLineParser() {
return baseLineParser;
}
@Override
public String toString() {
return "BaseLine [baseLineParser=" + baseLineParser + "]";
}
}

View File

@ -1,343 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.perf;
import ohos.unittest.log.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* BaseLineParser
*/
class BaseLineParser {
private static final int DEFAULT_DOUBLE_VALUE = -1;
private static final String BASELINE_KEY = "baseline";
private static final String LASTVALUE_KEY = "lastvalue";
private static final String FLOATRANGE_KEY = "floatrange";
/**
* case baseline value
*/
private HashMap<String /* case name */, HashMap<String /* item key */, String /* item value */>> caseBaseLine =
new HashMap<>();
/**
* baseline url
*/
private String url = "";
/**
* baseline date
*/
private String date = "";
/**
* isHasBaseLineCfg
*/
private boolean isHasBaseLineCfg = false;
/**
* BaseLine constructor
*/
BaseLineParser() {
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String /* case name */, HashMap<String /* item key */, String /* item value */>> getCaseBaseLine() {
return caseBaseLine;
}
/**
* isHasBaselineConfig
*
* @apiNote isHasBaselineConfig
* @return boolean
*/
public boolean isHasBaselineConfig() {
return isHasBaseLineCfg;
}
/**
* loadConfig
*
* @apiNote loadConfig
* @param configFilePath configFilePath
* @return boolean
*/
public boolean loadConfig(String configFilePath) {
boolean isSuccess = false;
if (configFilePath == null || configFilePath.trim().isEmpty()) {
Logger.info(String.format(Locale.ROOT, "[ ERROR ] Performance config file path can't be empty"));
return isSuccess;
}
File file = new File(configFilePath.trim());
if (file.exists()) {
try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
parserBaseline(document.getFirstChild());
isSuccess = true;
isHasBaseLineCfg = true;
} catch (SAXException e) {
Logger.info(String.format(Locale.ROOT, "SAXException: %s", e.getMessage()));
} catch (IOException e) {
Logger.info(String.format(Locale.ROOT, "IOException: %s", e.getMessage()));
} catch (ParserConfigurationException e) {
Logger.info(String.format(Locale.ROOT, "ParserConfigurationException: %s", e.getMessage()));
}
} else {
Logger.info(String.format(Locale.ROOT, "File:%s not exists", configFilePath));
}
showParsedBaseline();
return isSuccess;
}
/**
* parser xml document
*
* @apiNote parser
* @param root root
*/
public void parserBaseline(Node root) {
NodeList childNodes = root.getChildNodes();
String configLable = root.getNodeName();
if ("configuration".equals(configLable)) {
NamedNodeMap configLableAttribute = root.getAttributes();
if (configLableAttribute != null) {
for (int index = 0; index < configLableAttribute.getLength(); index++) {
Node attribute = configLableAttribute.item(index);
if ("date".equals(attribute.getNodeName())) {
this.date = attribute.getNodeValue();
}
if ("url".equals(attribute.getNodeName())) {
this.url = attribute.getNodeValue();
}
}
}
}
if (childNodes == null) {
return;
}
for (int index = 0; index < childNodes.getLength(); index++) {
Node caseItem = childNodes.item(index);
String caseLable = caseItem.getNodeName();
if (!"item".equals(caseLable)) {
continue;
}
String testCaseName = null;
HashMap<String, String> caseValue = new HashMap<>();
NamedNodeMap caseLableAttribute = caseItem.getAttributes();
for (int id = 0; id < caseLableAttribute.getLength(); id++) {
Node attribute = caseLableAttribute.item(id);
if ("name".equals(attribute.getNodeName())) {
testCaseName = attribute.getNodeValue();
}
caseValue.put(attribute.getNodeName(), attribute.getNodeValue());
}
if (testCaseName == null || testCaseName.isEmpty()) {
continue;
}
caseBaseLine.put(testCaseName, caseValue);
}
}
/**
* Show Parsed Baseline
*
* @apiNote show config info
*/
public void showParsedBaseline() {
Logger.info(String.format(Locale.ROOT, "baseline info:"));
Logger.info(String.format(Locale.ROOT, " update date : %s", getDate()));
Logger.info(String.format(Locale.ROOT, " data from db: %s", getUrl()));
Logger.info(String.format(Locale.ROOT, " total items : %s", String.valueOf(getCount())));
for (Entry<String, HashMap<String, String>> entry : caseBaseLine.entrySet()) {
Logger.info(String.format(Locale.ROOT, "case:%s %s:%s %s:%s %s:%s", entry.getKey(), BASELINE_KEY,
entry.getValue().get(BASELINE_KEY), LASTVALUE_KEY, entry.getValue().get(LASTVALUE_KEY), FLOATRANGE_KEY,
entry.getValue().get(FLOATRANGE_KEY)));
}
}
/**
* getCount
*
* @apiNote getCount
* @return int
*/
public int getCount() {
if (caseBaseLine != null) {
return caseBaseLine.size();
} else {
return 0;
}
}
/**
* isHasBaseLineValue
*
* @apiNote isHasBaseLineValue
* @param caseName test case name
* @return boolean
*/
public boolean isHasBaseLineValue(String caseName) {
return isContainCaseBaseValue(caseName, BASELINE_KEY);
}
/**
* isHasLastValue
*
* @apiNote isHasLastValue
* @param caseName test case name
* @return boolean
*/
public boolean isHasLastValue(String caseName) {
return isContainCaseBaseValue(caseName, LASTVALUE_KEY);
}
/**
* isHasFloatRange
*
* @apiNote isHasFloatRange
* @param caseName test case name
* @return boolean
*/
public boolean isHasFloatRange(String caseName) {
return isContainCaseBaseValue(caseName, FLOATRANGE_KEY);
}
/**
* getBaseLineValue
*
* @apiNote getBaseLineValue
* @param caseName test case name
* @return double
*/
public double getBaseLineValue(String caseName) {
if (caseBaseLine.containsKey(caseName)) {
return convertStr2Double(caseBaseLine.get(caseName).get(BASELINE_KEY));
} else {
return DEFAULT_DOUBLE_VALUE;
}
}
/**
* getLastValue
*
* @apiNote getLastValue
* @param caseName test case name
* @return double
*/
public double getLastValue(String caseName) {
if (caseBaseLine.containsKey(caseName)) {
return convertStr2Double(caseBaseLine.get(caseName).get(LASTVALUE_KEY));
} else {
return DEFAULT_DOUBLE_VALUE;
}
}
/**
* getFloatRange
*
* @apiNote getFloatRange
* @param caseName test case name
* @return double
*/
public double getFloatRange(String caseName) {
if (caseBaseLine.containsKey(caseName)) {
return convertStr2Double(caseBaseLine.get(caseName).get(FLOATRANGE_KEY));
} else {
return DEFAULT_DOUBLE_VALUE;
}
}
/**
* isContainCaseBaseValue
*
* @apiNote isContainCaseBaseValue
* @param caseName test case name
* @param itemName item name
* @return boolean
*/
private boolean isContainCaseBaseValue(String caseName, String itemName) {
if (caseName == null || caseName.isEmpty()) {
return false;
}
if (caseBaseLine == null || caseBaseLine.isEmpty()) {
return false;
}
HashMap<String, String> caseItem = caseBaseLine.get(caseName);
if (caseItem == null) {
return false;
}
String value = caseItem.get(itemName);
if (value == null || value.isEmpty() || convertStr2Double(value) <= 0) {
return false;
}
return true;
}
private double convertStr2Double(String str) {
if (str.isEmpty()) {
return 0.0;
}
return Double.valueOf(str);
}
@Override
public String toString() {
return "BaseLineParser [caseBaseLine=" + caseBaseLine + ", url=" + url + ", date=" + date
+ ", isHasBaseLineCfg=" + isHasBaseLineCfg + "]";
}
}

View File

@ -1,119 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.perf;
/**
* performance verify
*/
public class PerfVerify {
private static final int DATA_3 = 3;
/**
* baseLine
*/
private BaseLine perfBaseLine = null;
/**
* version
*/
private long version = 1;
/**
* constructor
*
* @param baseLine baseLine
*/
public PerfVerify(BaseLine baseLine) {
this.perfBaseLine = baseLine;
this.version = 1;
}
/**
* constructor
*
* @param baseLine baseLine
* @param version baseline version
*/
public PerfVerify(BaseLine baseLine, long version) {
this.perfBaseLine = baseLine;
this.version = version;
}
/**
* expectLarger
*
* @apiNote expectLarger
* @param spentTime spentTime
* @param version version
* @return boolean
*/
public boolean expectLarger(double spentTime, long version) {
this.version = version;
String caseName = Thread.currentThread().getStackTrace()[DATA_3].getMethodName();
String className = Thread.currentThread().getStackTrace()[DATA_3].getClassName();
return VerifySingleton.getInstance().expectLarger(className, caseName, spentTime,
this.perfBaseLine, this.version);
}
/**
* expectLarger
*
* @apiNote expectLarger
* @param spentTime spentTime
* @return boolean
*/
public boolean expectLarger(double spentTime) {
String caseName = Thread.currentThread().getStackTrace()[DATA_3].getMethodName();
String className = Thread.currentThread().getStackTrace()[DATA_3].getClassName();
return VerifySingleton.getInstance().expectLarger(className, caseName, spentTime,
this.perfBaseLine, this.version);
}
/**
* expectSmaller
*
* @apiNote expectSmaller
* @param spentTime spentTime
* @param version version
* @return boolean
*/
public boolean expectSmaller(double spentTime, long version) {
this.version = version;
String caseName = Thread.currentThread().getStackTrace()[DATA_3].getMethodName();
String className = Thread.currentThread().getStackTrace()[DATA_3].getClassName();
return VerifySingleton.getInstance().expectSmaller(className, caseName, spentTime,
this.perfBaseLine, this.version);
}
/**
* expectSmaller
*
* @apiNote expectSmaller
* @param spentTime spentTime
* @return boolean
*/
public boolean expectSmaller(double spentTime) {
String caseName = Thread.currentThread().getStackTrace()[DATA_3].getMethodName();
String className = Thread.currentThread().getStackTrace()[DATA_3].getClassName();
return VerifySingleton.getInstance().expectSmaller(className, caseName, spentTime,
this.perfBaseLine, this.version);
}
@Override
public String toString() {
return "Verify [perfBaseLine=" + perfBaseLine + ", version=" + version + "]";
}
}

View File

@ -1,498 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.perf;
import ohos.unittest.log.Logger;
import org.junit.Assert;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
/**
* performance verify Singleton
*/
public class VerifySingleton {
/**
* performance test result
*/
private Map<String /* suit name */, Map<String /* case name */, PerfTest>> suitPerfResult = new HashMap<>();
/**
* Verify constructor
*/
private VerifySingleton() {
}
/**
* Singleton
*/
private static class Singleton {
static VerifySingleton instance = new VerifySingleton();
}
/**
* getInstance
*
* @apiNote getInstance
* @return VerifyMgr Singleton
*/
public static VerifySingleton getInstance() {
return Singleton.instance;
}
public Map<String, Map<String, PerfTest>> getSuitPerfResult() {
return suitPerfResult;
}
/**
* isPerfTestcase
*
* @apiNote isPerfTestcase
* @param className test class Name
* @param caseName test case Name
* @return boolean
*/
public boolean isPerfTestcase(String className, String caseName) {
PerfTest perfTest = getTestCasePerfResult(className, caseName);
if (perfTest == null) {
return false;
}
return true;
}
private PerfTest getTestCasePerfResult(String className, String caseName) {
PerfTest perfTest = null;
for (Entry<String, Map<String, PerfTest>> entry : suitPerfResult.entrySet()) {
if (!className.equals(entry.getKey())) {
continue;
}
for (Entry<String, PerfTest> entry1 : entry.getValue().entrySet()) {
if (!caseName.equals(entry1.getKey())) {
continue;
}
perfTest = entry1.getValue();
}
if (perfTest != null) {
break;
}
}
return perfTest;
}
/**
* getPerfTestResult
*
* @apiNote getPerfTestResult
* @param className test class Name
* @param caseName test case Name
* @return Map
*/
public Map<String, String> getPerfTestResult(String className, String caseName) {
Map<String, String> perfResult = new HashMap<>();
PerfTest perfTest = getTestCasePerfResult(className, caseName);
if (perfTest == null) {
return perfResult;
}
perfResult.put("value", String.valueOf(perfTest.getTestValue()));
perfResult.put("category", String.valueOf(perfTest.getCategory()));
perfResult.put("tc_version", String.valueOf(perfTest.getCaseVersion()));
perfResult.put("lastvalue", String.valueOf(perfTest.getDbLastValue()));
perfResult.put("baseline", String.valueOf(perfTest.getDbBaseLineValue()));
return perfResult;
}
/**
* expectLarger
*
* @apiNote expectLarger
* @param className test class Name
* @param caseName test case Name
* @param spentTime spentTime
* @param baseLine performance baseLine
* @param version version
* @return boolean
*/
public boolean expectLarger(String className, String caseName, double spentTime, BaseLine baseLine, long version) {
PerfTest perfTest = new PerfTest(className, caseName, baseLine.getBaseLineParser(), version);
Map<String, PerfTest> defaultValue = suitPerfResult.get(className);
if (defaultValue == null) {
defaultValue = new HashMap<>();
}
defaultValue.put(caseName, perfTest);
suitPerfResult.put(className, defaultValue);
return perfTest.expectLarger(spentTime);
}
/**
* expectSmaller
*
* @apiNote expectSmaller
* @param className test class Name
* @param caseName test case Name
* @param spentTime spentTime
* @param baseLine performance baseLine
* @param version version
* @return boolean
*/
public boolean expectSmaller(String className, String caseName, double spentTime, BaseLine baseLine, long version) {
PerfTest perfTest = new PerfTest(className, caseName, baseLine.getBaseLineParser(), version);
Map<String, PerfTest> defaultValue = suitPerfResult.get(className);
if (defaultValue == null) {
defaultValue = new HashMap<>();
}
defaultValue.put(caseName, perfTest);
suitPerfResult.put(className, defaultValue);
return perfTest.expectSmaller(spentTime);
}
@Override
public String toString() {
return "VerifyMgr [suitPerfResult=" + suitPerfResult + "]";
}
}
/**
* PerfTest
*/
class PerfTest {
private String caseName = "";
private String className = "";
private String category = "performance";
private boolean isHasBaseLine = false;
private boolean isHasLastValue = false;
private boolean isHasFloatRange = false;
private double testValue = 0.0;
private double dbLastValue = 0.0;
private double dbBaseLineValue = 0.0;
private double dbFloatRange = 0.0;
private long caseVersion = 0L;
private BaseLineParser perfBaseLine = null;
/**
* PerfTest constructor
*
* @param baseLine Performance baseLine object
* @param version Performance baseLine version
*/
PerfTest(String className, String caseName, BaseLineParser baseLine, long version) {
this.className = className;
this.caseName = caseName;
this.perfBaseLine = baseLine;
this.caseVersion = version;
init();
}
public long getCaseVersion() {
return caseVersion;
}
public void setCaseVersion(long caseVersion) {
this.caseVersion = caseVersion;
}
public BaseLineParser getPerfBaseLine() {
return perfBaseLine;
}
public void setPerfBaseLine(BaseLineParser perfBaseLine) {
this.perfBaseLine = perfBaseLine;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getDbLastValue() {
return dbLastValue;
}
public void setDbLastValue(double dbLastValue) {
this.dbLastValue = dbLastValue;
}
public double getDbBaseLineValue() {
return dbBaseLineValue;
}
public void setDbBaseLineValue(double dbBaseLineValue) {
this.dbBaseLineValue = dbBaseLineValue;
}
public double getDbFloatRange() {
return dbFloatRange;
}
public void setDbFloatRange(double dbFloatRange) {
this.dbFloatRange = dbFloatRange;
}
public String getCaseName() {
return caseName;
}
public void setCaseName(String caseName) {
this.caseName = caseName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public boolean isHasBaseLine() {
return isHasBaseLine;
}
public void setHasBaseLine(boolean isBaseLine) {
this.isHasBaseLine = isBaseLine;
}
public boolean isHasLastValue() {
return isHasLastValue;
}
public void setHasLastValue(boolean isLastValue) {
this.isHasLastValue = isLastValue;
}
public boolean isHasFloatRange() {
return isHasFloatRange;
}
public void setHasFloatRange(boolean isFloatRange) {
this.isHasFloatRange = isFloatRange;
}
public double getTestValue() {
return testValue;
}
public void setTestValue(double testValue) {
this.testValue = testValue;
}
/**
* expectLarger
*
* @apiNote expectLarger
* @param spentTime spentTime
* @return boolean
*/
public boolean expectLarger(double spentTime) {
return expectValue(spentTime, true);
}
/**
* expectSmaller
*
* @apiNote expectSmaller
* @param spentTime spentTime
* @return boolean
*/
public boolean expectSmaller(double spentTime) {
return expectValue(spentTime, false);
}
/**
* saveResult
*
* @apiNote saveResult
* @param spentTime spentTime
*/
public void saveResult(double spentTime) {
}
/**
* initialize
*
* @apiNote init
* @return boolean
*/
private boolean init() {
if (caseName == null || perfBaseLine == null || caseName.isEmpty()) {
return false;
}
isHasBaseLine = perfBaseLine.isHasBaseLineValue(caseName);
if (!isHasBaseLine) {
return false;
} else {
dbBaseLineValue = perfBaseLine.getBaseLineValue(caseName);
}
dbLastValue = perfBaseLine.getLastValue(caseName);
isHasLastValue = perfBaseLine.isHasLastValue(caseName);
isHasFloatRange = perfBaseLine.isHasFloatRange(caseName);
if (isHasFloatRange) {
dbFloatRange = perfBaseLine.getFloatRange(caseName);
}
if (isHasFloatRange && (dbFloatRange < 0 || dbFloatRange >= 1)) {
Logger.info(String.format(Locale.ROOT, "[ ERROR ] %s has invalid float range: %s", caseName,
String.valueOf(dbFloatRange)));
isHasFloatRange = false;
}
if (!isHasFloatRange) {
dbFloatRange = 0.0;
Logger.info(String.format(Locale.ROOT, "[ WARING ] %s has NO FloatRange, default is %s", caseName,
String.valueOf(dbFloatRange)));
}
if (!isHasLastValue) {
dbLastValue = dbBaseLineValue;
Logger.info(String.format(Locale.ROOT, "[ WARING ] %s has NO LastValue, default is %s", caseName,
String.valueOf(dbLastValue)));
}
return true;
}
/**
* showBaselineInfo
*
* @apiNote showBaselineInfo
*/
public void showBaselineInfo() {
Logger.info(String.format(Locale.ROOT, "[ INFO ] %s default dbLastValue is %s", caseName,
String.valueOf(dbLastValue)));
Logger.info(String.format(Locale.ROOT, "[ INFO ] %s default dbFloatRange is %s", caseName,
String.valueOf(dbFloatRange)));
Logger.info(String.format(Locale.ROOT, "[ INFO ] %s default caseVersion is %s", caseName,
String.valueOf(caseVersion)));
Logger.info(String.format(Locale.ROOT, "[ INFO ] %s default dbBaseLineValue is %s", caseName,
String.valueOf(dbBaseLineValue)));
}
private boolean expectValue(double value, boolean isLargerBetter) {
Assert.assertTrue("expect true, but is false.", isTestCase());
boolean isTestSuccess = false;
testValue = value;
if (perfBaseLine != null && !perfBaseLine.isHasBaselineConfig()) {
isTestSuccess = true;
} else if (!isHasBaseLine) {
isTestSuccess = false;
} else if (isLargerBetter) {
double baseValue = Math.max(dbLastValue, dbBaseLineValue);
isTestSuccess = testValue >= baseValue * (1.0 - dbFloatRange) ? true : false;
} else {
double baseValue = Math.min(dbLastValue, dbBaseLineValue);
isTestSuccess = testValue <= baseValue * (1.0 + dbFloatRange) ? true : false;
}
Logger.info(String.format(Locale.ROOT, "[ PERF ] %s.%s: baseline:%f, test_result: %f", className, caseName,
dbBaseLineValue, value));
Assert.assertTrue("expect true, but is false.", isTestSuccess);
return isTestSuccess;
}
private boolean isTestCase() {
if (className == null || className.isEmpty()) {
Logger.info(String.format(Locale.ROOT,
"[ ERROR ] Failed to get test class name, class name can't be empty."));
return false;
}
if (caseName == null || caseName.isEmpty()) {
Logger.info(String.format(Locale.ROOT,
"[ ERROR ] Failed to get test case name, test case name can't be empty."));
return false;
}
Class<?> testClass;
try {
testClass = Class.forName(className);
if (testClass != null) {
List<String> listTestCase = getAllTestCase(testClass);
if (listTestCase.contains(caseName)) {
return true;
} else {
Logger.info(String.format(Locale.ROOT,
"[ ERROR ] %s Performance verification can only be called in test case functions",
className));
}
}
} catch (ClassNotFoundException e) {
Logger.info("[ ERROR ] Fail to get class by name: " + e.getMessage());
}
return false;
}
@SuppressWarnings("unchecked")
private List<String> getAllTestCase(Class<?> clazz) {
List<String> listTestCase = new ArrayList<>();
Class<? extends Annotation> junitIgnore;
Class<? extends Annotation> junitTest;
try {
junitIgnore = (Class<? extends Annotation>) Class.forName("org.junit.Ignore");
junitTest = (Class<? extends Annotation>) Class.forName("org.junit.Test");
} catch (ClassNotFoundException e) {
Logger.info("[ ERROR ] Fail to get Class by name: " + e.getMessage());
return listTestCase;
}
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
boolean isTestAnno = method.isAnnotationPresent(junitTest);
boolean isIgnoreAnno = method.isAnnotationPresent(junitIgnore);
if (isTestAnno && !isIgnoreAnno) {
listTestCase.add(method.getName());
}
}
return listTestCase;
}
@Override
public String toString() {
return "PerfTest [caseName=" + caseName + ", className=" + className + ", category=" + category
+ ", isHasBaseLine=" + isHasBaseLine + ", isHasLastValue=" + isHasLastValue + ", isHasFloatRange="
+ isHasFloatRange + ", testValue=" + testValue + ", dbLastValue=" + dbLastValue + ", dbBaseLineValue="
+ dbBaseLineValue + ", dbFloatRange=" + dbFloatRange + ", caseVersion=" + caseVersion + ", perfBaseLine="
+ perfBaseLine + "]";
}
}

View File

@ -1,40 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest;
import ohos.unittest.runner.UtTestRunner;
/**
* Testing launch APP
*/
public final class App {
/**
* Test App Constructor
*/
private App() {
}
/**
* Test Application main function
*
* @param args Test parameter
*/
public static void main(final String[] args) {
UtTestRunner testRunner = new UtTestRunner();
testRunner.run(args);
System.exit(0);
}
}

View File

@ -1,486 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.runner;
import ohos.unittest.Level;
import ohos.unittest.log.Logger;
import ohos.unittest.log.LogFile;
import ohos.unittest.runner.record.ReportGenerater;
import ohos.unittest.runner.record.TestClassInfo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Test Runner
*/
public abstract class TestRunner {
/**
* mini test parameter count
*/
private static final int MIN_ARGS_COUNT = 3;
/**
* Test class keywords for recognition
*/
private static final String CASEFILE_KEYWORDS = "Test";
/**
* Test result output dir path
*/
private static final String OUTPUT_DIR = "OUTPUT_DIR";
/**
* Test result output file path
*/
private static final String OUTPUT_FILE = "OUTPUT_FILE";
/**
* Jacoco flag
*/
private static final String COVERAGE_FLAG = "COVERAGE_FLAG";
/**
* All test class for current execution
*/
private static final String TEST_CLASS = "TEST_CLASS";
/**
* Specially specified test class for current execution
*/
private static final String EXEC_CLASS = "EXEC_CLASS";
/**
* Specially specified test method for current execution
*/
private static final String EXEC_METHOD = "EXEC_METHOD";
/**
* Specially specified test case level for current execution
*/
private static final String EXEC_LEVEL = "EXEC_LEVEL";
/**
* execute Class name
*/
private String execClassName = "";
/**
* execute Class Method name
*/
private String execMethodName = "";
/**
* execute Class Method name
*/
private ArrayList<Level> execCaseLevel = new ArrayList<>();
/**
* Filtered class for unittest test
*/
private ArrayList<String> filteredClass = new ArrayList<>();
/**
* execute Class Method name
*/
private String exportPath = "/data/test";
public String getExecClassName() {
return execClassName;
}
public String getExecMethodName() {
return execMethodName;
}
public ArrayList<Level> getExecCaseLevel() {
return execCaseLevel;
}
/**
* ZRunner Constructor
*/
public TestRunner() {
this.execClassName = "";
this.execMethodName = "";
this.filteredClass = new ArrayList<>();
this.filteredClass.add("ohos.unittest.R");
this.filteredClass.add("ohos.unittest.App");
this.filteredClass.add("ohos.unittest.AppContext");
this.filteredClass.add("ohos.unittest.MainAbility");
this.filteredClass.add("ohos.unittest.log.LogUtil");
this.filteredClass.add("ohos.unittest.TestApplication");
this.filteredClass.add("ohos.unittest.MainAbilityShellActivity");
}
private void printCorrectTips() {
Logger.info("###Run Test Error, please input corrent args" + System.lineSeparator());
Logger.info("#########Tips: Corrent Info needed" + System.lineSeparator());
Logger.info("############First arg is folder path" + System.lineSeparator());
Logger.info("############Second arg is file name" + System.lineSeparator());
Logger.info("############Others is test class full path and parameters" + System.lineSeparator());
}
/**
* Prepare Folder to saving test resutls
*
* @param strFolderPath FolderPath
* @param strFileName FileName
* @return file path
*/
private String prepareResutlFolder(String strFolderPath, String strFileName) {
String strFilePath = "";
if (strFolderPath != null && !strFolderPath.isEmpty() && strFileName != null && !strFileName.isEmpty()) {
File folder = new File(strFolderPath);
if (!folder.exists()) {
folder.mkdirs();
}
strFilePath = strFolderPath + strFileName;
File file = new File(strFilePath);
if (file.exists()) {
file.delete();
}
return strFilePath;
}
return strFilePath;
}
/**
* Run test from class name
*
* @param lstClassName list ClassName
* @return all TestClassInfo list
* @throws IOException
*/
private List<TestClassInfo> runClassByName(List<String> lstClassName) throws IOException {
List<TestClassInfo> listRecorder = new ArrayList<>();
for (String strName : lstClassName) {
String strClassName = strName.trim();
if (strClassName.isEmpty()) {
continue;
}
listRecorder.addAll(runClassByNameImp(strClassName));
}
return listRecorder;
}
/**
* execute single class
*
* @param lstClassName class name needed to execute
* @return all TestClassInfo list
* @throws IOException
*/
public abstract List<TestClassInfo> runClassByNameImp(String lstClassName) throws IOException;
/**
* Get test class name by parser Test Class parameter
*
* @param lstTestClassArg ClassArg
* @return class name list
*/
private List<String> getlstClassName(List<String> lstTestClassArg) {
List<String> lstRet = new ArrayList<>();
if (lstTestClassArg == null || lstTestClassArg.isEmpty()) {
return lstRet;
}
for (String strFullPath : lstTestClassArg) {
// get java class name
List<String> listPre = Arrays.asList(strFullPath.split(","));
for (String strTmpValue : listPre) {
String value = strTmpValue.trim();
if (value == null || value.isEmpty() || filteredClass.contains(value)) {
continue;
}
String strClass = value;
int lastDotPos = strClass.lastIndexOf(".");
if (lastDotPos > 0) {
String className = strClass.substring(lastDotPos + 1, strClass.length());
if (className.length() > CASEFILE_KEYWORDS.length()) {
String strSubFix =
className.substring(className.length() - CASEFILE_KEYWORDS.length(), className.length());
if (strSubFix.equalsIgnoreCase(CASEFILE_KEYWORDS)) {
lstRet.add(strClass);
}
}
}
}
}
return lstRet;
}
/**
* Convert test parameter to map format
*
* @param args test parameter
* @return parameter as map format
*/
private Map<String, String> convertToMap(String[] args) {
Map<String, String> mapArgs = new HashMap<>();
int length = args.length;
for (int index = 0; index < length; index++) {
String strArg = args[index].trim();
int equalPos = strArg.indexOf("=");
if (equalPos > 0) {
String strKey = strArg.substring(0, equalPos).trim();
String strValue = "";
if (strArg.length() > equalPos) {
strValue = strArg.substring(equalPos + 1, strArg.length()).trim();
}
mapArgs.put(strKey, strValue);
}
}
return mapArgs;
}
/**
* Run test by parameter
*
* @param args test parameter
*/
public void run(String[] args) {
int length = args.length;
Map<String, String> mapArgs = convertToMap(args);
String exportPathParam = mapArgs.get(OUTPUT_DIR);
String resultFileName = mapArgs.get(OUTPUT_FILE);
if (exportPathParam == null || exportPathParam.isEmpty()) {
exportPath = "/data/test";
} else {
exportPath = exportPathParam;
}
String resultFilePathLog = prepareResutlFolder(exportPath, resultFileName + ".log");
Logger.createLogFile(resultFilePathLog);
if (length < MIN_ARGS_COUNT) {
printCorrectTips();
return;
}
String resultFilePath = prepareResutlFolder(exportPath, resultFileName + ".xml");
if (resultFilePath.isEmpty()) {
Logger.info("prepare Resutl Folder error!");
return;
}
List<String> lstTestClassArg = new ArrayList<>();
String strTestClassArg = mapArgs.get(TEST_CLASS);
if (strTestClassArg != null && !strTestClassArg.isEmpty()) {
lstTestClassArg.add(strTestClassArg);
}
initExecParemater(mapArgs);
runTestCase(resultFilePath, lstTestClassArg);
String coverageFlag = mapArgs.get(COVERAGE_FLAG);
if (coverageFlag != null && !coverageFlag.isEmpty() && coverageFlag.equalsIgnoreCase("1")) {
String execFilePath = exportPath + "jacoco.exec";
if (!genJacocoExecData(execFilePath)) {
Logger.info("Generate jacoco execution data failed, "
+ "Please confirm that you have restarted the device after upgrading the system.");
}
}
String testRunStatusFile = prepareResutlFolder(exportPath, "jtest_status.txt");
List<String> fileData = new ArrayList<>();
fileData.add("Java testcase executed finished");
LogFile.createFileAndWriteData(testRunStatusFile, fileData);
}
/**
* Parser test parameter
*
* @param mapArgs test parameter
*/
private void initExecParemater(Map<String, String> mapArgs) {
if (mapArgs.isEmpty()) {
return;
}
if (mapArgs.containsKey(EXEC_CLASS) && !mapArgs.get(EXEC_CLASS).isEmpty()) {
execClassName = mapArgs.get(EXEC_CLASS);
}
if (mapArgs.containsKey(EXEC_METHOD) && !mapArgs.get(EXEC_METHOD).isEmpty()) {
execMethodName = mapArgs.get(EXEC_METHOD);
}
String strExecCaseLevels = mapArgs.get(EXEC_LEVEL);
if (strExecCaseLevels != null && !strExecCaseLevels.isEmpty()) {
String levelPrefix = "Level";
List<String> listCaseLevel = Arrays.asList(strExecCaseLevels.split(","));
for (String strCaseLevel : listCaseLevel) {
String caseLevel = strCaseLevel;
int prefixPos = strCaseLevel.indexOf(levelPrefix);
if (prefixPos < 0) {
caseLevel = strCaseLevel;
} else {
caseLevel = strCaseLevel.substring(prefixPos + levelPrefix.length(), strCaseLevel.length());
}
if ("0".equals(caseLevel)) {
this.execCaseLevel.add(Level.LEVEL_0);
}
if ("1".equals(caseLevel)) {
this.execCaseLevel.add(Level.LEVEL_1);
}
if ("2".equals(caseLevel)) {
this.execCaseLevel.add(Level.LEVEL_2);
}
if ("3".equals(caseLevel)) {
this.execCaseLevel.add(Level.LEVEL_3);
}
if ("4".equals(caseLevel)) {
this.execCaseLevel.add(Level.LEVEL_4);
}
}
}
}
/**
* Test running and save results
*
* @param strFilePath FilePath
* @param lstTestClassArg TestClassArg
* @return true or false
*/
private boolean runTestCase(String strFilePath, List<String> lstTestClassArg) {
boolean isSuccess = false;
List<String> lstTestClass = getlstClassName(lstTestClassArg);
try {
List<String> lstAllTestClass = new ArrayList<>();
lstAllTestClass.addAll(lstTestClass);
List<TestClassInfo> listTestClassInfo = runClassByName(lstAllTestClass);
ReportGenerater reportGenerater = new ReportGenerater();
reportGenerater.generateXmlReport(strFilePath, listTestClassInfo);
return true;
} catch (IOException e) {
Logger.info("generateXmlReport Exception with message:" + e.getMessage());
}
return isSuccess;
}
/**
* Generate java code coverage execution data, and save it in file
*
* @param java code coverage execution data File Path
* @return true or false
*/
private boolean genJacocoExecData(String execFilePath) {
boolean isSuccess = false;
OutputStream out = null;
try {
out = new FileOutputStream(execFilePath, false);
isSuccess = saveJacocoExecData(out);
} catch (FileNotFoundException e) {
Logger.info("GenJacocoExecData FileNotFoundException with message:" + e.getMessage());
} catch (ClassNotFoundException e) {
Logger.info("GenJacocoExecData ClassNotFoundException with message:" + e.getMessage());
} catch (NoSuchMethodException e) {
Logger.info("GenJacocoExecData NoSuchMethodException with message:" + e.getMessage());
} catch (IllegalAccessException e) {
Logger.info("GenJacocoExecData IllegalAccessException with message:" + e.getMessage());
} catch (InvocationTargetException e) {
Logger.info("GenJacocoExecData InvocationTargetException with message:" + e.getMessage());
Throwable throwable = e.getTargetException();
Logger.info("GenJacocoExecData FileNotFoundException Throwable with message:" + throwable.getMessage());
} catch (IOException e) {
Logger.info("GenJacocoExecData IOException with message:" + e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
Logger.info("GenJacocoExecData close IOException with message:" + e.getMessage());
}
}
}
return isSuccess;
}
/**
* Save java code coverage execution Data to OutputStream
*
* @param out OutputStream
* @return true or false
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws IOException
*/
private boolean saveJacocoExecData(OutputStream out) throws ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException, IOException {
boolean isSuccess = false;
Class<?> testClass = Class.forName("org.jacoco.agent.rt.RT");
if (testClass == null) {
Logger.info("saveJacocoExecData load class org.jacoco.agent.rt.RT failed");
return isSuccess;
}
Method method = testClass.getMethod("getAgent");
if (method == null) {
Logger.info("saveJacocoExecData load method getAgent() from org.jacoco.agent.rt.RT failed");
return isSuccess;
}
Object agent = method.invoke(null);
if (agent == null) {
Logger.info("saveJacocoExecData invoke method getAgent() of from org.jacoco.agent.rt.RT failed");
return isSuccess;
}
if (out == null) {
Logger.info("saveJacocoExecData OutputStream out is null");
return isSuccess;
}
Method execMethod = agent.getClass().getMethod("getExecutionData", boolean.class);
if (execMethod == null) {
Logger.info("saveJacocoExecData getExecutionData is null");
return isSuccess;
}
Object object = execMethod.invoke(agent, false);
if (object == null) {
Logger.info("saveJacocoExecData invoke getExecutionData is null");
return isSuccess;
}
if (object instanceof byte[]) {
out.write((byte[]) object);
isSuccess = true;
} else {
Logger.info("saveJacocoExecData invoke getExecutionData result is not byte[]");
}
return isSuccess;
}
}

View File

@ -1,98 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.runner;
import ohos.unittest.Level;
import ohos.unittest.log.Logger;
import ohos.unittest.log.LogFile;
import ohos.unittest.runner.record.TestClassInfo;
import ohos.unittest.runner.notification.MyCaseListener;
import ohos.unittest.runner.notification.MyRunListener;
import org.junit.runner.JUnitCore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.List;
/**
* java UT Test Runner
*/
public class UtTestRunner extends TestRunner {
public UtTestRunner() {
}
/**
* execute single class
*
* @param strClassName class name needed to execute
* @return all TestClassInfo list
* @throws IOException
*/
public List<TestClassInfo> runClassByNameImp(String strClassName) throws IOException {
List<TestClassInfo> listRecorderTmp = new ArrayList<>();
try {
Class<?> testClass = Class.forName(strClassName);
if (testClass != null) {
Logger.info("");
Logger.info(String.format(Locale.ROOT, "[==========] Running tests from %s", strClassName));
listRecorderTmp = runClasses(testClass);
Logger.info("");
}
} catch (ClassNotFoundException e) {
Logger.info("runClassByName Exception with message:" + e.getMessage());
}
return listRecorderTmp;
}
/**
* Test running by JunitCore
*
* @param classes list classes
* @return TestClassInfo list
*/
private List<TestClassInfo> runClasses(Class<?>... classes) {
List<TestClassInfo> listTestClassInfo = new ArrayList<>();
// Execute Junit test class
for (Class<?> clazz : classes) {
JUnitCore junitCore = new JUnitCore();
// Add Listener for JUnitCore to monitor Junit test class Execute results
MyRunListener listener = new MyRunListener();
junitCore.addListener(listener);
// Add ZRunCase for JUnitCore to decide witch test case should be executed
MyCaseListener caseListener = new MyCaseListener();
caseListener.setExecClassName(super.getExecClassName());
caseListener.setExecMethodName(super.getExecMethodName());
caseListener.setExecCaseLevel(super.getExecCaseLevel());
junitCore.setCaseListener(caseListener);
// Launch Junit test class running
junitCore.run(clazz);
String className = clazz.getName();
TestClassInfo testClassInfo = listener.getTestClassInfo();
testClassInfo.setClassName(className);
listTestClassInfo.add(testClassInfo);
}
return listTestClassInfo;
}
}

View File

@ -1,114 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.runner.notification;
import org.junit.runner.Description;
import java.util.ArrayList;
import ohos.unittest.listener.CaseListener;
import ohos.unittest.CaseLevel;
import ohos.unittest.Level;
/**
* User defined Junit CaseListener
*/
public class MyCaseListener extends CaseListener {
/**
* Default test class or method flag, it means "all"
*/
private static final String DEFAULT = "*";
/**
* execute Class name
*/
private String execClassName = "";
/**
* execute Class Method name
*/
private String execMethodName = "";
/**
* execute Class level list
*/
private ArrayList<Level> execCaseLevel = new ArrayList<>();
/**
* ZRunCase constructor
*/
public MyCaseListener() {
this.execClassName = "";
this.execMethodName = "";
}
public String getExecClassName() {
return execClassName;
}
public void setExecClassName(String execClassName) {
this.execClassName = execClassName;
}
public String getExecMethodName() {
return execMethodName;
}
public void setExecMethodName(String execMethodName) {
this.execMethodName = execMethodName;
}
public ArrayList<Level> getExecCaseLevel() {
return execCaseLevel;
}
public void setExecCaseLevel(ArrayList<Level> execCaseLevel) {
this.execCaseLevel = execCaseLevel;
}
@Override
public boolean isContinue(Description description) {
String strClassName = description.getClassName();
String strMethodName = description.getMethodName();
if (execClassName != null && !execClassName.isEmpty() && !execClassName.equals(DEFAULT)
&& !execClassName.equals(strClassName)) {
return false;
}
if (execMethodName != null && !execMethodName.isEmpty() && !execMethodName.equals(DEFAULT)
&& !execMethodName.equals(strMethodName)) {
return false;
}
if (this.execCaseLevel != null && !this.execCaseLevel.isEmpty()) {
CaseLevel caseLevel = description.getAnnotation(CaseLevel.class);
if (caseLevel != null && this.execCaseLevel.contains(caseLevel.level())) {
return true;
} else {
return false;
}
}
return true;
}
@Override
public String toString() {
return "ZCaseListener [execClassName=" + execClassName + ", execMethodName=" + execMethodName
+ ", execCaseLevel=" + execCaseLevel + "]";
}
}

View File

@ -1,251 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.runner.notification;
import ohos.unittest.CaseLevel;
import ohos.unittest.Level;
import ohos.unittest.TestTarget;
import ohos.unittest.log.Logger;
import ohos.unittest.runner.record.TestCaseInfo;
import ohos.unittest.runner.record.TestClassInfo;
import org.junit.Ignore;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* User defined Junit RunListener
*/
public class MyRunListener extends RunListener {
/**
* Test class execution result record
*/
private TestClassInfo testClassInfo = null;
/**
* Test class test case execution temporary result record
*/
private TestCaseInfo testCaseInfo = null;
/**
* Test class execution result record
*/
private List<TestCaseInfo> allRanTestCaseInfo = null;
/**
* Case level map
*/
private Map<Level, String> mapLevel = null;
/**
* MyRunListener Constructor
*/
public MyRunListener() {
this.allRanTestCaseInfo = new ArrayList<>();
this.mapLevel = new HashMap<>();
this.mapLevel.put(Level.DEFAULT, "");
this.mapLevel.put(Level.LEVEL_0, "0");
this.mapLevel.put(Level.LEVEL_1, "1");
this.mapLevel.put(Level.LEVEL_2, "2");
this.mapLevel.put(Level.LEVEL_3, "3");
this.mapLevel.put(Level.LEVEL_4, "4");
}
@Override
public void testRunStarted(Description description) throws Exception {
testClassInfo = new TestClassInfo();
}
@Override
public void testRunFinished(Result result) throws Exception {
testClassInfo.setSuccess(result.wasSuccessful());
testClassInfo.setRunTime(result.getRunTime());
int runCount = result.getRunCount();
testClassInfo.setRunCount(runCount);
int ignoreCount = result.getIgnoreCount();
testClassInfo.setIgnoreCount(ignoreCount);
testClassInfo.setAllRanTestCaseInfo(allRanTestCaseInfo);
String className = testClassInfo.getClassName();
long runTime = testClassInfo.getRunTime();
boolean isRunException = false;
if (runCount <= 0) {
isRunException = true;
}
if (isRunException) {
Logger.info(
String.format(Locale.ROOT, "[==========] %s", "Testsuit running exception, please check your code!"));
}
Logger.info(String.format(Locale.ROOT, "[==========] %s tests from %s (%s ms total)", String.valueOf(runCount),
className, String.valueOf(runTime)));
int passedCount = 0;
int failureCount = testClassInfo.getFailureCount();
if (runCount >= failureCount) {
passedCount = runCount - failureCount;
}
Logger.info(String.format(Locale.ROOT, "[ PASSED ] %s tests.", String.valueOf(passedCount)));
if (runCount >= failureCount && failureCount > 0) {
Logger.info(String.format(Locale.ROOT, "[ FAILED ] %s tests.", String.valueOf(failureCount)));
}
if (ignoreCount > 0) {
Logger.info(String.format(Locale.ROOT, "[ IGNORED ] %s tests.", String.valueOf(ignoreCount)));
}
}
public TestClassInfo getTestClassInfo() {
return testClassInfo;
}
public void setTestClassInfo(TestClassInfo testClassInfo) {
this.testClassInfo = testClassInfo;
}
public TestCaseInfo getTestCaseInfo() {
return testCaseInfo;
}
public void setTestCaseInfo(TestCaseInfo testCaseInfo) {
this.testCaseInfo = testCaseInfo;
}
public List<TestCaseInfo> getAllRanTestCaseInfo() {
return allRanTestCaseInfo;
}
public void setAllRanTestCaseInfo(List<TestCaseInfo> allRanTestCaseInfo) {
this.allRanTestCaseInfo = allRanTestCaseInfo;
}
public Map<Level, String> getMapLevel() {
return mapLevel;
}
public void setMapLevel(Map<Level, String> mapLevel) {
this.mapLevel = mapLevel;
}
@Override
public void testStarted(Description description) throws Exception {
iniTestCaseInfo(description);
Logger.info(
String.format(Locale.ROOT, "[ RUN ] %s.%s", description.getClassName(), description.getMethodName()));
}
private void iniTestCaseInfo(Description description) {
Ignore ignoreCase = description.getAnnotation(Ignore.class);
if (ignoreCase != null) {
return;
}
testCaseInfo = new TestCaseInfo();
testCaseInfo.setStartTime(System.currentTimeMillis());
CaseLevel caseLevel = description.getAnnotation(CaseLevel.class);
if (caseLevel != null && mapLevel.containsKey(caseLevel.level())) {
testCaseInfo.setLevel(mapLevel.get(caseLevel.level()));
} else {
testCaseInfo.setLevel("undefined");
}
TestTarget testTarget = description.getAnnotation(TestTarget.class);
if (testTarget != null) {
testCaseInfo.setTestTargetClass(testTarget.className());
testCaseInfo.setTestTargetMethod(testTarget.methodName());
}
testCaseInfo.setName(description.getMethodName());
testCaseInfo.setClassName(description.getClassName());
if (testClassInfo != null) {
String strClassName = description.getClassName();
testClassInfo.setClassName(strClassName);
}
allRanTestCaseInfo.add(testCaseInfo);
}
@Override
public void testFinished(Description description) throws Exception {
if (testCaseInfo != null) {
testCaseInfo.setEndTime(System.currentTimeMillis());
if (testCaseInfo.isSuccess()) {
Logger.info(String.format(Locale.ROOT, "[ OK ] %s.%s (%s ms)", description.getClassName(),
description.getMethodName(), String.valueOf(testCaseInfo.getTotalTime())));
} else {
if (testClassInfo != null) {
testClassInfo.setFailureCount(testClassInfo.getFailureCount() + 1);
}
Logger.info(String.format(Locale.ROOT, "[ FAILED ] %s.%s (%s ms)", description.getClassName(),
description.getMethodName(), String.valueOf(testCaseInfo.getTotalTime())));
Logger.info(testCaseInfo.getTraceInfo());
}
}
}
@Override
public void testFailure(Failure failure) throws Exception {
if (testCaseInfo != null) {
testCaseInfo.setSuccess(false);
if (failure != null && failure.getMessage() != null) {
testCaseInfo.setErrorMsg(failure.getMessage());
} else {
testCaseInfo.setErrorMsg("Message is empty");
}
if (failure != null && failure.getTrace() != null) {
testCaseInfo.setTraceInfo(failure.getTrace());
}
testCaseInfo.setEndTime(System.currentTimeMillis());
} else {
if (failure != null && failure.getMessage() != null) {
Logger.info(String.format(Locale.ROOT, "[ ERROR ] %s", failure.getMessage()));
if (testClassInfo != null) {
testClassInfo.setSuccess(false);
testClassInfo.setErrorMessage(failure.getMessage());
}
}
}
}
@Override
public void testIgnored(Description description) throws Exception {
iniTestCaseInfo(description);
if (testCaseInfo != null) {
testCaseInfo.setEndTime(System.currentTimeMillis());
}
Logger.info(String.format(Locale.ROOT, "[----------] %s.%s Ignored", description.getClassName(),
description.getMethodName()));
}
@Override
public String toString() {
return "ZRunListener [testClassInfo=" + testClassInfo + ", testCaseInfo=" + testCaseInfo
+ ", allRanTestCaseInfo=" + allRanTestCaseInfo + ", mapLevel=" + mapLevel + "]";
}
}

View File

@ -1,480 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.runner.record;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import ohos.unittest.log.Logger;
import ohos.unittest.perf.VerifySingleton;
/**
* Record test result as xml format
*/
public class ReportGenerater {
/**
* constant data:1000.0
*/
private static final double ONE_THOUSAND = 1000.0;
/**
* Test result key
*/
private static final String RESULT = "result";
/**
* Test class name key
*/
private static final String CLASSNAME = "classname";
/**
* Test result key
*/
private static final String NAME = "name";
/**
* Test execution time key
*/
private static final String TIME = "time";
/**
* File format
*/
private static final String UTF_8 = "UTF-8";
/**
* ReportGenerater Constructor
*/
public ReportGenerater() {
}
/**
* Write data to document
*
* @param document xml document object
* @param filePath xml file full path
*/
private void writeXmlFile(Document document, String filePath) {
if (!isValidate(document, filePath)) {
return;
}
TransformerFactory transFactory = TransformerFactory.newInstance();
ByteArrayOutputStream bytes = null;
try {
Transformer transformer = transFactory.newTransformer();
if (transformer == null) {
Logger.info("transformer object is null");
return;
}
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, UTF_8);
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource();
source.setNode(document);
bytes = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bytes);
transformer.transform(source, result);
String xmlStr = bytes.toString(UTF_8);
writeDataInFile(filePath, xmlStr);
} catch (IOException e) {
Logger.info("writeXmlFile IOException with message:" + e.getMessage());
} catch (TransformerConfigurationException e) {
Logger.info("writeXmlFile TransformerConfigurationException with message:" + e.getMessage());
} catch (TransformerException e) {
Logger.info("writeXmlFile TransformerException with message:" + e.getMessage());
} finally {
try {
bytes.close();
} catch (IOException e) {
Logger.info("close the bytes of writeXmlFile:" + e.getMessage());
}
}
}
/**
* Determine if Document and filePath is valid
*
* @param document XML document object
* @param filePath xml filePath
* @return true or false
*/
private boolean isValidate(Document document, String filePath) {
boolean isValidate = false;
if (document == null) {
Logger.info("Document object is null");
return isValidate;
}
if (filePath == null) {
Logger.info("filePath is null");
return isValidate;
}
String parent = new File(filePath).getParent();
if (parent == null) {
Logger.info("filePath parent not exists");
return isValidate;
}
File dirPath = new File(parent);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
return true;
}
/**
* Write data in file
*
* @param filePath file full path
* @param fileData file data
*/
private void writeDataInFile(String filePath, String fileData) {
OutputStream fos = null;
OutputStreamWriter writer = null;
try {
fos = new FileOutputStream(filePath);
writer = new OutputStreamWriter(fos, UTF_8);
writer.write(fileData);
} catch (FileNotFoundException e1) {
Logger.info("writeDataInFile FileNotFoundException with message:" + e1.getMessage());
} catch (UnsupportedEncodingException e1) {
Logger.info("writeDataInFile UnsupportedEncodingException with message:" + e1.getMessage());
} catch (IOException e) {
Logger.info("writeDataInFile IOException with message:" + e.getMessage());
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
Logger.info("writeDataInFile IOException1 with message:" + e.getMessage());
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
Logger.info("writeDataInFile IOException2 with message:" + e.getMessage());
}
}
}
}
private String convertMillisecond2Second(long time) {
double retSecond = 0;
retSecond = time / ONE_THOUSAND;
return String.format(Locale.ROOT, "%.3f", retSecond);
}
/**
* Create XML Document by data list
*
* @param listReportData TestClassInfo list
* @return XML Document object
* @throws ParserConfigurationException
*/
private Document createXmlDocument(List<TestClassInfo> listReportData) throws ParserConfigurationException {
Document doc = initXmlDocument();
if (doc == null) {
return doc;
}
// Add root element
addTestclassesExecInfoInDocument(listReportData, doc);
return doc;
}
/**
* addTestsuitExecInfo2Doc
*
* @param listReportData TestClassInfo execution list
* @param doc xml Document object
*/
private void addTestclassesExecInfoInDocument(List<TestClassInfo> listReportData, Document doc) {
Element testsuites = doc.createElement("testsuites");
if (testsuites == null) {
Logger.info("Create testsuites element error");
return;
}
doc.appendChild(testsuites);
int allRunCount = 0;
int allIgnoreCount = 0;
int allFailureCount = 0;
long allRunTime = 0L;
String strTimestamp = "";
for (TestClassInfo testClassInfo : listReportData) {
// Add sub element
Element testsuite = doc.createElement("testsuite");
if (testsuite == null) {
Logger.info("Create testsuite element error");
continue;
}
testsuites.appendChild(testsuite);
copyTestsuiteExecutedInfo(testClassInfo, testsuite);
if (strTimestamp.isEmpty()) {
strTimestamp = testClassInfo.getStartTime();
}
allRunTime += testClassInfo.getRunTime();
allRunCount += testClassInfo.getRunCount();
allFailureCount += testClassInfo.getFailureCount();
allIgnoreCount += testClassInfo.getIgnoreCount();
List<TestCaseInfo> lstTestCaseInfo = testClassInfo.getAllRanTestCaseInfo();
if (lstTestCaseInfo == null || lstTestCaseInfo.isEmpty()) {
Logger.info("Executed case is empty");
continue;
}
addTestCaseElement2TestsSuite(doc, testsuite, lstTestCaseInfo);
}
testsuites.setAttribute("tests", String.valueOf(allRunCount));
testsuites.setAttribute("failures", String.valueOf(allFailureCount));
testsuites.setAttribute("ignores", String.valueOf(allIgnoreCount));
testsuites.setAttribute("disabled", String.valueOf(0));
testsuites.setAttribute("errors", String.valueOf(0));
testsuites.setAttribute("timestamp", strTimestamp);
testsuites.setAttribute(TIME, String.valueOf(convertMillisecond2Second(allRunTime)));
testsuites.setAttribute(NAME, "");
}
/**
* copy TestSuite Executed Information
*
* @param testClassInfo source testClassInfo
* @param testsuite destination test suite
*/
private void copyTestsuiteExecutedInfo(TestClassInfo testClassInfo, Element testsuite) {
if (testClassInfo == null) {
Logger.info("testClassInfo testClassInfo is null");
return;
}
if (testsuite == null) {
Logger.info("testsuite is null");
return;
}
testsuite.setAttribute(NAME, testClassInfo.getClassName());
int runCount = testClassInfo.getRunCount();
int failureCount = testClassInfo.getFailureCount();
int ignoreCount = testClassInfo.getIgnoreCount();
testsuite.setAttribute("tests", String.valueOf(runCount));
testsuite.setAttribute("failures", String.valueOf(failureCount));
testsuite.setAttribute("ignores", String.valueOf(ignoreCount));
testsuite.setAttribute("disabled", String.valueOf(0));
testsuite.setAttribute("errors", String.valueOf(0));
long runTime = testClassInfo.getRunTime();
testsuite.setAttribute(TIME, String.valueOf(convertMillisecond2Second(runTime)));
testsuite.setAttribute(RESULT, String.valueOf(testClassInfo.isSuccess()));
if (!testClassInfo.isSuccess()) {
testsuite.setAttribute("unavailable", String.valueOf(1));
testsuite.setAttribute("message", String.valueOf(testClassInfo.getErrorMessage()));
}
}
/**
* Init Xml Document
*
* @return xml Document
* @throws ParserConfigurationException
*/
private Document initXmlDocument() throws ParserConfigurationException {
// Instance DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
if (factory == null) {
Logger.info("DocumentBuilderFactory.newInstance error");
return null;
}
factory.setNamespaceAware(true);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
// Create Document
Document doc = documentBuilder.newDocument();
if (doc == null) {
Logger.info("newDocument error");
return null;
}
return doc;
}
/**
* Add TestCase Element to TestsSuite Element for xml Document
*
* @param doc XML Document
* @param testsuite testsuite Element
* @param lstTestCaseInfo TestCaseInfo list
*/
private void addTestCaseElement2TestsSuite(Document doc, Element testsuite, List<TestCaseInfo> lstTestCaseInfo) {
for (TestCaseInfo testCaseInfo : lstTestCaseInfo) {
// Add sub element
Element testcase = doc.createElement("testcase");
if (testcase == null) {
Logger.info("Create testcase element error");
continue;
}
testcase.setAttribute(NAME, testCaseInfo.getName());
if (testCaseInfo.isIgnored()) {
testcase.setAttribute("status", "notrun");
} else {
testcase.setAttribute("status", "run");
}
testcase.setAttribute(TIME, String.valueOf(convertMillisecond2Second(testCaseInfo.getTotalTime())));
testcase.setAttribute(CLASSNAME, testCaseInfo.getClassName());
testcase.setAttribute(RESULT, String.valueOf(testCaseInfo.isSuccess()));
if (!testCaseInfo.isSuccess()) {
Element failureElemment = doc.createElement("failure");
if (testCaseInfo.getErrorMsg() != null && !testCaseInfo.getErrorMsg().isEmpty()) {
failureElemment.setAttribute("message", testCaseInfo.getErrorMsg());
} else if (testCaseInfo.getTraceInfo() != null && !testCaseInfo.getTraceInfo().isEmpty()) {
int index = testCaseInfo.getTraceInfo().indexOf("org.junit.runners.model.FrameworkMethod");
String message = testCaseInfo.getTraceInfo();
if (index > 0) {
message = testCaseInfo.getTraceInfo().substring(0, index) + " ......";
}
failureElemment.setAttribute("message", message);
} else {
failureElemment.setAttribute("message", "");
}
failureElemment.setAttribute("type", "");
failureElemment.setTextContent(testCaseInfo.getErrorMsg());
testcase.appendChild(failureElemment);
}
addPerfTestResult(doc, testcase, testCaseInfo);
testcase.setAttribute("level", String.valueOf(testCaseInfo.getLevel()));
testsuite.appendChild(testcase);
}
}
private void addPerfTestResult(Document doc, Element testcase, TestCaseInfo testCaseInfo) {
if (doc == null || testcase == null || testCaseInfo == null) {
return;
}
boolean isPerfTestcase = false;
Map<String, String> perfResult = null;
String className = testCaseInfo.getClassName();
String caseName = testCaseInfo.getName();
if (VerifySingleton.getInstance().isPerfTestcase(className, caseName)) {
isPerfTestcase = true;
perfResult = VerifySingleton.getInstance().getPerfTestResult(className,
caseName);
} else {
isPerfTestcase = false;
perfResult = null;
}
if (isPerfTestcase && perfResult != null) {
Element propertiesElemment = doc.createElement("properties");
for (Entry<String, String> entry : perfResult.entrySet()) {
Element property = doc.createElement("property");
property.setAttribute("name", entry.getKey());
property.setAttribute("value", entry.getValue());
propertiesElemment.appendChild(property);
}
Element propertyClass = doc.createElement("property");
propertyClass.setAttribute("name", "test_class");
propertyClass.setAttribute("value", testCaseInfo.getTestTargetClass());
propertiesElemment.appendChild(propertyClass);
Element propertyMethod = doc.createElement("property");
propertyMethod.setAttribute("name", "test_interface");
propertyMethod.setAttribute("value", testCaseInfo.getTestTargetMethod());
propertiesElemment.appendChild(propertyMethod);
testcase.appendChild(propertiesElemment);
}
}
/**
* Save testing results to XML file
*
* @param strReportPath xml test report file path
* @param listReportData test results
* @return true or false
*/
public boolean generateXmlReport(String strReportPath, List<TestClassInfo> listReportData) {
try {
Document document = createXmlDocument(listReportData);
writeXmlFile(document, strReportPath);
} catch (ParserConfigurationException e) {
Logger.info("generateXmlReport Exception with message:" + e.getMessage());
return false;
}
return true;
}
}
/**
* XmlConstants
*/
final class XmlConstants {
/**
* XML ACCESS_EXTERNAL_DTD
*/
public static final String ACCESS_EXTERNAL_DTD = "http://javax.xml.XMLConstants/property/accessExternalDTD";
/**
* XML ACCESS_EXTERNAL_STYLESHEET
*/
public static final String ACCESS_EXTERNAL_STYLESHEET =
"http://javax.xml.XMLConstants/property/accessExternalStylesheet";
private XmlConstants() {
}
}

View File

@ -1,209 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.runner.record;
/**
* Test Case Information
*/
public class TestCaseInfo {
/**
* Test method execution begin time, in milliseconds
*/
private long startTime = 0L;
/**
* Test method execution end time, in milliseconds
*/
private long endTime = 0L;
/**
* Test method execution total time, in milliseconds
*/
private long totalTime = 0L;
/**
* Test case level
*/
private String level = "";
/**
* Test class name
*/
private String className = "";
/**
* Test method(case) name
*/
private String name = "";
/**
* Test method execution result(true/false)
*/
private boolean isSuccess = true;
/**
* Test method ignored flag(true/false)
*/
private boolean isIgnored = false;
/**
* Test method execution errorMsg
*/
private String errorMsg = "";
/**
* Test method execution traceInfo
*/
private String traceInfo = "";
/**
* test Target Class name
*/
private String testTargetClass = "";
/**
* test Target Method name
*/
private String testTargetMethod = "";
/**
* CaseInfo Constructor
*/
public TestCaseInfo() {
super();
this.name = "";
this.level = "";
this.className = "";
this.startTime = 0;
this.endTime = 0;
this.totalTime = 0;
this.errorMsg = "";
this.testTargetClass = "";
this.testTargetMethod = "";
this.isIgnored = false;
this.isSuccess = true;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getEndTime() {
return endTime;
}
public void setEndTime(long endTime) {
this.endTime = endTime;
}
/**
* Get case total execution time
*
* @return total execution time
*/
public long getTotalTime() {
totalTime = endTime - startTime;
return totalTime;
}
public void setTotalTime(long totalTime) {
this.totalTime = totalTime;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccessed) {
this.isSuccess = isSuccessed;
}
public boolean isIgnored() {
return isIgnored;
}
public void setIgnored(boolean isIgnoredFlag) {
this.isIgnored = isIgnoredFlag;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getTraceInfo() {
return traceInfo;
}
public void setTraceInfo(String traceInfo) {
this.traceInfo = traceInfo;
}
public String getTestTargetMethod() {
return testTargetMethod;
}
public void setTestTargetMethod(String testTargetMethod) {
this.testTargetMethod = testTargetMethod;
}
public String getTestTargetClass() {
return testTargetClass;
}
public void setTestTargetClass(String testTargetClass) {
this.testTargetClass = testTargetClass;
}
@Override
public String toString() {
return "TestCaseInfo [startTime=" + startTime + ", endTime=" + endTime + ", totalTime=" + totalTime + ", level="
+ level + ", className=" + className + ", name=" + name + ", isSuccess=" + isSuccess + ", isIgnored="
+ isIgnored + ", testTargetClass=" + testTargetClass + ", testTargetMethod=" + testTargetMethod
+ ", errorMsg=" + errorMsg + ", traceInfo=" + traceInfo + "]";
}
}

View File

@ -1,160 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.runner.record;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Test class test method execution result statistics
*/
public class TestClassInfo {
/**
* start time for test class execution
*/
private String startTime;
/**
* Test class
*/
private String className = "";
/**
* errorMessage for test class execution
*/
private String errorMessage;
/**
* Test function execution result list
*/
private List<TestCaseInfo> allRanTestCaseInfo = null;
/**
* Test class test result
*/
private boolean isSuccess = false;
/**
* Test class all use case execution time total, in milliseconds
*/
private long runTime = 0L;
/**
* Test class test function execution quantity
*/
private int runCount = 0;
/**
* Test class test function execution failure quantity
*/
private int failureCount = 0;
/**
* Test class test function execution ignores quantity
*/
private int ignoreCount = 0;
/**
* TestClassInfo Constructor
*/
public TestClassInfo() {
super();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
this.startTime = df.format(new Date());
}
public List<TestCaseInfo> getAllRanTestCaseInfo() {
return allRanTestCaseInfo;
}
public void setAllRanTestCaseInfo(List<TestCaseInfo> allRanTestCaseInfo) {
this.allRanTestCaseInfo = allRanTestCaseInfo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccessed) {
this.isSuccess = isSuccessed;
}
public long getRunTime() {
return runTime;
}
public void setRunTime(long runTime) {
this.runTime = runTime;
}
public int getRunCount() {
return runCount;
}
public void setRunCount(int runCount) {
this.runCount = runCount;
}
public int getFailureCount() {
return failureCount;
}
public void setFailureCount(int failureCount) {
this.failureCount = failureCount;
}
public int getIgnoreCount() {
return ignoreCount;
}
public void setIgnoreCount(int ignoreCount) {
this.ignoreCount = ignoreCount;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public String toString() {
return "TestClassInfo [startTime=" + startTime + ", className=" + className + ", errorMessage=" + errorMessage
+ ", allRanTestCaseInfo=" + allRanTestCaseInfo + ", isSuccess=" + isSuccess + ", runTime=" + runTime
+ ", runCount=" + runCount + ", failureCount=" + failureCount + ", ignoreCount=" + ignoreCount + "]";
}
}

View File

@ -1,37 +0,0 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/config/ohos/rules.gni")
java_library("test_app_executor_java") {
final_jar_path = "$root_out_dir/test_platform/libs/test_app_executor_java.jar"
aosp_deps = [ "maple:framework" ]
deps = [
"//test/developertest/libs/jtr/common/java:test_executor_java",
"//test/developertest/libs/jtr/shell/java:test_app_shell_context_java",
]
external_deps = [
"ability:abilitykit_java",
"intent:intent_java",
"appexecfwk:appexecfwk_base_java",
"appexecfwk:appexecfwk_java",
]
external_deps += [
"ability:abilitykit_java_maple",
"intent:intent_java_maple",
"appexecfwk:appexecfwk_base_java_maple",
"appexecfwk:appexecfwk_java_maple",
]
}

View File

@ -1,35 +0,0 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/config/ohos/rules.gni")
java_library("test_app_shell_context_java") {
emma_never_instrument = true
java_files = [
"//test/developertest/libs/jtr/shell/java/src/ohos/unittest/log/HiLogUtil.java",
]
final_jar_path =
"$root_out_dir/test_platform/libs/test_app_shell_context_java.jar"
aosp_deps = [ "maple:framework" ]
deps = []
external_deps = [
"ability:abilitykit_java",
"hilog:hilog_java",
]
external_deps += [
"ability:abilitykit_java_maple",
"hilog:hilog_maple_java",
]
}

View File

@ -1,122 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ohos.unittest.log;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import java.util.Locale;
/**
* HiLog Util
*/
public class HiLogUtil {
/**
* Log tag
*/
private static final String TAG_LOG = "AppUnitTest";
/**
* HiLogLabel instance
*/
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0, HiLogUtil.TAG_LOG);
/**
* Log format
*/
private static final String LOG_FORMAT = " %s: %s";
/**
* LogUtil Constructor
*/
private HiLogUtil() {
}
/**
* Print debug log
*
* @param classType class name
* @param msg log message
*/
@SuppressWarnings("rawtypes")
public static void debug(Class classType, String msg) {
HiLog.debug(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, classType.getSimpleName(), msg));
}
/**
* Print info log
*
* @param classType class name
* @param msg log message
*/
@SuppressWarnings("rawtypes")
public static void info(Class classType, String msg) {
HiLog.info(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, classType.getSimpleName(), msg));
}
/**
* Print info log
*
* @param className class name
* @param msg log message
*/
public static void info(String className, String msg) {
HiLog.info(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, className, msg));
}
/**
* Print error log
*
* @param classType class name
* @param msg log message
*/
@SuppressWarnings("rawtypes")
public static void error(Class classType, String msg) {
HiLog.error(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, classType.getSimpleName(), msg));
}
/**
* Print error log
*
* @param className class name
* @param msg log message
*/
public static void error(String className, String msg) {
HiLog.error(LABEL_LOG, String.format(Locale.ROOT, LOG_FORMAT, className, msg));
}
/**
* print String info to log
*
* @param classType class name
* @param msg log message
*/
@SuppressWarnings("rawtypes")
public static void printInfo(Class classType, String msg) {
HiLog.info(LABEL_LOG, "classType is %s, message is %s", classType, msg);
}
/**
* print String error to log
*
* @param classType class name
* @param msg log message
*/
@SuppressWarnings("rawtypes")
public static void printError(Class classType, String msg) {
HiLog.error(LABEL_LOG, "classType is %s, message is %s", classType, msg);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 394 B

View File

@ -18,6 +18,7 @@
import os
from xdevice import platform_logger
from core.utils import scan_support_product
from core.config.config_manager import UserConfigManager
from core.build.select_targets import SelectTargets
from core.build.build_testcases import BuildTestcases
@ -68,9 +69,8 @@ class BuildManager(object):
return build_result
def _compile_testcases(self, project_root_path, para):
is_doublefwk = UserConfigManager().get_user_config_flag(
"common", "doublefwk")
if not is_doublefwk:
all_product_list = scan_support_product()
if para.productform not in all_product_list:
from core.build.build_lite_manager import BuildLiteManager
build_lite_manager = BuildLiteManager()
return build_lite_manager.exec_build_test(para)

View File

@ -17,16 +17,20 @@
#
import os
import sys
import json
import shutil
import subprocess
import platform
from xdevice import platform_logger
from core.utils import get_build_output_path
from core.utils import scan_support_product
from core.common import is_open_source_product
from core.config.config_manager import UserConfigManager
BUILD_FILEPATH = "build/build_scripts/build_ohos.sh"
BUILD_LITE_FILE = "build/lite/build.py"
BUILD_FILEPATH = "./build.sh"
BUILD_LITE = "build/lite/build.py"
BUILD_TARGET_PLATFORM = "build_platform=\"%s\""
LOG = platform_logger("BuildTestcases")
@ -38,8 +42,6 @@ class BuildTestcases(object):
self.project_rootpath = project_rootpath
user_manager = UserConfigManager()
self.is_doublefwk = user_manager.get_user_config_flag(
"common", "doublefwk")
self.is_build_example = user_manager.get_user_config_flag(
"build", "example")
self.build_paramter_dic = user_manager.get_user_config(
@ -61,12 +63,12 @@ class BuildTestcases(object):
@classmethod
def _get_testcase_outname_by_productform(cls, productform):
if productform == "phone":
if productform == "phone" or is_open_source_product(productform):
return ""
testcase_outpath = ""
toolchain_filepath = os.path.join(
get_build_output_path(),
get_build_output_path(productform),
"build_configs",
"platforms_info",
"toolchain_to_variant.json")
@ -78,17 +80,26 @@ class BuildTestcases(object):
LOG.warning("The %s file load error." %
toolchain_filepath)
data_dic = []
paltform_toolchain_dic = data_dic.get("paltform_toolchain")
paltform_toolchain_dic = data_dic.get("platform_toolchain")
testcase_outpath = paltform_toolchain_dic.get(productform, "")
pos = testcase_outpath.rfind(':') + 1
testcase_outpath = testcase_outpath[pos:len(testcase_outpath)]
return testcase_outpath
def _delete_testcase_dir(self, productform):
package_out_dir = os.path.join(
get_build_output_path(),
"packages",
productform, "tests")
if is_open_source_product(productform):
package_out_dir = os.path.join(
get_build_output_path(productform),
"packages",
"phone",
"tests")
else:
package_out_dir = os.path.join(
get_build_output_path(productform),
"packages",
productform,
"tests")
LOG.info("package_out_dir=%s" % package_out_dir)
if os.path.exists(package_out_dir):
shutil.rmtree(package_out_dir)
@ -105,7 +116,7 @@ class BuildTestcases(object):
return
curr_productform_outdir = os.path.join(
get_build_output_path(),
get_build_output_path(productform),
curr_productform_outname,
"tests")
LOG.info("curr_productform_outdir=%s" % curr_productform_outdir)
@ -113,14 +124,21 @@ class BuildTestcases(object):
shutil.rmtree(curr_productform_outdir)
def _merge_testcase_dir(self, productform):
package_out_dir = os.path.join(
get_build_output_path(),
"packages",
productform)
if is_open_source_product(productform):
package_out_dir = os.path.join(
get_build_output_path(productform),
"packages",
"phone")
else:
package_out_dir = os.path.join(
get_build_output_path(productform),
"packages",
productform)
if platform.system() == 'Windows':
package_out_dir = os.path.join(package_out_dir, "tests")
phone_out_dir = os.path.join(get_build_output_path(), "tests")
phone_out_dir = os.path.join(get_build_output_path(productform),
"tests")
if os.path.exists(phone_out_dir):
self._copy_folder(phone_out_dir, package_out_dir)
@ -130,37 +148,42 @@ class BuildTestcases(object):
return
curr_productform_outdir = os.path.join(
get_build_output_path(),
get_build_output_path(productform),
curr_productform_outname,
"tests")
LOG.info("curr_productform_outdir=%s" % curr_productform_outdir)
if os.path.exists(curr_productform_outdir):
self._copy_folder(curr_productform_outdir, package_out_dir)
def _execute_build_command(self, command):
def _execute_build_command(self, productform, command):
build_result = False
current_path = os.getcwd()
os.chdir(self.project_rootpath)
command.append("--product-name")
command.append(productform)
command.append("--export-para")
command.append("PYCACHE_ENABLE:true")
if os.path.exists(BUILD_FILEPATH):
build_command = [BUILD_FILEPATH]
build_command.extend(command)
LOG.info("build_command: %s" % str(build_command))
if subprocess.call(build_command) == 0:
build_result = True
else:
build_result = False
else:
if not self.is_doublefwk:
build_result = self._execute_build_lite_command()
# scan standard and large system
all_scan_product_list = scan_support_product()
if productform in all_scan_product_list:
if os.path.exists(BUILD_FILEPATH):
build_command = [BUILD_FILEPATH]
build_command.extend(command)
LOG.info("build_command: %s" % str(build_command))
if subprocess.call(build_command) == 0:
build_result = True
else:
build_result = False
else:
LOG.warning("Error: The %s is not exist" % BUILD_FILEPATH)
else:
build_result = self._execute_build_lite_cmd()
os.chdir(current_path)
return build_result
def _execute_build_lite_command(self):
if os.path.exists(BUILD_LITE_FILE):
def _execute_build_lite_cmd(self):
if os.path.exists(BUILD_LITE):
temp_user_manager = UserConfigManager()
build_command_config = \
temp_user_manager.get_user_config("build", "board_info")
@ -171,82 +194,55 @@ class BuildTestcases(object):
LOG.info("execute build lite command success")
return True
else:
LOG.error("execute build lite command failed")
LOG.error("execute build lite command success")
except IOError as exception:
LOG.error("build lite test case failed, exception=%s"
% exception)
else:
LOG.warning("Error: The %s is not exist" % BUILD_LITE_FILE)
return True
LOG.warning("Error: The %s is not exist" % BUILD_LITE)
return False
def build_testcases(self, productform, target):
command = []
target_os = self.build_paramter_dic.get("target_os")
command.append("target_os=" + target_os)
target_cpu = self.build_paramter_dic.get("target_cpu")
command.append("target_cpu=" + target_cpu)
if self.is_doublefwk:
command.append("double_framework=true")
if self.is_build_example:
command.append("--gn-args")
command.append("build_example=true")
command.append("target_platform=" + productform.lower())
command.append("build_target=" + target)
command.append("--build-target")
command.append(target)
command.append("--gn-args")
command.append(BUILD_TARGET_PLATFORM % productform)
self._delete_testcase_dir(productform)
build_result = self._execute_build_command(command)
build_result = self._execute_build_command(productform, command)
self._merge_testcase_dir(productform)
return build_result
def build_gn_file(self, productform):
command = []
target_os = self.build_paramter_dic.get("target_os")
command.append("target_os=" + target_os)
target_cpu = self.build_paramter_dic.get("target_cpu")
command.append("target_cpu=" + target_cpu)
if self.is_doublefwk:
command.append("double_framework=true")
if self.is_build_example:
command.append("--gn-args")
command.append("build_example=true")
command.append("target_platform=" + productform.lower())
command.append("build_only_gn=true")
return self._execute_build_command(command)
command.append("--build-only-gn")
command.append("--gn-args")
command.append(BUILD_TARGET_PLATFORM % productform)
return self._execute_build_command(productform, command)
def build_version(self, productform):
command = []
target_os = self.build_paramter_dic.get("target_os")
command.append("target_os=" + target_os)
target_cpu = self.build_paramter_dic.get("target_cpu")
command.append("target_cpu=" + target_cpu)
if self.is_doublefwk:
command.append("double_framework=true")
command.append("target_platform=" + productform.lower())
command.append("build_target=make_all")
return self._execute_build_command(command)
command.append("--build-target")
command.append("make_all")
command.append("--gn-args")
command.append(BUILD_TARGET_PLATFORM % productform)
return self._execute_build_command(productform, command)
def build_all_testcases(self):
command = []
if self.is_doublefwk:
command.append("double_framework=true")
if self.is_build_example:
command.append("--gn-args")
command.append("build_example=true")
command.append("build_target=make_test")
command.append("target_platform=all")
command.append("--build-target")
command.append("make_test")
command.append("--gn-args")
command.append(BUILD_TARGET_PLATFORM % "all")
return self._execute_build_command(command)

View File

@ -64,7 +64,7 @@ class SelectTargets(object):
part_path_list = []
default_part_path = os.path.join(
get_build_output_path(),
get_build_output_path(productform),
"module_list_files",
origin_part_name)
if os.path.exists(default_part_path):
@ -72,7 +72,7 @@ class SelectTargets(object):
if build_out_dir != ".":
product_part_path = os.path.join(
get_build_output_path(),
get_build_output_path(productform),
build_out_dir,
"module_list_files",
origin_part_name)

View File

@ -23,6 +23,7 @@ from core.constants import ToolCommandType
from core.utils import get_file_list
from core.utils import get_file_list_by_postfix
from core.utils import get_build_output_path
from core.utils import scan_support_product
from core.config.config_manager import UserConfigManager
from core.config.config_manager import FrameworkConfigManager
from core.config.parse_parts_config import ParsePartsConfig
@ -159,8 +160,10 @@ def select_user_input(data_list):
def select_productform():
select_value = "phone"
productform_list = \
scan_product_list = scan_support_product()
config_product_list = \
FrameworkConfigManager().get_framework_config("productform")
productform_list = scan_product_list + config_product_list
if len(productform_list) != 0:
print("Please select the current tested product form:")
for index, element in enumerate(productform_list):
@ -214,15 +217,18 @@ def display_show_info(para_list, productform):
#############################################################################
#############################################################################
def get_module_list_from_output_dir():
def get_module_list_from_output_dir(product_form):
module_path_list = []
if UserConfigManager().get_user_config_flag("common", "doublefwk"):
module_list_file_path = os.path.join(get_build_output_path(),
"module_list_files")
all_product_list = scan_support_product()
if product_form in all_product_list:
module_list_file_path = os.path.join(
get_build_output_path(product_form),
"module_list_files")
else:
module_list_file_path = os.path.join(get_build_output_path(),
"test_info",
"module_list_files")
module_list_file_path = os.path.join(
get_build_output_path(product_form),
"test_info",
"module_list_files")
print(module_list_file_path)
if os.path.exists(module_list_file_path):
file_list = get_file_list_by_postfix(module_list_file_path, ".mlf")
@ -257,11 +263,11 @@ def get_module_list_from_case_dir(test_case_dir):
return file_list
def get_module_list():
def get_module_list(product_form):
module_path_list = []
testcase_dir = UserConfigManager().get_test_cases_dir()
if testcase_dir == "":
module_path_list = get_module_list_from_output_dir()
module_path_list = get_module_list_from_output_dir(product_form)
else:
module_path_list = get_module_list_from_case_dir(testcase_dir)
return module_path_list
@ -273,8 +279,10 @@ def get_module_list():
def show_product_list():
print("List of currently supported productform:")
productform_list = FrameworkConfigManager().get_framework_config(
"productform")
scan_product_list = scan_support_product()
config_product_list = \
FrameworkConfigManager().get_framework_config("productform")
productform_list = scan_product_list + config_product_list
if 0 != len(productform_list):
for index, element in enumerate(productform_list):
print(" %d. %s" % (index + 1, element))
@ -322,10 +330,10 @@ def show_partname_list(product_form):
print(" %d. %s" % (index + 1, element))
def show_module_list():
def show_module_list(product_form):
print("List of currently supported module names:")
subsystem_name_list = []
subsystem_module_list = get_module_list()
subsystem_module_list = get_module_list(product_form)
for item in subsystem_module_list:
if item != "":
@ -373,7 +381,7 @@ def display_show_command_info(command, product_form="phone"):
elif command == CMD_KEY_PARTLIST:
show_partname_list(product_form)
elif command == CMD_KEY_MODULELIST:
show_module_list()
show_module_list(product_form)
else:
print("This command is not support.")

View File

@ -17,6 +17,7 @@
#
from xdevice import platform_logger
from core.utils import scan_support_product
from core.config.config_manager import FrameworkConfigManager
LOG = platform_logger("Console")
@ -75,12 +76,6 @@ class Parameter(object):
LOG.warning("The productform is incorrect.")
return False
productform_list = FrameworkConfigManager().get_framework_config(
"productform")
if options.productform not in productform_list:
LOG.warning("The productform you entered is incorrect.")
return False
if "" != options.testcase and "" != options.testlevel:
LOG.warning("The -l and -c parameters cannot exist at the \
same time.")

View File

@ -26,6 +26,8 @@ from xdevice import get_plugin
from xdevice import platform_logger
from xdevice import Scheduler
from core.utils import get_build_output_path
from core.utils import scan_support_product
from core.common import is_open_source_product
from core.command.parameter import Parameter
from core.testcase.testcase_manager import TestCaseManager
from core.config.config_manager import UserConfigManager
@ -141,7 +143,7 @@ class Run(object):
target_out_path = UserConfigManager().get_test_cases_dir()
if target_out_path == "":
target_out_path = os.path.join(
get_build_output_path(),
get_build_output_path(product_form),
"packages",
product_form)
target_out_path = os.path.abspath(target_out_path)
@ -178,21 +180,30 @@ class Run(object):
def get_tests_out_path(cls, product_form):
tests_out_path = UserConfigManager().get_test_cases_dir()
if tests_out_path == "":
if UserConfigManager().get_user_config_flag("common", "doublefwk"):
tests_out_path = os.path.abspath(os.path.join(
get_build_output_path(),
"packages",
product_form,
"tests"))
all_product_list = scan_support_product()
if product_form in all_product_list:
if is_open_source_product(product_form):
tests_out_path = os.path.abspath(os.path.join(
get_build_output_path(product_form),
"packages",
"phone",
"tests"))
else:
tests_out_path = os.path.abspath(os.path.join(
get_build_output_path(product_form),
"packages",
product_form,
"tests"))
else:
tests_out_path = os.path.join(get_build_output_path(), "test")
tests_out_path = os.path.join(
get_build_output_path(product_form), "test")
return tests_out_path
@classmethod
def get_coverage_outpath(cls, options):
coverage_out_path = ""
if options.coverage:
coverage_out_path = get_build_output_path()
coverage_out_path = get_build_output_path(options.productform)
if coverage_out_path == "":
coverage_out_path = UserConfigManager().get_user_config(
"coverage").get("outpath", "")

View File

@ -22,7 +22,7 @@ __all__ = ["get_source_code_root_path"]
def is_source_code_root_path(path):
check_name_list = ["build/build_scripts/build_ohos.sh",
check_name_list = ["./build.sh",
"build",
"prebuilts"]
for item in check_name_list:
@ -44,3 +44,10 @@ def get_source_code_root_path(path):
break
code_root_path = os.path.dirname(code_root_path)
return code_root_path
def is_open_source_product(product_name):
open_source_products = ["Hi3516DV300"]
if product_name in open_source_products:
return True
return False

View File

@ -20,6 +20,7 @@ import os
import json
from core.utils import get_build_output_path
from core.common import is_open_source_product
from core.config.config_manager import UserConfigManager
@ -31,15 +32,14 @@ class ParsePartsConfig(object):
self.productform = productform
self.subsystem_infos, self.part_infos = self.get_infos_data()
@classmethod
def get_config_file_path(cls):
def get_config_file_path(self):
manager = UserConfigManager()
testcase_dir = manager.get_test_cases_dir()
if testcase_dir == "":
if sys.source_code_root_path != "":
config_filepath = os.path.join(
get_build_output_path(),
get_build_output_path(self.productform),
"build_configs",
"infos_for_testfwk.json")
else:
@ -63,7 +63,11 @@ class ParsePartsConfig(object):
print("Error: json file load error.")
return None, None
product_data_dic = data_dic.get(self.productform, None)
# open source branch, the part form of all product is "phone"
if is_open_source_product(self.productform):
product_data_dic = data_dic.get("phone", None)
else:
product_data_dic = data_dic.get(self.productform, None)
if product_data_dic is None:
print("Error: product_data_dic is None.")
return None, None

479
src/core/driver/drivers.py Executable file
View File

@ -0,0 +1,479 @@
#!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import time
import platform
from dataclasses import dataclass
from xdevice import DeviceTestType
from xdevice import DeviceLabelType
from xdevice import ExecuteTerminate
from xdevice import DeviceError
from xdevice import IDriver
from xdevice import platform_logger
from xdevice import Plugin
from core.utils import get_decode
from core.config.resource_manager import ResourceManager
__all__ = [
"CppTestDriver",
"disable_keyguard",
"GTestConst"]
LOG = platform_logger("Drivers")
DEFAULT_TEST_PATH = "/%s/%s/" % ("data", "test")
TIME_OUT = 900 * 1000
##############################################################################
##############################################################################
class DisplayOutputReceiver:
def __init__(self):
self.output = ""
self.unfinished_line = ""
def _process_output(self, output, end_mark="\n"):
content = output
if self.unfinished_line:
content = "".join((self.unfinished_line, content))
self.unfinished_line = ""
lines = content.split(end_mark)
if content.endswith(end_mark):
return lines[:-1]
else:
self.unfinished_line = lines[-1]
return lines[:-1]
def __read__(self, output):
self.output = "%s%s" % (self.output, output)
lines = self._process_output(output)
for line in lines:
line = line.strip()
if line:
LOG.info(get_decode(line))
def __error__(self, message):
pass
def __done__(self, result_code="", message=""):
pass
@dataclass
class GTestConst(object):
exec_para_filter = "--gtest_filter"
exec_para_level = "--gtest_testsize"
def get_device_log_file(report_path, serial=None, log_name="device_log"):
from xdevice import Variables
log_path = os.path.join(report_path, Variables.report_vars.log_dir)
os.makedirs(log_path, exist_ok=True)
serial = serial or time.time_ns()
device_file_name = "{}_{}.log".format(log_name, serial)
device_log_file = os.path.join(log_path, device_file_name)
return device_log_file
def get_level_para_string(level_string):
level_list = list(set(level_string.split(",")))
level_para_string = ""
for item in level_list:
if not item.isdigit():
continue
item = item.strip(" ")
level_para_string += ("Level%s," % item)
level_para_string = level_para_string.strip(",")
return level_para_string
def get_result_savepath(testsuit_path, result_rootpath):
findkey = os.sep + "tests" + os.sep
filedir, _ = os.path.split(testsuit_path)
pos = filedir.find(findkey)
if -1 != pos:
subpath = filedir[pos + len(findkey):]
pos1 = subpath.find(os.sep)
if -1 != pos1:
subpath = subpath[pos1 + len(os.sep):]
result_path = os.path.join(result_rootpath, "result", subpath)
else:
result_path = os.path.join(result_rootpath, "result")
else:
result_path = os.path.join(result_rootpath, "result")
if not os.path.exists(result_path):
os.makedirs(result_path)
LOG.info("result_savepath = " + result_path)
return result_path
# all testsuit common Unavailable test result xml
def _create_empty_result_file(filepath, filename, error_message):
error_message = str(error_message)
error_message = error_message.replace("\"", "")
error_message = error_message.replace("<", "")
error_message = error_message.replace(">", "")
error_message = error_message.replace("&", "")
if filename.endswith(".hap"):
filename = filename.split(".")[0]
if not os.path.exists(filepath):
with open(filepath, "w", encoding='utf-8') as file_desc:
time_stamp = time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime())
file_desc.write('<?xml version="1.0" encoding="UTF-8"?>\n')
file_desc.write(
'<testsuites tests="0" failures="0" '
'disabled="0" errors="0" timestamp="%s" '
'time="0" name="AllTests">\n' % time_stamp)
file_desc.write(
' <testsuite name="%s" tests="0" failures="0" '
'disabled="0" errors="0" time="0.0" '
'unavailable="1" message="%s">\n' %
(filename, error_message))
file_desc.write(' </testsuite>\n')
file_desc.write('</testsuites>\n')
return
def _unlock_screen(device):
device.execute_shell_command("svc power stayon true")
time.sleep(1)
def _unlock_device(device):
device.execute_shell_command("input keyevent 82")
time.sleep(1)
device.execute_shell_command("wm dismiss-keyguard")
time.sleep(1)
def _lock_screen(device):
device.execute_shell_command("svc power stayon false")
time.sleep(1)
def disable_keyguard(device):
_unlock_screen(device)
_unlock_device(device)
def _sleep_according_to_result(result):
if result:
time.sleep(1)
##############################################################################
##############################################################################
class ResultManager(object):
def __init__(self, testsuit_path, config):
self.testsuite_path = testsuit_path
self.config = config
self.result_rootpath = self.config.report_path
self.device = self.config.device
if testsuit_path.endswith(".hap"):
self.device_testpath = self.config.test_hap_out_path
else:
self.device_testpath = self.config.target_test_path
self.testsuite_name = os.path.basename(self.testsuite_path)
self.is_coverage = False
def set_is_coverage(self, is_coverage):
self.is_coverage = is_coverage
def get_test_results(self, error_message=""):
# Get test result files
filepath = self.obtain_test_result_file()
if not os.path.exists(filepath):
_create_empty_result_file(filepath, self.testsuite_name,
error_message)
if "benchmark" == self.config.testtype[0]:
if self.device.is_directory(
os.path.join(self.device_testpath, "benchmark")):
self._obtain_benchmark_result()
# Get coverage data files
if self.is_coverage:
self.obtain_coverage_data()
return filepath
def _obtain_benchmark_result(self):
benchmark_root_dir = os.path.abspath(
os.path.join(self.result_rootpath, "benchmark"))
benchmark_dir = os.path.abspath(
os.path.join(benchmark_root_dir,
self.get_result_sub_save_path(),
self.testsuite_name))
if not os.path.exists(benchmark_dir):
os.makedirs(benchmark_dir)
print("benchmark_dir =%s", benchmark_dir)
if not self.device.pull_file(
os.path.join(self.device_testpath, "benchmark"),
benchmark_dir):
os.rmdir(benchmark_dir)
return benchmark_dir
def get_result_sub_save_path(self):
find_key = os.sep + "tests" + os.sep
file_dir, _ = os.path.split(self.testsuite_path)
pos = file_dir.find(find_key)
subpath = ""
if -1 != pos:
subpath = file_dir[pos + len(find_key):]
pos1 = subpath.find(os.sep)
if -1 != pos1:
subpath = subpath[pos1 + len(os.sep):]
print("subpath = " + subpath)
return subpath
def obtain_test_result_file(self):
result_save_path = get_result_savepath(self.testsuite_path,
self.result_rootpath)
result_file_path = os.path.join(result_save_path,
"%s.xml" % self.testsuite_name)
result_josn_file_path = os.path.join(result_save_path,
"%s.json" % self.testsuite_name)
if self.testsuite_path.endswith('.hap'):
remote_result_file = os.path.join(self.device_testpath,
"testcase_result.xml")
remote_json_result_file = os.path.join(self.device_testpath,
"%s.json" % self.testsuite_name)
else:
remote_result_file = os.path.join(self.device_testpath,
"%s.xml" % self.testsuite_name)
remote_json_result_file = os.path.join(self.device_testpath,
"%s.json" % self.testsuite_name)
if self.device.is_file_exist(remote_result_file):
self.device.pull_file(remote_result_file, result_file_path)
elif self.device.is_file_exist(remote_json_result_file):
self.device.pull_file(remote_json_result_file,
result_josn_file_path)
result_file_path = result_josn_file_path
else:
LOG.error("%s not exist", remote_result_file)
return result_file_path
def make_empty_result_file(self, error_message=""):
result_savepath = get_result_savepath(self.testsuite_path,
self.result_rootpath)
result_filepath = os.path.join(result_savepath, "%s.xml" %
self.testsuite_name)
if not os.path.exists(result_filepath):
_create_empty_result_file(result_filepath,
self.testsuite_name, error_message)
def is_exist_target_in_device(self, path, target):
if platform.system() == "Windows":
command = '\"ls -l %s | grep %s\"' % (path, target)
else:
command = "ls -l %s | grep %s" % (path, target)
check_result = False
stdout_info = self.device.execute_shell_command(command)
if stdout_info != "" and stdout_info.find(target) != -1:
check_result = True
return check_result
def obtain_coverage_data(self):
cov_root_dir = os.path.abspath(os.path.join(
self.result_rootpath,
"..",
"coverage",
"data",
"exec"))
target_name = "obj"
cxx_cov_path = os.path.abspath(os.path.join(
self.result_rootpath,
"..",
"coverage",
"data",
"cxx",
self.testsuite_name))
if self.is_exist_target_in_device(DEFAULT_TEST_PATH, target_name):
if not os.path.exists(cxx_cov_path):
os.makedirs(cxx_cov_path)
src_file = os.path.join(DEFAULT_TEST_PATH, target_name)
self.device.pull_file(src_file, cxx_cov_path, is_create=True)
##############################################################################
##############################################################################
@Plugin(type=Plugin.DRIVER, id=DeviceTestType.cpp_test)
class CppTestDriver(IDriver):
"""
CppTest is a Test that runs a native test package on given device.
"""
# test driver config
config = None
result = ""
def __check_environment__(self, device_options):
if len(device_options) == 1 and device_options[0].label is None:
return True
if len(device_options) != 1 or \
device_options[0].label != DeviceLabelType.phone:
return False
return True
def __check_config__(self, config):
pass
def __result__(self):
return self.result if os.path.exists(self.result) else ""
def __execute__(self, request):
try:
self.config = request.config
self.config.target_test_path = DEFAULT_TEST_PATH
self.config.device = request.config.environment.devices[0]
suite_file = request.root.source.source_file
LOG.debug("Testsuite FilePath: %s" % suite_file)
if not suite_file:
LOG.error("test source '%s' not exists" %
request.root.source.source_string)
return
if not self.config.device:
result = ResultManager(suite_file, self.config)
result.set_is_coverage(False)
result.make_empty_result_file(
"No test device is found. ")
return
serial = request.config.device.__get_serial__()
device_log_file = get_device_log_file(
request.config.report_path,
serial)
with open(device_log_file, "a", encoding="UTF-8") as file_pipe:
self.config.device.start_catch_device_log(file_pipe)
self._init_gtest()
self._run_gtest(suite_file)
finally:
self.config.device.stop_catch_device_log()
def _init_gtest(self):
self.config.device.hdc_command("remount")
self.config.device.execute_shell_command(
"rm -rf %s" % self.config.target_test_path)
self.config.device.execute_shell_command(
"mkdir -p %s" % self.config.target_test_path)
def _run_gtest(self, suite_file):
from xdevice import Variables
filename = os.path.basename(suite_file)
test_para = self._get_test_para(self.config.testcase,
self.config.testlevel,
self.config.testtype,
self.config.target_test_path,
filename)
is_coverage_test = True if self.config.coverage else False
# push testsuite file
self.config.device.push_file(suite_file, self.config.target_test_path)
# push resource files
resource_manager = ResourceManager()
resource_data_dic, resource_dir = \
resource_manager.get_resource_data_dic(suite_file)
resource_manager.process_preparer_data(resource_data_dic, resource_dir,
self.config.device)
# execute testcase
if not self.config.coverage:
command = "cd %s; rm -rf %s.xml; chmod +x *; ./%s %s" % (
self.config.target_test_path,
filename,
filename,
test_para)
else:
coverage_outpath = self.config.coverage_outpath
strip_num = len(coverage_outpath.split(os.sep)) - 1
command = "cd %s; rm -rf %s.xml; chmod +x *; GCOV_PREFIX=. " \
"GCOV_PREFIX_STRIP=%s ./%s %s" % \
(self.config.target_test_path,
filename,
str(strip_num),
filename,
test_para)
result = ResultManager(suite_file, self.config)
result.set_is_coverage(is_coverage_test)
try:
# get result
display_receiver = DisplayOutputReceiver()
self.config.device.execute_shell_command(
command,
receiver=display_receiver,
timeout=TIME_OUT,
retry=0)
return_message = display_receiver.output
except (ExecuteTerminate, DeviceError) as exception:
return_message = str(exception.args)
self.result = result.get_test_results(return_message)
resource_manager.process_cleaner_data(resource_data_dic,
resource_dir,
self.config.device)
@staticmethod
def _get_test_para(testcase,
testlevel,
testtype,
target_test_path,
filename):
if "benchmark" == testtype[0]:
test_para = (" --benchmark_out_format=json"
" --benchmark_out=%s%s.json") % (
target_test_path, filename)
return test_para
if "" != testcase and "" == testlevel:
test_para = "%s=%s" % (GTestConst.exec_para_filter, testcase)
elif "" == testcase and "" != testlevel:
level_para = get_level_para_string(testlevel)
test_para = "%s=%s" % (GTestConst.exec_para_level, level_para)
else:
test_para = ""
return test_para
##############################################################################
##############################################################################

View File

@ -219,7 +219,7 @@ class LiteUnitTest(IDriver):
timeout=5, receiver=None)
if xml_file in result:
return True
time.sleep(1)
time.sleep(5)
return False
def show_help_info(self):

View File

@ -70,36 +70,70 @@ def get_device_log_file(report_path, serial=None, log_name="device_log"):
return device_log_file
def get_build_output_path():
def get_build_output_path(product_form):
if sys.source_code_root_path == "":
return ""
manager = UserConfigManager()
if manager.get_user_config_flag("common", "doublefwk"):
para_dic = manager.get_user_config("build", "paramter")
target_os = para_dic.get("target_os", "")
target_cpu = para_dic.get("target_cpu", "")
variant = para_dic.get("variant", "")
build_output_name = "%s-%s-%s" % (target_os, target_cpu, variant)
if build_output_name == "ohos-arm64-release":
build_output_name = "release"
standard_large_system_list = scan_support_product()
property_info = parse_product_info(product_form)
if product_form in standard_large_system_list:
if property_info is not None:
target_os = property_info.get("target_os")
target_cpu = property_info.get("target_cpu")
build_output_name = "%s-%s-%s" % (target_os, target_cpu, "release")
else:
return ""
else:
para_dic = manager.get_user_config("build", "board_info")
para_dic = UserConfigManager().get_user_config("build", "board_info")
board_series = para_dic.get("board_series", "")
board_type = para_dic.get("board_type", "")
board_product = para_dic.get("board_product", "")
first_build_output = "%s_%s" % (board_series, board_type)
second_build_output = "%s_%s" % (board_product, first_build_output)
build_output_name = os.path.join(first_build_output,
fist_build_output = "%s_%s" % (board_series, board_type)
second_build_output = "%s_%s" % (board_product, fist_build_output)
build_output_name = os.path.join(fist_build_output,
second_build_output)
build_output_path = os.path.join(
sys.source_code_root_path,
"out",
build_output_name)
build_output_path = os.path.join(sys.source_code_root_path,
"out",
build_output_name)
return build_output_path
def scan_support_product():
# scan standard and large system info
product_form_dir = os.path.join(sys.source_code_root_path,
"productdefine",
"common",
"products")
productform_list = []
if os.path.exists(product_form_dir):
for product_form_file in os.listdir(product_form_dir):
if os.path.isdir(os.path.join(product_form_dir,
product_form_file)):
continue
product_file = os.path.basename(product_form_file)
if product_file.endswith(".build") or "parts" in product_file or \
"x86_64" in product_file or "32" in product_file:
continue
product_name, _ = os.path.splitext(product_file)
productform_list.append(product_name)
return productform_list
def parse_product_info(product_form):
build_prop = os.path.join(sys.source_code_root_path,
"out",
"build_configs",
product_form,
"preloader",
"build.prop")
with open(build_prop, 'r') as pro_file:
properties = {}
for line in pro_file:
if line.find('=') > 0:
strs = line.replace('\n', '').split('=')
properties[strs[0]] = strs[1]
return properties
def is_32_bit_test():
manager = UserConfigManager()
para_dic = manager.get_user_config("build", "paramter")

View File

@ -49,6 +49,20 @@ def _init_global_config():
"python"))
sys.path.insert(2, sys.pytest_dir)
sys.adapter_dir = os.path.abspath(os.path.join(
sys.framework_root_dir,
"adapter"
"aw",
"python"))
sys.path.insert(3, sys.adapter_dir)
sys.hmh_script = os.path.abspath(os.path.join(
sys.framework_root_dir,
"..",
"test-tools",
"hmh"))
sys.path.insert(4, sys.hmh_script)
sys.framework_res_dir = sys.framework_root_dir
sys.exec_dir = sys.framework_root_dir
@ -84,6 +98,11 @@ def _load_internal_plugins():
except (ModuleNotFoundError, ImportError):
pass
try:
import script.report
_iter_module_plugins([script.report])
except (ModuleNotFoundError, ImportError):
pass
_init_global_config()
del _init_global_config