Skip to content

Commit

Permalink
Added refactoring and code clean up for java files (#230)
Browse files Browse the repository at this point in the history
  • Loading branch information
bipin-k committed Jan 16, 2023
1 parent a51e34f commit 7b9ebdb
Show file tree
Hide file tree
Showing 20 changed files with 92 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,11 @@ public DeviceStabilityMonitor deviceStabilityMonitor(AgentWebSocketClientService
public void onDeviceInactive(DeviceInfo deviceInfo) {
//send message to master to update device status
JSONObject data = new JSONObject();
data.put(Const.AgentConfig.serial_param, deviceInfo.getSerialNum());
data.put(Const.AgentConfig.SERIAL_PARAM, deviceInfo.getSerialNum());
if (DeviceInfo.UNSTABLE.equals(deviceInfo.getStatus())) {
data.put(Const.AgentConfig.status_param, deviceInfo.getStatus());
data.put(Const.AgentConfig.STATUS_PARAM, deviceInfo.getStatus());
} else {
data.put(Const.AgentConfig.status_param, DeviceInfo.OFFLINE);
data.put(Const.AgentConfig.STATUS_PARAM, DeviceInfo.OFFLINE);
}
agentWebSocketClientService.send(Message.ok(Const.Path.DEVICE_STATUS, data));
}
Expand All @@ -185,11 +185,11 @@ public void onDeviceInactive(DeviceInfo deviceInfo) {
public void onDeviceConnected(DeviceInfo deviceInfo) {
//send message to master to update device status
JSONObject data = new JSONObject();
data.put(Const.AgentConfig.serial_param, deviceInfo.getSerialNum());
data.put(Const.AgentConfig.SERIAL_PARAM, deviceInfo.getSerialNum());
if (DeviceInfo.UNSTABLE.equals(deviceInfo.getStatus())) {
data.put(Const.AgentConfig.status_param, deviceInfo.getStatus());
data.put(Const.AgentConfig.STATUS_PARAM, deviceInfo.getStatus());
} else {
data.put(Const.AgentConfig.status_param, DeviceInfo.ONLINE);
data.put(Const.AgentConfig.STATUS_PARAM, DeviceInfo.ONLINE);
}
agentWebSocketClientService.send(Message.ok(Const.Path.DEVICE_STATUS, data));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public boolean isCancelled() {
checkTestTaskCancel(testTask);
listener.startRecording(testTask.getTimeOutSecond());
String result = startInstrument(deviceInfo, testTask.getTestScope(), testTask.getTestSuite(), testTask.getTestPkgName(), testTask.getTestRunnerName(), reportLogger, instrumentationResultParser, testTask.getTimeOutSecond(), testTask.getInstrumentationArgs());
if (Const.TaskResult.error_device_offline.equals(result)) {
if (Const.TaskResult.ERROR_DEVICE_OFFLINE.equals(result)) {
testTaskRunCallback.onDeviceOffline(testTask);
return;
}
Expand Down Expand Up @@ -119,7 +119,7 @@ public String startInstrument(DeviceInfo deviceInfo, String scope, String suiteN
logger.info(">> adb -s {} shell {}", deviceInfo.getSerialNum(), LogUtils.scrubSensitiveArgs(command));
}
adbOperateUtil.executeShellCommandOnDevice(deviceInfo, command, receiver, testTimeOutSec);
return Const.TaskResult.success;
return Const.TaskResult.SUCCESS;
} catch (Exception e) {
if (logger != null) {
logger.error(e.getMessage(), e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
public void testRunFailed(String errorMessage) {
logEnter("testRunFailed", errorMessage);
testRun.addNewTimeTag("testRunFailed", System.currentTimeMillis() - recordingStartTimeMillis);
Assert.isTrue(deviceInfo.isAlive(), Const.TaskResult.error_device_offline);
Assert.isTrue(deviceInfo.isAlive(), Const.TaskResult.ERROR_DEVICE_OFFLINE);
super.testRunFailed(errorMessage);
testRun.setTestErrorMessage(errorMessage);
if (errorMessage != null && errorMessage.toLowerCase(Locale.US).contains("process crash")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,16 +144,16 @@ public void runSmartTestOnce(int i, DeviceInfo deviceInfo, TestRun testRun, Logg
String resString = smartTestUtil.runPYFunction(smartTestParam, logger);
Assert.notEmpty(resString, "Run Smart Test Failed!");
res = JSONObject.parseObject(resString);
isSuccess = res.getBoolean(Const.SmartTestConfig.successTag);
crashStack = res.getJSONArray(Const.SmartTestConfig.appExpTag);
isSuccess = res.getBoolean(Const.SmartTestConfig.SUCCESS_TAG);
crashStack = res.getJSONArray(Const.SmartTestConfig.APP_EXP_TAG);
} catch (Exception e) {
logger.error(e.getMessage(), e);
res.put(Const.SmartTestConfig.taskExpTag, e.getMessage());
res.put(Const.SmartTestConfig.TASK_EXP_TAG, e.getMessage());
}
if (!isSuccess) {
ongoingSmartTest.setStatusCode(AndroidTestUnit.StatusCodes.FAILURE);
ongoingSmartTest.setSuccess(false);
ongoingSmartTest.setStack(res.getString(Const.SmartTestConfig.taskExpTag));
ongoingSmartTest.setStack(res.getString(Const.SmartTestConfig.TASK_EXP_TAG));
testRun.addNewTimeTag(ongoingSmartTest.getTitle() + ".fail", System.currentTimeMillis() - recordingStartTimeMillis);
testRun.oneMoreFailure();
} else if (crashStack != null && crashStack.size() > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ public class SmartTestUtil {

public SmartTestUtil(String location) {
File testBaseDir = new File(location);
String name = Const.SmartTestConfig.zipFileName;
String folderName = Const.SmartTestConfig.zipFolderName;
String name = Const.SmartTestConfig.ZIP_FILE_NAME;
String folderName = Const.SmartTestConfig.ZIP_FOLDER_NAME;

folderPath = testBaseDir.getAbsolutePath() + "/" + Const.SmartTestConfig.zipFolderName + "/";
stringFolderPath = testBaseDir.getAbsolutePath() + "/" + Const.SmartTestConfig.stringFolderName + "/";
folderPath = testBaseDir.getAbsolutePath() + "/" + Const.SmartTestConfig.ZIP_FOLDER_NAME + "/";
stringFolderPath = testBaseDir.getAbsolutePath() + "/" + Const.SmartTestConfig.STRING_FOLDER_NAME
+ "/";

try {
InputStream resourceAsStream = FileUtils.class.getClassLoader().getResourceAsStream(name);
Expand All @@ -55,8 +56,8 @@ public SmartTestUtil(String location) {
e.printStackTrace();
}
initStringPool();
filePath = folderPath + Const.SmartTestConfig.pyFileName;
String requireFilePath = folderPath + Const.SmartTestConfig.requireFileName;
filePath = folderPath + Const.SmartTestConfig.PY_FILE_NAME;
String requireFilePath = folderPath + Const.SmartTestConfig.REQUIRE_FILE_NAME;
String[] command = new String[]{"pip3", "install", "-r", requireFilePath};
try {
Process proc = Runtime.getRuntime().exec(command);
Expand Down Expand Up @@ -96,7 +97,7 @@ public String runPYFunction(SmartTestParam smartTestParam, Logger logger) throws
}

public JSONObject analysisRes(JSONObject data) {
JSONObject coverage = data.getJSONObject(Const.SmartTestConfig.coverageTag);
JSONObject coverage = data.getJSONObject(Const.SmartTestConfig.COVERAGE_TAG);
JSONObject result = new JSONObject();
Set<String> activityKeys = coverage.keySet();
int totalActivity = activityKeys.size();
Expand All @@ -106,11 +107,11 @@ public JSONObject analysisRes(JSONObject data) {

for (String activityKey : activityKeys) {
JSONObject activityInfo = coverage.getJSONObject(activityKey);
if (!activityInfo.getBoolean(Const.SmartTestConfig.visitTag)) {
if (!activityInfo.getBoolean(Const.SmartTestConfig.VISIT_TAG)) {
continue;
}
Set<String> elementKeys = activityInfo.keySet();
elementKeys.remove(Const.SmartTestConfig.visitTag);
elementKeys.remove(Const.SmartTestConfig.VISIT_TAG);
totalElement = totalElement + elementKeys.size();
for (String elementKey : elementKeys) {
if (activityInfo.getBoolean(elementKey)) {
Expand All @@ -132,7 +133,7 @@ public void initStringPool() {
throw new RuntimeException("mkdirs fail for: " + stringDir);
}
}
String[] fileNames = Const.SmartTestConfig.stringFileNames.split(",");
String[] fileNames = Const.SmartTestConfig.STRING_FILE_NAMES.split(",");
for (String fileName : fileNames) {
creatTxtFile(stringFolderPath, fileName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ public void restartAgent(String packageFileName, String path) {

packageFileName = packageFileName == null ? "" : packageFileName;
if (deviceManager instanceof IOSDeviceManager && !((IOSDeviceManager) deviceManager).isDeviceConnectedToWindows()) {
scriptPath = appOptions.getLocation() + File.separator + Const.AgentConfig.restartFileMac;
scriptPath = appOptions.getLocation() + File.separator + Const.AgentConfig.RESTART_FILE_MAC;
restartArgs = new String[]{"sh", scriptPath, packageFileName};
} else {
scriptPath = appOptions.getLocation() + File.separator + Const.AgentConfig.restartFileWin;
scriptPath = appOptions.getLocation() + File.separator + Const.AgentConfig.RESTART_FILE_WIN;
restartArgs = new String[]{"cmd.exe", "/c", "Start", scriptPath, packageFileName};
}
File scriptFile = new File(scriptPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public void onMessage(Message message) {
break;
}
JSONObject deviceData = (JSONObject) message.getBody();
DeviceInfo device = deviceControlService.updateDeviceScope(deviceData.getString(Const.AgentConfig.serial_param), deviceData.getBoolean(Const.AgentConfig.scope_param));
DeviceInfo device = deviceControlService.updateDeviceScope(deviceData.getString(Const.AgentConfig.SERIAL_PARAM), deviceData.getBoolean(Const.AgentConfig.SCOPE_PARAM));
response = new Message();
response.setPath(message.getPath());
response.setSessionId(message.getSessionId());
Expand Down Expand Up @@ -122,7 +122,7 @@ public void onMessage(Message message) {
break;
}
JSONObject data = (JSONObject) message.getBody();
testTaskEngineService.cancelTestTaskById(data.getString(Const.AgentConfig.task_id_param));
testTaskEngineService.cancelTestTaskById(data.getString(Const.AgentConfig.TASK_ID_PARAM));
break;
case Const.Path.TEST_TASK_RUN:
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ protected Set<DeviceInfo> chooseDevices(TestTaskSpec testTaskSpec, TestRunner ru
Set<DeviceInfo> allActiveConnectedDevice = deviceManager.getDeviceList(log);
log.info("Choosing devices from {}", allActiveConnectedDevice.size());

if (identifier.startsWith(Const.DeviceGroup.groupPre)) {
if (identifier.startsWith(Const.DeviceGroup.GROUP_NAME_PREFIX)) {
List<String> devices = Arrays.asList(testTaskSpec.groupDevices.split(","));
return allActiveConnectedDevice.stream()
.filter(adbDeviceInfo -> devices.contains(adbDeviceInfo.getSerialNum()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public void getUserPhoto(@CurrentSecurityContext SysUser requestor,
try {
InputStream inputStream = null;
if (requestor == null || requestor.getAccessToken() == null) {
inputStream = FileUtils.class.getClassLoader().getResourceAsStream(Const.Path.default_photo);
inputStream = FileUtils.class.getClassLoader().getResourceAsStream(Const.Path.DEFAULT_PHOTO);
} else {
inputStream = authUtil.requestPhoto(requestor.getAccessToken());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public Result<DeviceGroup> createGroup(@CurrentSecurityContext SysUser requestor
if (deviceGroupService.isGroupNameIllegal(groupName)) {
return Result.error(HttpStatus.BAD_REQUEST.value(), "groupName should contain A-Z, a-z and 0-9 only");
}
String groupRealName = Const.DeviceGroup.groupPre + groupName;
String groupRealName = Const.DeviceGroup.GROUP_NAME_PREFIX + groupName;
if (deviceGroupService.checkGroupName(groupRealName)) {
return Result.error(HttpStatus.FORBIDDEN.value(), "groupName already exist!");
}
Expand Down Expand Up @@ -244,7 +244,7 @@ public Result<AccessInfo> generateDeviceToken(@CurrentSecurityContext SysUser re
if (deviceIdentifier == null || "".equals(deviceIdentifier)) {
return Result.error(HttpStatus.BAD_REQUEST.value(), "deviceIdentifier is required");
}
if (deviceIdentifier.startsWith(Const.DeviceGroup.groupPre)) {
if (deviceIdentifier.startsWith(Const.DeviceGroup.GROUP_NAME_PREFIX)) {
if (!deviceGroupService.checkGroupAuthorization(requestor, deviceIdentifier, true)) {
return Result.error(HttpStatus.UNAUTHORIZED.value(), "Authentication failed");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ private void handleQualifiedAgentMessage(Message message, AgentSessionInfo saved
case Const.Path.DEVICE_STATUS:
if (message.getBody() instanceof JSONObject) {
JSONObject data = (JSONObject) message.getBody();
updateDeviceStatus(data.getString(Const.AgentConfig.serial_param), data.getString(Const.AgentConfig.status_param), data.getString(Const.AgentConfig.task_id_param));
updateDeviceStatus(data.getString(Const.AgentConfig.SERIAL_PARAM), data.getString(Const.AgentConfig.STATUS_PARAM), data.getString(Const.AgentConfig.TASK_ID_PARAM));
}
break;
case Const.Path.ACCESS_INFO:
Expand Down Expand Up @@ -247,7 +247,7 @@ private void handleQualifiedAgentMessage(Message message, AgentSessionInfo saved
case Const.Path.TEST_TASK_RETRY:
if (message.getBody() instanceof TestTask) {
TestTask testTask = (TestTask) message.getBody();
if (testTask.getRetryTime() == Const.AgentConfig.retry_time) {
if (testTask.getRetryTime() == Const.AgentConfig.RETRY_TIME) {
testTask.setStatus(TestTask.TestStatus.EXCEPTION);
testTask.setTestErrorMsg("Device offline!");
testDataService.saveTestTaskData(testTask);
Expand Down Expand Up @@ -279,7 +279,7 @@ public void cancelTestTaskById(String taskId, String reason) {
Set<String> agentIds = testDataService.cancelTaskById(taskId, reason);
JSONObject data = new JSONObject();
Message message = new Message();
data.put(Const.AgentConfig.task_id_param, taskId);
data.put(Const.AgentConfig.TASK_ID_PARAM, taskId);
message.setPath(Const.Path.TEST_TASK_CANCEL);
message.setBody(data);
for (String agentId : agentIds) {
Expand Down Expand Up @@ -492,8 +492,8 @@ public void updateDeviceScope(String deviceSerial, Boolean isPrivate) {
Assert.notNull(agentSession.session, "agent session error");

JSONObject data = new JSONObject();
data.put(Const.AgentConfig.serial_param, deviceSerial);
data.put(Const.AgentConfig.scope_param, isPrivate);
data.put(Const.AgentConfig.SERIAL_PARAM, deviceSerial);
data.put(Const.AgentConfig.SCOPE_PARAM, isPrivate);

Message message = new Message();
message.setPath(Const.Path.DEVICE_UPDATE);
Expand Down Expand Up @@ -659,7 +659,7 @@ public JSONObject runTestTaskBySpec(TestTaskSpec testTaskSpec) {
} else if (TestTask.TestRunningType.T2C_JSON_TEST.equals(testTaskSpec.runningType)) {
result = runT2CTest(testTaskSpec);
} else {
if (testTaskSpec.deviceIdentifier.startsWith(Const.DeviceGroup.groupPre)) {
if (testTaskSpec.deviceIdentifier.startsWith(Const.DeviceGroup.GROUP_NAME_PREFIX)) {
result = runTestTaskByGroup(testTaskSpec);
} else {
result = runTestTaskByDevice(testTaskSpec);
Expand Down Expand Up @@ -776,8 +776,8 @@ private JSONObject runTestTaskByGroup(TestTaskSpec testTaskSpec) {
checkAccessInfo(testTaskSpec.deviceIdentifier, testTaskSpec.accessKey);
}
Map<String, List<String>> agents = new HashMap<>();
boolean isSingle = Const.DeviceGroup.singleType.equals(testTaskSpec.groupTestType);
boolean isAll = Const.DeviceGroup.allType.equals(testTaskSpec.groupTestType);
boolean isSingle = Const.DeviceGroup.SINGLE_TYPE.equals(testTaskSpec.groupTestType);
boolean isAll = Const.DeviceGroup.ALL_TYPE.equals(testTaskSpec.groupTestType);
Message message = new Message();
message.setPath(Const.Path.TEST_TASK_RUN);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

Expand All @@ -41,9 +40,9 @@ public DeviceGroup createGroup(String teamId, String teamName, String groupName,
DeviceGroup deviceGroup = new DeviceGroup();
deviceGroup.setTeamId(teamId);
deviceGroup.setTeamName(teamName);
deviceGroup.setGroupName(Const.DeviceGroup.groupPre + groupName);
deviceGroup.setGroupName(Const.DeviceGroup.GROUP_NAME_PREFIX + groupName);
deviceGroup.setGroupDisplayName(groupName);
deviceGroup.setGroupType(Const.DeviceGroup.userGroup);
deviceGroup.setGroupType(Const.DeviceGroup.USER_GROUP);
return deviceGroupRepository.save(deviceGroup);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public Boolean isQueueEmpty() {
public Boolean isDeviceFree(String deviceIdentifier) {
Set<String> relatedIdentifiers = new HashSet<>();
relatedIdentifiers.add(deviceIdentifier);
if (deviceIdentifier.startsWith(Const.DeviceGroup.groupPre)) {
if (deviceIdentifier.startsWith(Const.DeviceGroup.GROUP_NAME_PREFIX)) {
relatedIdentifiers.addAll(deviceAgentManagementService.queryDeviceByGroup(deviceIdentifier));
} else {
relatedIdentifiers.addAll(deviceAgentManagementService.queryGroupByDevice(deviceIdentifier));
Expand Down Expand Up @@ -148,7 +148,7 @@ public boolean checkTestTaskTeamConsistency(TestTaskSpec testTaskSpec) {
return testTaskSpec.teamId.equals(agent.getTeamId());
} else {
String deviceIdentifier = testTaskSpec.deviceIdentifier;
if (deviceIdentifier.startsWith(Const.DeviceGroup.groupPre)) {
if (deviceIdentifier.startsWith(Const.DeviceGroup.GROUP_NAME_PREFIX)) {
DeviceGroup deviceGroup = deviceGroupService.getGroupByName(deviceIdentifier);
if (deviceGroup == null) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ void testDeviceGroupManagement() {
SysTeam defaultTeam = sysTeamService.getOrCreateDefaultTeam(Const.DefaultTeam.DEFAULT_TEAM_NAME);

deviceGroupService.createGroup(defaultTeam.getTeamId(), defaultTeam.getTeamName(), groupName, null);
DeviceGroup group = deviceGroupService.getGroupByName(Const.DeviceGroup.groupPre + groupName);
DeviceGroup group = deviceGroupService.getGroupByName(Const.DeviceGroup.GROUP_NAME_PREFIX + groupName);
Assertions.assertNotNull(group, "Insert group failed!");

deviceGroupService.saveRelation(groupName, deviceSerial);
Expand Down
Loading

0 comments on commit 7b9ebdb

Please sign in to comment.