Python+PyQt5 Uos+飞腾处理器,实现LTP测试

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Aging_Test_Ltp.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.
import configparser
import json
import logging
import os
import platform
import shutil
import subprocess
import sys
import requests
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QThread, pyqtSignal, QMetaObject, Qt
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox

class Worker(QtCore.QObject):
    finished = pyqtSignal(bool, str)  # 发送测试结果和消息的信号

    def __init__(self, testTime, parent=None):
        super().__init__(parent)
        self.testTime = testTime
        self.system_name = ''  # 系统环境
        self.cpu_architecture = ''  # CPU框架
        # 读取系统信息
        self.system_name = self.get_system_name().lower()
        # 读取CPU框架
        self.cpu_architecture = self.get_cpu_architecture()

    def run(self):
        # 在这里执行老化测试
        result = self.run_ltp_stress_test(self.testTime)
        if result:
            self.finished.emit(True, "老化测试 LTP 通过!!")
        else:
            self.finished.emit(False, "老化测试 LTP 失败!!")

    def run_ltp_stress_test(self, testTime):
        original_dir = os.getcwd()
        log_file = os.path.join(original_dir, "ltpstress.log")
        try:
            if self.cpu_architecture == 'arm':
                testscripts_dir = "ltp/testscripts"
                if not os.path.exists(testscripts_dir):
                    return False, "Error: ltp/testscripts does not exist"

                os.chdir(testscripts_dir)
                result = subprocess.run(["sudo", "./ltpstress.sh", "-n", "-t", str(testTime), "-p", "-l", log_file],check=True)
                if result.returncode == 0:
                    return True, f"LTP stress test started. Logging to {log_file}."
                else:
                    return False, "LTP stress test failed."
            else:
                testscripts_dir = "/opt/ltp/testscripts"
                if not os.path.exists(testscripts_dir):
                    return False, "Error: /opt/ltp/testscripts does not exist"

                os.chdir(testscripts_dir)
                ltpstress_command = f"sudo ./ltpstress.sh -l {log_file} -t {testTime} -n"
                result = subprocess.run(ltpstress_command, shell=True, text=True)
                if result.returncode == 0:
                    return True, f"LTP stress test started. Logging to {log_file}."
                else:
                    return False, "LTP stress test failed."
        except Exception as e:
            return False, f"run_ltp_stress_test Info Err: {str(e)}"
        finally:
            os.chdir(original_dir)

    # 使用os库检测系统名称
    def get_system_name(self):
        try:
            with open("/etc/os-release") as f:
                for line in f:
                    if line.startswith("NAME="):
                        # 移除行中的"NAME="和可能的引号
                        return line.strip().replace('NAME=', '').replace('"', '')
        except FileNotFoundError:
            pass
        return "Unknown"

    def get_cpu_architecture(self):
        # 使用platform库检测CPU架构
        arch = platform.machine()
        # 简化为常用架构名称
        if arch in ['x86_64']:
            return 'x86_64'
        elif arch in ['arm', 'arm64', 'aarch64']:
            return 'arm'
        else:
            return 'unknown'

