# -*- encoding=utf8 -*-
__author__ = "Tmi2szh"
from airtest.core.api import *
from airtest.report.report import simple_report
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import unittest
import os
import time
import logging
# 配置日志
logging.basicConfig(filename='script_log.txt', level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# 初始化Airtest
auto_setup(__file__, logdir=True)
# 创建测试报告存放文件夹
report_dir = "report"
os.makedirs(report_dir, exist_ok=True) # 如果目录已存在,不会抛出异常
# 定义一个全局变量来存储测试结果
test_results = []
# 最大重试次数和重试间隔(秒)
MAX_RETRY = 500
RETRY_INTERVAL = 5
class MyTestCase(unittest.TestCase):
def setUp(self):
# 初始化ADB连接状态
self.poco = AndroidUiautomationPoco()
self.adb_connected = False
def tearDown(self):
# 清理操作
print('清理操作')
logging.info(f"清理操作")
# 关闭 ADB 服务
os.system('adb kill-server')
os.system('adb start-server')
# 检查ADB连接状态并重试,直到连接成功或达到最大重试次数
def check_adb_connection(self):
retry_count = 0
while not self.adb_connected and retry_count < MAX_RETRY:
try:
connect_device("Android:///")
self.adb_connected = True
print("ADB连接成功")
except Exception as e:
logging.info(f"ADB连接失败,正在重试... ({retry_count+1}/{MAX_RETRY})")
print(f"ADB连接失败,正在重试... ({retry_count+1}/{MAX_RETRY})")
time.sleep(RETRY_INTERVAL)
retry_count += 1
if not self.adb_connected:
print("ADB连接失败,无法执行测试用例!")
self.fail("ADB连接失败,无法执行测试用例!")
# Airtest测试用例1,操作蓝牙开关
def test_airtest_case1(self):
self.check_adb_connection()
if not self.adb_connected:
self.skipTest("ADB连接失败")
try:
# 在这里写入具体的测试步骤,使用Airtest进行操作
print('用例通过1')
logging.info(f"用例通过1")
pass
except Exception as e:
logging.info(f"测试用例1发生异常:{str(e)}")
# Airtest测试用例2,操作WiFi开关
def test_airtest_case2(self):
self.check_adb_connection()
if not self.adb_connected:
self.skipTest("ADB连接失败")
try:
# 在这里写入具体的测试步骤,使用Airtest进行操作
print('用例通过2')
logging.info(f"用例通过2")
pass
except Exception as e:
logging.info(f"测试用例2发生异常:{str(e)}")
# Airtest测试用例3,操作热点开关
def test_airtest_case3(self):
self.check_adb_connection()
if not self.adb_connected:
self.skipTest("ADB连接失败")
try:
# 在这里写入具体的测试步骤,使用Airtest进行操作
print('用例通过3')
logging.info(f"用例通过3")
pass
except Exception as e:
logging.info(f"测试用例3发生异常:{str(e)}")
# 使用 suite() 函数创建测试套件
def suite():
suite = unittest.TestSuite()
suite.addTest(MyTestCase('test_airtest_case1'))
suite.addTest(MyTestCase('test_airtest_case2'))
suite.addTest(MyTestCase('test_airtest_case3'))
return suite
if __name__ == '__main__':
# 运行测试用例
runner = unittest.TextTestRunner()
result = runner.run(suite())
# 生成测试报告,保存在当前文件夹下并以时间命名
current_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
current_directory = os.path.dirname(__file__)
report_path = simple_report(__file__, logpath=True, output=os.path.join(current_directory,'report', f'report_{current_time}.html'))
【AirTest模板】
于 2024-05-29 02:36:18 首次发布