1.1 打开串口示例
常用的模组则包含AT指令测试,或串口数据测试,则可添加串口配置,将指令通过串口发送出去,如下所示:
import serial def open_serial_port(port, baudrate=115200, timeout=2): try: # 创建并配置串行端口对象 serial_port = serial.Serial(port=port, baudrate=baudrate, timeout=timeout) # 如果需要,可以在这里添加更多的配置代码 # 检查端口是否成功打开 if serial_port.isOpen(): print(f"Serial port {port} opened successfully.") return serial_port else: raise Exception(f"Failed to open serial port {port}.") except serial.SerialException as e: print(f"Error opening serial port {port}: {e}") return None # 使用示例
if __name__ == "__main__": port = "COM23" baudrate = 115200 timeout = 2 serial_port = open_serial_port(port, baudrate, timeout) if serial_port: print("Open serial success.")# 这里可以添加使用 serial_port 的代码 pass else: print("Failed to open serial port.")exit(1) #直接退出程序
1.2 导入多个测试用例示例
本文以移远模组为示例,则对模组信号查询与网络查询AT指令进行测试,常用的指令为:
则本文以其进行示例创建测试用例
首先,创建一个log打印的py文件名为at_log_set.py
,将直接使用 Python 的日志级别将其映射,更方面的管理日志。
import sys
import serial
import time
import logging
from time import strftime, localtime# 配置日志
logging.basicConfig(level=logging.DEBUG, filename='log.txt')
# 创建一个handler,用于将日志输出到控制台
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.addHandler(console_handler) def report_info(loginfo, loglevel=logging.DEBUG):logger.log(loglevel, loginfo)def send_at(serial_port, at_str, timeout):report_info(at_str, logging.DEBUG)serial_port.write(at_str.encode())serial_port.flushif(timeout > 0):time.sleep(timeout)at_response = serial_port.readall().decode()report_info(at_response, logging.DEBUG)return at_responsedef capture_response_with_retry(serial_port, at_response, des_str, timeout_step, timeout_retraymax):retray = 1while(retray < timeout_retraymax):if(at_response != ""):report_info(at_response, logging.DEBUG) if (at_response.find(des_str) != -1):return 0retray = retray + 1serial_port.flush()time.sleep(timeout_step)at_response = serial_port.readall().decode()if(retray >= timeout_retraymax):report_info("timeout_retraymax don't find", logging.ERROR)return -1return 0def retry_send_str(serial_port, at_response, src_str, des_str, count, timeout):index = 1while(index < count):at_response = send_at(serial_port,src_str, timeout)if(at_response != ""):report_info(at_response, logging.DEBUG)if (at_response.find(des_str) != -1):return 0index = index + 1if(index >= count):report_info("don't find", logging.ERROR)return -1return 0
新建一个python文件,at_internet_test.py
,代码如下:
import sys
import serial
import unittest
from at_log_set import *def at_test(serial_port):at_response = send_at(serial_port, "AT\r\n", 0.5)if(at_response.find("OK") == -1):return -1return 0def csq_test(serial_port):at_response = send_at(serial_port, "AT+CSQ\r\n", 0.5)if(at_response.find("+CSQ:") == -1):return -1return 0def cereg_test(serial_port):at_response = send_at(serial_port, "AT+CEREG?\r\n", 0.5)if(retry_send_str(serial_port, at_response, "AT+CEREG?\r\n", "+CEREG:0,1", 10, 0.5) == 0):return 0return -1def internet_at(serial_port):ret = 0if(at_test(serial_port) == -1):ret = -1if(csq_test(serial_port) == -1):ret = -1if(cereg_test(serial_port) == -1):ret = -1return ret
将之前所示的串口和测试用例放到一起,则为main.py
, 如下所示:
import unittest
from unittestreport import TestRunner
import os
import serial
from at_log_set import *
from at_internet_test import *def open_serial_port(port, baudrate=115200, timeout=2): try: serial_port = serial.Serial(port=port, baudrate=baudrate, timeout=timeout) if serial_port.isOpen(): print(f"Serial port {port} opened successfully.") return serial_port else: raise Exception(f"Failed to open serial port {port}.") except serial.SerialException as e: print(f"Error opening serial port {port}: {e}") return None class TestInternetAT(unittest.TestCase):def test_internet_at(self):self.assertEqual(0, internet_at(serial_port))# 创建 TestSuite 实例
suite = unittest.TestSuite()
suite.addTest(TestInternetAT("test_internet_at")) BasePath = os.path.dirname(__file__)#获取当前文件所在路径
if __name__ == "__main__":port = "COM7" baudrate = 115200 timeout = 2 serial_port = open_serial_port(port, baudrate, timeout) if serial_port: print("Open serial success.") else: print("Failed to open serial port.")exit(1)if not os.path.isdir("report"):os.mkdir("report")fp = BasePath + "\\report" #特别需要注意的是 report文件是已存在的,否则会报错runner = TestRunner(suite,filename="TEST测试报告.html",report_dir=fp,title="TEST测试报告",tester="USER1",desc="20240731执行测试")runner.run()
则可将该测试用例导入测试,若有其他模块的测试用例,可参考该测试用例进行导入,之后则运行main.py,则将测试报告显示在report文件夹下
运行log如下图所示:
也可通过tkinter将其作为可视化测试工具,结合数据库,更方便的用来管理模块化测试用例,后续持续更新。。。
若有错误,欢迎指正