class Aging_Test_Ltp(QWidget):
    # 定义颜色代码
    COLOR_SUCCESS = "\033[1;32;43m"
    COLOR_ERROR = "\033[1;31m"
    COLOR_RESET = "\033[0m"

    def __init__(self):
        super().__init__()
        self.setupUi()
        self.testArgs = []  # 测试参数信息
        self.itemName = ''  # 项目名称
        self.testStandardArgs = ''  # 测试标准参数
        self.Product_name = ''  # 产品名称
        self.Process_name = ''  # 工序名称
        self.SN = ''  # 获取SN条码
        self.TestWebApi = 'N/A'  # 测试WebApi接口
        self.info_update_counter = 0  # 初始化计数器
        self.total_seconds=0#测试总时间
        self.elapsed_time=0#设置进度初始值
        self.logger = None
        self.config = None
        self.system_name = ''  # 系统环境
        self.cpu_architecture = ''  # CPU框架

        self.delete_file('ltpstress.log')  # 删除ltp老化测试日志文件
        self.loggerrinfo()  # 创建日志信息
        self.GetitemName()  # 获取项目名称
        self.gather_log_upload_data()  # 获取产品名称、工序名称、SN条码信息

        # 读取系统信息
        self.system_name = self.get_system_name().lower()
        # 读取CPU框架
        self.cpu_architecture = self.get_cpu_architecture()

        # 读取配置
        self.config.read('./Conf/config.conf', encoding='utf-8')  # 读取配置文件,如果配置文件不存在则创建

        # 读取Test_WebApi接口配置
        self.TestWebApi = self.config.get('TestWepApi', 'url')

        if self.ReadJsonTestArgs() == True:
            self.install_ltp()  # 安装ltp老化环境
            self.total_seconds = int(self.testStandardArgs) * 60 * 60
            self.lbl_readargs.setText(f'{self.total_seconds}秒')
            self.progressBar.setMaximum(self.total_seconds)  # 设置进度条的最大值

            self.timer = QTimer(self)  # 创建定时器
            self.timer.timeout.connect(self.update_time)  # 定时器超时连接到更新时间的槽函数
            # self.elapsed_time = 0  # 初始化经过时间
            self.timer.start(1000)  # 每1000毫秒(即每秒)触发一次

            # 创建工作线程
            self.thread = QThread()
            self.worker = Worker(self.testStandardArgs)
            self.worker.moveToThread(self.thread)
            self.worker.finished.connect(self.test_complete)
            self.thread.started.connect(self.worker.run)
            self.thread.start()
        else:
            self.ShowLog(f"Read {self.itemName} Test Args Fail!!", False)
            sys.exit(1)

    # 使用os库检测系统名称
    def get_system_name(self):
        try:
            with open("/etc/os-release") as f:
                for line in f:
                    if line.startswith("NAME="):
                        # 移除行中的"NAME="和可能的引号
                        return line.strip().replace('NAME=', '').replace('"', '')
        except FileNotFoundError:
            pass
        return "Unknown"

    def get_cpu_architecture(self):
        # 使用platform库检测CPU架构
        arch = platform.machine()
        # 简化为常用架构名称
        if arch in ['x86_64']:
            return 'x86_64'
        elif arch in ['arm', 'arm64', 'aarch64']:
            return 'arm'
        else:
            return 'unknown'

    def test_complete(self, success, message):
        if success:
            self.timer.stop()
            self.lbl_showinfo.setText("老化测试完成!")
            self.UpdateJsonTestArgs(self.itemName, self.testStandardArgs, 'PASS')
            self.process_ltplogfile_upload()
            self.ShowLog(message, True)
            sys.exit(0)
        else:
            self.UpdateJsonTestArgs(self.itemName, self.testStandardArgs, 'FAIL')
            self.ShowLog(message, False)
            sys.exit(1)
    #时钟计时
    def update_time(self):
        if self.elapsed_time>=self.total_seconds:
            self.timer.stop()  # 停止定时器
        else:
            self.elapsed_time += 1  # 秒数加1
            self.lcdNumber.display(self.elapsed_time)  # 显示在LCD数码管
            self.progressBar.setValue(self.elapsed_time)  # 更新进度条
            self.update_info_message()  # 更新信息显示

    #更新显示文字动态效果
    def update_info_message(self):
        try:
            self.info_update_counter += 1
            if self.info_update_counter % 5 == 0:
                dots_count = (self.info_update_counter // 5) % 4
                message = f"老化测试中{'.' * dots_count}"
                QMetaObject.invokeMethod(self.lbl_showinfo, "setText", Qt.AutoConnection, QtCore.Q_ARG(str, message))
        except Exception as e:
            print(f"Error in update_info_message: {e}")

    def setupUi(self):
        self.setObjectName("Form")
        self.resize(873, 231)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("Conf/ICON/Aging_Test_Ltp"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.gridLayout = QtWidgets.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.lbl_logo = QtWidgets.QLabel(self)
        self.lbl_logo.setText("")
        self.lbl_logo.setPixmap(QtGui.QPixmap("IMAGE/logo.jpg"))
        self.lbl_logo.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_logo.setObjectName("lbl_logo")
        self.verticalLayout_2.addWidget(self.lbl_logo)
        self.lbl_Title = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(20)
        self.lbl_Title.setFont(font)
        self.lbl_Title.setStyleSheet("background-color: rgb(85, 255, 127);\n"
"color: rgb(85, 85, 127);")
        self.lbl_Title.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Title.setObjectName("lbl_Title")
        self.verticalLayout_2.addWidget(self.lbl_Title)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.lbl_Args = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.lbl_Args.setFont(font)
        self.lbl_Args.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Args.setObjectName("lbl_Args")
        self.verticalLayout_3.addWidget(self.lbl_Args)
        self.lbl_readargs = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_readargs.setFont(font)
        self.lbl_readargs.setStyleSheet("color: rgb(255, 170, 0);")
        self.lbl_readargs.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_readargs.setObjectName("lbl_readargs")
        self.verticalLayout_3.addWidget(self.lbl_readargs)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label_3 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.label_3.setFont(font)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.verticalLayout_4.addWidget(self.label_3)
        self.lcdNumber = QtWidgets.QLCDNumber(self)
        self.lcdNumber.setObjectName("lcdNumber")
        self.verticalLayout_4.addWidget(self.lcdNumber)

        # 创建一个新的 QLabel 来显示单位 "秒"
        self.lbl_seconds = QtWidgets.QLabel(self)
        self.lbl_seconds.setObjectName("lbl_seconds")
        self.lbl_seconds.setText("秒")  # 设置文本为 "秒"
        self.lbl_seconds.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)  # 设置标签文本居左垂直居中对齐
        self.verticalLayout_4.addWidget(self.lbl_seconds)  # 将标签添加到布局中

        self.horizontalLayout.addLayout(self.verticalLayout_4)
        self.horizontalLayout.setStretch(0, 4)
        self.horizontalLayout.setStretch(1, 3)
        self.horizontalLayout.setStretch(2, 3)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.lbl_showinfo = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.lbl_showinfo.setFont(font)
        self.lbl_showinfo.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_showinfo.setObjectName("lbl_showinfo")
        self.horizontalLayout_2.addWidget(self.lbl_showinfo)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.progressBar = QtWidgets.QProgressBar(self)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout_3.addWidget(self.progressBar)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.verticalLayout.setStretch(0, 5)
        self.verticalLayout.setStretch(1, 4)
        self.verticalLayout.setStretch(2, 1)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)  # 只显示最小化按钮和关闭按钮

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Form", "【老化】-LTP测试"))
        self.lbl_Title.setText(_translate("Form", "老化-LTP测试"))
        self.lbl_Args.setText(_translate("Form", "配置老化时间"))
        self.lbl_readargs.setText(_translate("Form", "N/A"))
        self.label_3.setText(_translate("Form", "已完成老化时间"))
        self.lbl_showinfo.setText(_translate("Form", "老化测试中..."))

    # 定义一个函数使得函数窗口居中显示
    def Center(self):
        # 获取屏幕尺寸
        screen_geometry = app.desktop().availableGeometry()
        # 计算窗口居中位置
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        # 设置窗口位置
        self.move(x, y)

    # 手动关闭窗口
    def closeEvent(self, event):
        # 创建一个消息框,上面有两个按钮:“是”和“否”
        # reply = QMessageBox.question(self, '退出', "你确定要退出吗?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        # 如果用户点击了“是”,则执行event.accept()来关闭窗口
        # if reply == QMessageBox.Yes:
        #    event.accept()
        #    sys.exit(1)
        # else:
        # 如果用户点击了“否”,则忽略event,不关闭窗口
        #    event.ignore()
        sys.exit(1)

    #处理LTP老化日志文件并上传
    def process_ltplogfile_upload(self):
        try:
            if self.check_log_file_exists('ltpstress.log'):
                # 尝试复制文件
                copied_log_file = f'{self.SN}_ltpstress.log'
                self.copy_file('ltpstress.log', copied_log_file)
                # 尝试上传文件
                upload_url = f"{self.TestWebApi}/TestLog/uploadTestLog"
                if not self.upload_test_log(upload_url, self.Product_name, f'{self.Process_name}/LTP',
                                            f'{self.SN}_ltpstress.log'):
                    self.ShowLog('Failed to upload test log', False)
                    return False

                # 文件上传成功后删除原始和复制的日志文件
                self.delete_file('ltpstress.log')
                self.delete_file(copied_log_file)
                return True
            else:
                self.ShowLog(f'{self.SN}_ltpstress.log Log file does not exist', False)
                return False
        except Exception as e:
            self.ShowLog(f'process ltplogfile upload Err:{str(e)}', False)
            sys.exit(1)

    #复制文件
    def copy_file(self, src, dest):
        try:
            shutil.copy(src, dest)
        except shutil.Error as e:
            self.ShowLog(f'Error copying file: {str(e)}', False)
            return False
        return True

    #查找当前目录文件是否存在
    def check_log_file_exists(self,filename):
        # 获取当前工作目录
        current_directory = os.getcwd()
        # 构造文件的完整路径
        file_path = os.path.join(current_directory, filename)
        # 检查文件是否存在
        return os.path.exists(file_path)

    #装载订单信息
    def load_order_info(self, filepath='./Conf/OrderInfo.json'):
        try:
            with open(filepath, 'r') as file:
                data = json.load(file)
                return {item: value for dic in data for item, value in dic.items()}
        except FileNotFoundError:
            self.ShowLog(f"'./Conf/OrderInfo.json' File not found. Please check the filepath.", False)
            sys.exit(1)
        except json.JSONDecodeError:
            self.ShowLog("Error decoding JSON. Please check the file format.", False)
            sys.exit(1)

    #获取日志上传基础信息
    #蛇形命名法(snake_case)
    def gather_log_upload_data(self):
        order_info = self.load_order_info()
        if order_info is None:
            self.ShowLog("Failed to load order info, aborting update.", False)
            sys.exit(1)

        # Extract needed information
        self.SN = order_info.get("SN", "Not Found")
        self.Process_name = order_info.get("NextWorkStation", "Not Found")
        self.Product_name = order_info.get("ItemDesc", "Not Found")

        if self.SN == "Not Found" or self.Process_name == "Not Found" or self.Product_name == "Not Found":
            self.ShowLog("Required information is missing from the order info.", False)
            sys.exit(1)
        return True

    #上传测试日志
    def upload_test_log(self,url, product_name, process_name, file_path):
        """
        上传测试日志文件到指定的 Web API。

        :param url: Web API 的 URL。
        :param product_name: 产品名称。
        :param process_name: 测试过程名称。
        :param file_path: 要上传的日志文件的路径。
        :return: 返回响应对象。
        """

        # 设置查询参数
        params = {
            "productName": product_name,
            "processName": process_name
        }

        # 打开要上传的文件
        with open(file_path, 'rb') as file:
            # 设置请求体中的文件部分
            files = {
                "logfile": (file_path, file, "application/json")
            }

            # 发送 POST 请求
            response = requests.post(url, params=params, files=files)
            if response.status_code == 200:
                self.ShowLog("Test log file uploaded successfully.",True)
                self.delete_file(file_path) #删除上传文件
                return True
            else:
                self.ShowLog(f"Failed to upload test log file. Status code: {response.status_code}, Response: {response.text}",False)
                sys.exit(1)

    # 获取项目名称
    def GetitemName(self):
        try:
            # 获取当前执行文件的完整路径
            full_path = sys.argv[0]
            # 从完整路径中提取文件名
            file_name = os.path.basename(full_path)
            self.itemName = file_name  # 项目名称
        except Exception as e:
            self.ShowLog(f'Get Item Name Err:{str(e)}', False)
            sys.exit(1)

    #日志信息
    def loggerrinfo(self):
        try:
            # 确保日志文件的目录存在
            log_directory = os.path.abspath('./log')  # 使用绝对路径
            if not os.path.exists(log_directory):
                os.makedirs(log_directory)

            self.config = configparser.ConfigParser()  # 创建配置解析器对象
            # 生成日志信息
            self.logger = logging.getLogger('my_logger')  # 创建日志记录器
            self.logger.setLevel(logging.DEBUG)  # 设置日志级别为DEBUG
            file_handler = logging.FileHandler(f'{log_directory}/log.txt')  # 创建文件处理器
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')  # 创建格式化器
            file_handler.setFormatter(formatter)  # 将格式化器设置到文件处理器
            self.logger.addHandler(file_handler)  # 将文件处理器添加到日志记录器
        except Exception as e:
            self.ShowLog(f'Create logger_info Error: {str(e)}', False)

    #安装老化测试环境
    def install_ltp(self):
        try:
            if self.cpu_architecture == 'arm':
                ltp_command = "ltp/runltp"
                if not os.path.exists(ltp_command):
                    ltp_tar_path = "./Installation_Package/ltp.tar.gz"
                    if not os.path.exists(ltp_tar_path):
                        self.ShowLog(f"错误:文件 {ltp_tar_path} 不存在。", False)
                        return False

                    # 解压文件
                    subprocess.run(["sudo", "tar", "-xvf", ltp_tar_path], check=True)

                    # 切换到LTP安装目录
                    #os.chdir("ltp")

                    return True
            else:
                ltp_command = "/opt/ltp/runltp"
                if not os.path.exists(ltp_command):
                    ltp_tar_path = "./Installation_Package/ltp-full-20160510_kylin.tar.bz2"
                    if not os.path.exists(ltp_tar_path):
                        self.ShowLog(f"错误:文件 {ltp_tar_path} 不存在。", False)
                        return True

                    # 解压文件
                    subprocess.run(["sudo", "tar", "-xvf", ltp_tar_path], check=True)

                    # 切换到LTP安装目录
                    os.chdir("ltp-full-20160510")

                    # 执行安装步骤
                    subprocess.run(["sudo", "./configure"], check=True)
                    subprocess.run(["sudo", "make"], check=True)
                    subprocess.run(["sudo", "make", "install"], check=True)

                    # 检查是否安装成功
                    if os.path.exists("/opt/ltp/runltp"):
                        self.ShowLog("LTP installation completed successfully.", True)
                    else:
                        self.ShowLog("LTP installation failed. '/opt/ltp/runltp' does not exist.", False)
                        return False

                    # 返回到原始工作目录
                    os.chdir("..")

                    # 删除解压的LTP安装目录
                    shutil.rmtree("ltp-full-20160510")

                    return True
                else:
                    self.ShowLog("LTP is already installed.", True)
                    return True
        except subprocess.CalledProcessError as e:
            self.ShowLog(f"Command '{e.cmd}' failed with exit status {e.returncode}: {e.output}", False)
            sys.exit(1)
        except Exception as e:
            self.ShowLog(f"install_ltp Err: {str(e)}", False)
            sys.exit(1)
    # def install_ltp(self):
    #     try:
    #         if self.cpu_architecture == 'arm':
    #             ltp_command = "/opt/ltp/runltp"
    #             if not os.path.exists(ltp_command):
    #                 ltp_tar_path = "./Installation_Package/ltp-full-20200515.tar.bz2"
    #                 if not os.path.exists(ltp_tar_path):
    #                     self.ShowLog(f"错误:文件 {ltp_tar_path} 不存在。", False)
    #                     return
    #
    #                 # 解压文件
    #                 subprocess.run(["sudo", "tar", "-xvf", ltp_tar_path], check=True)
    #
    #                 #切换到LTP安装目录
    #                 os.chdir("ltp-full-20200515")
    #
    #
    #
    #         else:
    #             ltp_command = "/opt/ltp/runltp"
    #             if not os.path.exists(ltp_command):
    #                 #self.ShowLog("LTP is not installed. Installing now...", False)
    #                 ltp_tar_path = "./Installation_Package/ltp-full-20160510_kylin.tar.bz2"
    #                 if not os.path.exists(ltp_tar_path):
    #                     self.ShowLog(f"错误:文件 {ltp_tar_path} 不存在。", False)
    #                     return
    #
    #                 # 解压文件
    #                 subprocess.run(["sudo", "tar", "-xvf", ltp_tar_path], check=True)
    #
    #                 # 切换到LTP安装目录
    #                 os.chdir("ltp-full-20160510")
    #
    #                 # 执行安装步骤
    #                 configure = subprocess.run(["sudo", "./configure"], check=True)
    #                 make = subprocess.run(["sudo", "make"], check=True)
    #                 make_install = subprocess.run(["sudo", "make", "install"], check=True)
    #
    #                 # 检查是否安装成功
    #                 if os.path.exists("/opt/ltp/runltp"):
    #                     self.ShowLog("LTP installation completed successfully.", True)
    #                 else:
    #                     self.ShowLog("LTP installation failed. '/opt/ltp/runltp' does not exist.", False)
    #                     return
    #
    #                 # 返回到原始工作目录
    #                 os.chdir("..")
    #
    #                 # 删除解压的LTP安装目录
    #                 shutil.rmtree("ltp-full-20160510")
    #             else:
    #                 self.ShowLog("LTP is already installed.", True)
    #     except subprocess.CalledProcessError as e:
    #         self.ShowLog(f"Command '{e.cmd}' failed with exit status {e.returncode}: {e.output}", False)
    #         sys.exit(1)
    #     except Exception as e:
    #         self.ShowLog(f"install_ltp Err: {str(e)}", False)
    #         sys.exit(1)

    #执行老化测试
    def run_ltp_stress_test(self, testTime):
        original_dir = os.getcwd()
        log_file = os.path.join(original_dir, "ltpstress.log")
        try:
            if self.cpu_architecture == 'arm':
                testscripts_dir = "ltp/testscripts"
                if not os.path.exists(testscripts_dir):
                    self.ShowLog("Error: ltp/testscripts does not exist", False)
                    return False

                os.chdir(testscripts_dir)
                if not os.path.exists("./ltpstress.sh"):
                    self.ShowLog("Error: ltpstress.sh does not exist in /opt/ltp/testscripts", False)
                    return False

                ltpstress_command = f"sudo ./ltpstress.sh -l {log_file} -t {testTime} -n"
                # 移除capture_output,改用 subprocess.PIPE 或完全去除以直接打印到终端
                result = subprocess.run(ltpstress_command, shell=True, text=True)

                if result.returncode == 0:
                    self.ShowLog(f"LTP stress test started. Logging to {log_file}.", True)
                    return True
                else:
                    self.ShowLog(f"LTP stress test failed.", False)
                    return False
            else:
                testscripts_dir = "/opt/ltp/testscripts"
                if not os.path.exists(testscripts_dir):
                    self.ShowLog("Error: /opt/ltp/testscripts does not exist", False)
                    return False

                os.chdir(testscripts_dir)
                if not os.path.exists("./ltpstress.sh"):
                    self.ShowLog("Error: ltpstress.sh does not exist in /opt/ltp/testscripts", False)
                    return False

                ltpstress_command = f"sudo ./ltpstress.sh -l {log_file} -t {testTime} -n"
                # 移除capture_output,改用 subprocess.PIPE 或完全去除以直接打印到终端
                result = subprocess.run(ltpstress_command, shell=True, text=True)

                if result.returncode == 0:
                    self.ShowLog(f"LTP stress test started. Logging to {log_file}.", True)
                    return True
                else:
                    self.ShowLog(f"LTP stress test failed.", False)
                    return False
        except Exception as e:
            self.ShowLog(f"run_ltp_stress_test Info Err: {str(e)}", False)
            return False
        finally:
            os.chdir(original_dir)

    # 删除当前目录下指定文件
    def delete_file(self, filename):
        # 获取当前工作目录的完整路径
        full_path = os.path.join(os.getcwd(), filename)

        # 检查文件是否存在于当前工作目录
        if os.path.exists(full_path):
            # 删除文件
            os.remove(full_path)
            print(f"{filename} has been deleted from the current directory.")
        else:
            # 如果文件不存在,打印一个消息
            print(f"The file {filename} does not exist in the current directory.")

    # 更新测试参数json,itemName:项目名称,readValue:读取值,testResult:测试结果
    def UpdateJsonTestArgs(self, itemName, readValue, testResult):
        try:
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            if self.testArgs is None:
                raise Exception("Failed to read configuration, aborting update.")

            for js in self.testArgs:
                if itemName in js['ItemScript']:
                    js['Read'] = readValue
                    js['TestResult'] = testResult

            with open("./Conf/TestArgs.json", "w") as write_file:
                json.dump(self.testArgs, write_file, indent=4)  # Use indent for pretty printing

            return True
        except Exception as e:
            self.ShowLog(f"Update TestArgs.json ItemName: {itemName} Info Err: {str(e)}", False)
            sys.exit(1)

    # 读取项目参数信息,itemName:项目名称
    def ReadJsonTestArgs(self):
        try:
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                print(self.itemName, js['ItemScript'])
                if self.itemName in js['ItemScript']:
                    self.testStandardArgs = js['Standard']
                    return True
            return False
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:" + self.itemName + " Info Err:" + str(e), False)
            sys.exit(1)

    # 读取json信息,fileName:文件名称
    def ReadJsonInfo(self, fileName):
        try:
            if os.path.exists(fileName):
                f = open(fileName, 'r', encoding='utf-8')
            return json.loads(f.read())
        except Exception as e:
            self.ShowLog("Read " + fileName + " Err:" + str(e), False)
            sys.exit(1)

    # 打印的信息
    def ShowLog(self, log, isPass):
        try:
            if isPass == True:
                print("\033[1;32;43m" + str(log) + " \033[0m")
                self.logger.info(str(log))
            else:
                print("\033[1;31m" + str(log) + " \033[0m")
                self.logger.error(str(log))
                QMessageBox.critical(self, '系统提醒', f"{log}", QMessageBox.Yes, QMessageBox.Yes)
        except Exception as e:
            print("\033[1;31m" + str(e) + " \033[0m")
            QMessageBox.critical(self, '系统提醒', f"{log}", QMessageBox.Yes, QMessageBox.Yes)
            sys.exit(1)


if __name__=='__main__':
    app=QApplication(sys.argv)
    win=Aging_Test_Ltp()
    win.Center()  # 居中
    win.show()
    sys.exit(app.exec_())

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值