一、获取app应用版本信息以及手机id
import os
def exec_cmd(cmd) -> str:
result = os.popen(cmd).read()
print(result)
return result
def get_all_devices() -> list:
result = exec_cmd('adb devices')
result = result.strip().split(" ")[3].replace("\n", '').replace("\t", ''). \
replace("attached", '').split('device')
print('1====',result)
result.remove('')
print('2====', result)
if len(result) == 0:
raise Exception("电脑未连接设备信息,无法进行正常测试。。")
return result
def get_devices_version(device: str) -> str:
if not isinstance(device, str):
raise Exception("device type is should str..")
result = exec_cmd("adb -s {} shell getprop ro.build.version.release".format(device))
result = result.strip()
if "error" not in result:
return result
else:
raise Exception("获取设备系统版本失败,无法进行正常测试。。")
def get_device_infos():
device_infos = []
devices = get_all_devices()
for i in range(len(devices)):
device_dict = {"platform_version": get_devices_version(devices[i]), "server_port": 4723 + i * 2,
"system_port": 8200 + i * 1, "device": devices[i]}
device_infos.append(device_dict)
if len(device_infos) < 1:
raise Exception("当前电脑未连接设备信息。。。")
print(device_infos)
return device_infos
if __name__ == '__main__':
device_lists = get_device_infos()
运行结果:
List of devices attached
HDP9K18629901709 device
1==== ['HDP9K18629901709', '']
2==== ['HDP9K18629901709']
8.1.0
[{'platform_version': '8.1.0', 'server_port': 4723, 'system_port': 8200, 'device': 'HDP9K18629901709'}]
包含CMD操作:
二、Appium利用python自动启动和关闭appium server
参考文章
后台启动&关闭appium server的命令:
- appium -a 127.0.0.1 -p 4723 –U HDP9K18629901709 --no-reset
- appium -a 127.0.0.1 -p 4723 --log xxx.log --local-timezone
-p 4723 指定端口
–log xxx.log指定日志保存到指定文件内(可以是绝对路径)
–local-timezone指定时间为本地时间
–log-level error设置日志级别,默认是debug
根据端口号查看进程&关闭相应的进程:
- 第一步查询:
- 根据端口号查找进程号:
netstat -o -n -a | findstr :端口号
# 命令
netstat -aon|findstr 4723
# 结果
TCP 127.0.0.1:4723 0.0.0.0:0 LISTENING 1744
- 第二步终止:
- 终止进程taskkill /F /PID 进程号(PID号):
# 命令
taskkill /f /pid 1744
# 结果
成功: 已终止 PID 为 1744 的进程。
其他:终止所有appium进程 :taskkill /f /t /im node.exe
三、APPIUM报错:InvalidSelectorError: Locator Strategy ‘name’ is not supported for this session
1、打开本地文件 driver.js (路径:appium的安装路径\resources\app\node_modules\appium\node_modules\appium-android-driver\build\lib\driver.js)
比如我的:
C:\Users\make\AppData\Local\Programs\Appium\resources\app\node_modules\appium\node_modules\appium-android-driver\build\lib
2、查找 this.locatorStrategies = ['xpath', 'id', 'class name', 'accessibility id', '-android uiautomator'];
将 name加到里面: this.locatorStrategies = ['xpath', 'id', 'class name', 'accessibility id', '-android uiautomator','name'];
3、重启appium服务
四、记录pytest.ini
[pytest]
log_cli=true -o log_cli_level=INFO ; # 开启日记
log_level=NOTSET ; # 日志等级
log_format = %(asctime)s %(levelname)s %(message)s # 日记日期
log_date_format = %Y-%m-%d %H:%M:%S # 日记时间
addopts = -vs # 日志执行的命令
log_file = ./outputs/logs/log.txt # 日志存放地方
log_file_level = info # 记录日志等级
log_file_format = %(asctime)s %(levelname)s %(message)s # 同记录时间一样
log_file_date_format = %Y-%m-%d %H:%M:%S
五、conftest.py文件
from common.app_driver import AppDriver
from pageobjects.login_page import LoginPage
import pytest, platform, sys, requests, pytest_html, os, time, datetime
from common.all_path import logPath
from py.xml import html
# 编辑html报告标题
def pytest_html_report_title(report):
report.title = "Appium report"
# log输出文件目录
def pytest_configure(config):
now = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
logfile_name = f'{now}.log'
config.option.log_file = os.path.join(config.rootdir, logPath, logfile_name)
# 添加项目名称
config._metadata["项目名称"] = "小程序测试"
# 增加测试结果time时间戳
def pytest_html_results_table_header(cells):
cells.insert(1, html.th("Time", class_="sortable time", col="time"))
cells.pop()
def pytest_html_results_table_row(report, cells):
cells.insert(1, html.td(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S'), class_="col-time"))
cells.pop()
@pytest.fixture(scope='session')
def common_driver():
global driver
base_driver = AppDriver()
driver = base_driver.driver()
print(driver)
lg = LoginPage(driver)
if lg.login() == 1:
pytest.skip('环境检查不通过')
yield lg
# driver.close_app()
driver.quit()
六、附带pytest跳过的资料:点击跳转
七、附带pytest跳过的资料:点击输入键盘输入中文的问题,点击这里
总结:
在driver里面新增两个属性:
desired_caps["unicodeKeyboard"] = True # 使用中文输入法条件一 使用unicode输入法
desired_caps["resetKeyboard"] = True # 使用中文输入法条件二 讲键盘隐藏起来
如果遇到乱码问题:在运行 driver 加上下面代码
前面加上 # -*- coding:gb18030 -*-
如下图所示:
附带:安装好之后的下载包:
注意:Appium Sever 要和我们的 Appium-Python-Client 匹配上 不然会出现 :Method has not yet been implemented
报错
Appium Sever v1.13.0
Package | Version |
---|---|
adbutils | 1.0.10 |
allure-pytest | 2.8.10 |
allure-python-commons | 2.8.10 |
apkutils2 | 1.0.0 |
Appium-Python-Client | 1.2.0 |
async-generator | 1.1 |
atomicwrites | 1.4.1 |
attrs | 22.1.0 |
BeautifulReport | 0.1.3 |
cached-property | 1.5.2 |
certifi | 2022.9.24 |
cffi | 1.15.1 |
chardet | 3.0.4 |
charset-normalizer | 2.1.1 |
cigam | 0.0.3 |
colorama | 0.4.6 |
colorlog | 6.6.0 |
ddt | 1.6.0 |
decorator | 5.1.1 |
Deprecated | 1.2.13 |
deprecation | 2.1.0 |
dill | 0.3.6 |
et-xmlfile | 1.1.0 |
exceptiongroup | 1.0.0 |
facebook-wda | 1.4.6 |
Faker | 13.12.0 |
filelock | 3.8.0 |
h11 | 0.14.0 |
idna | 2.8 |
iniconfig | 1.1.1 |
Jinja2 | 3.0.3 |
jsonpath | 0.82 |
logzero | 1.7.0 |
lxml | 4.9.1 |
MarkupSafe | 2.1.1 |
more-itertools | 9.0.0 |
MouseInfo | 0.1.3 |
openpyxl | 3.0.9 |
outcome | 1.2.0 |
packaging | 20.9 |
pdfminer | 20191125 |
Pillow | 9.3.0 |
pip | 22.3.1 |
pluggy | 0.13.1 |
progress | 1.6 |
py | 1.11.0 |
PyAutoGUI | 0.9.53 |
pycparser | 2.21 |
pycryptodome | 3.15.0 |
pyelftools | 0.29 |
PyGetWindow | 0.0.9 |
PyMsgBox | 1.0.9 |
pymssql | 2.2.4 |
pyparsing | 3.0.9 |
pyperclip | 1.8.2 |
PyRect | 0.2.0 |
PyScreeze | 0.1.28 |
PySocks | 1.7.1 |
pytest | 6.2.5 |
pytest-html | 3.2.0 |
pytest-metadata | 2.0.4 |
python-dateutil | 2.8.2 |
pytweening | 1.0.4 |
pywin32 | 305 |
PyYAML | 5.3 |
requests | 2.22.0 |
retry | 0.9.2 |
selenium | 4.7.2 |
setuptools | 50.3.2 |
six | 1.16.0 |
sniffio | 1.3.0 |
sortedcontainers | 2.4.0 |
toml | 0.10.2 |
tornado | 6.2 |
trio | 0.22.0 |
trio-websocket | 0.9.2 |
uiautomator2 | 2.16.19 |
unittestreport | 1.4.3 |
urllib3 | 1.26.13 |
wcwidth | 0.2.5 |
weditor | 0.6.4 |
whichcraft | 0.6.1 |
wrapt | 1.14.1 |
wsproto | 1.2.0 |
xlrd | 1.2.0 |
xmltodict | 0.13.0 |