Skip to content

Commit

Permalink
1、修改pytest在Windows下编码的bug
Browse files Browse the repository at this point in the history
2、支持多渠道包测试
  • Loading branch information
yanchunhuo committed Jan 15, 2020
1 parent 0dcc9b0 commit 4c43e0d
Show file tree
Hide file tree
Showing 14 changed files with 193 additions and 96 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*nohup.out*
*uwsgi.pid*
*.pytest_cache*
*pytest.ini*
*common/java/lib/java/libs/*
*config/app_ui_tmp/*
*.vscode*
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding:utf-8 -*-
# 作者 yanchunhuo
# 创建时间 2018/01/19 22:36
# github https://github.com/yanchunhuo

from appium import webdriver
from base.read_app_ui_config import Read_APP_UI_Config
from common.appium.appOperator import AppOperator
Expand All @@ -23,9 +23,10 @@ def __init__(self):
if self.__inited is None:
self._init()
self.config = Read_APP_UI_Config().app_ui_config
self.device_info=FileTool.readJsonFromFile('config/app_ui_tmp/'+str(os.getpid()))
self.device_info=FileTool.readJsonFromFile('config/app_ui_tmp/'+str(os.getppid()))
self.current_desired_capabilities = FileTool.readJsonFromFile('config/app_ui_tmp/' + str(os.getppid()) + '_current_desired_capabilities')
self._appium_hub='http://'+self.device_info['server_ip']+':%s/wd/hub'%self.device_info['server_port']
self.driver = webdriver.Remote(self._appium_hub,desired_capabilities=self.device_info['capabilities'])
self.driver = webdriver.Remote(self._appium_hub,desired_capabilities=self.current_desired_capabilities)
self.appOperator = AppOperator(self.driver,self._appium_hub)

self.__inited=True
Expand Down
12 changes: 4 additions & 8 deletions base/read_app_ui_devices_info.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# 作者 yanchunhuo
# 创建时间 2019/12/26 11:15
# github https://github.com/yanchunhuo

from pojo.app_ui_devices_info import APP_UI_Devices_Info
import configparser as ConfigParser
import os

class Read_APP_UI_Devices_Info(object):
__instance=None
Expand Down Expand Up @@ -42,10 +41,7 @@ def _read_devices_info(self, filepath):
devices_info.systemports=get_lambda(config.get('devices_info','systemports', fallback=''))
devices_info.wdaLocalPorts = get_lambda(config.get('devices_info', 'wdaLocalPorts', fallback=''))
devices_info.wdaLocalPorts = get_lambda(config.get('devices_info', 'wdaLocalPorts', fallback=''))
devices_info.appActivity = config.get('devices_info','appActivity')
devices_info.appPackage = config.get('devices_info','appPackage')
devices_info.app = config.get('devices_info','app')
# 将安装包所在位置转为绝对路径
if devices_info.app:
devices_info.app = os.path.abspath(devices_info.app)
devices_info.appActivitys = get_lambda(config.get('devices_info','appActivitys',fallback=''))
devices_info.appPackages = get_lambda(config.get('devices_info','appPackages',fallback=''))
devices_info.apps_dirs = get_lambda(config.get('devices_info','apps_dirs',fallback=''))
return devices_info.get_devices_info()
2 changes: 1 addition & 1 deletion base/web_ui/demoProject/web_ui_demoProject_read_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self):

def _readConfig(self, configFile):
config = ConfigParser.ConfigParser()
config.read(configFile)
config.read(configFile,encoding='utf-8')
demoProjectConfig = DemoProjectConfig()
demoProjectConfig.web_host = config.get('servers','web_host')
demoProjectConfig.init=config.get('isInit','init')
Expand Down
26 changes: 26 additions & 0 deletions common/custom_multiprocessing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# @Author : yanchunhuo
# @Time : 2020/1/15 16:25

from multiprocessing.pool import Pool
import multiprocessing

class NoDaemonProcess(multiprocessing.Process):
"""
重构multiprocessing.Process类,将进程始终定义为非守护进程
"""
def _get_daemon(self):
"""
总返回非守护进程属性值
"""
return False

def _set_daemon(self, value):
pass

daemon = property(_get_daemon, _set_daemon)

class Custom_Pool(Pool):
"""
重构multiprocessing.Pool类
"""
Process = NoDaemonProcess
34 changes: 17 additions & 17 deletions common/fileTool.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,39 @@
class FileTool:

@classmethod
def writeObjectIntoFile(cls,obj,filePath):
def writeObjectIntoFile(cls,obj,filePath,encoding='utf-8'):
"""
将对象转为json字符串,写入到文件
:param obj:
:param filePath:
:return:
"""
str = ujson.dumps(obj)
with open(filePath,'w') as f:
with open(filePath,'w',encoding=encoding) as f:
f.write(str)
f.close()

@classmethod
def readJsonFromFile(cls,filePath):
def readJsonFromFile(cls,filePath,encoding='utf-8'):
"""
从文件里读取json字符串
:param filePath:
:return:
"""
with open(filePath,'r') as f:
with open(filePath,'r',encoding=encoding) as f:
result=f.read()
f.close()
result=ujson.loads(result)
return result

@classmethod
def truncateFile(cls,fielPath):
def truncateFile(cls,fielPath,encoding='utf-8'):
"""
清空文件
:param fielPath:
:return:
"""
with open(fielPath,'r+') as f:
with open(fielPath,'r+',encoding=encoding) as f:
f.truncate()
f.close()

Expand All @@ -64,7 +64,7 @@ def truncateDir(cls,dirPath,regexs=None):
os.remove(filePath)

@classmethod
def replaceFileLineContent(cls, filePath, match_keyword, old, new):
def replaceFileLineContent(cls, filePath, match_keyword, old, new,encoding='utf-8'):
"""
根据关键字匹配文档中的行,对行内容进行替换
:param filePath: 文档路径
Expand All @@ -73,7 +73,7 @@ def replaceFileLineContent(cls, filePath, match_keyword, old, new):
:param new: 用于替换匹配的行中的旧字符串
:return:
"""
with open(filePath, 'r') as f:
with open(filePath, 'r',encoding=encoding) as f:
new_lines = []
lines = f.readlines()
for line in lines:
Expand All @@ -82,12 +82,12 @@ def replaceFileLineContent(cls, filePath, match_keyword, old, new):
new_lines.append(line)
f.close()

with open(filePath, 'w+') as f:
with open(filePath, 'w+',encoding=encoding) as f:
f.writelines(new_lines)
f.close()

@classmethod
def replaceFileContent(cls, filePath, old, new, replaceNum=-1, replaceOffset=0):
def replaceFileContent(cls, filePath, old, new, replaceNum=-1, replaceOffset=0,encoding='utf-8'):
"""
替换文档中的内容,支持替换全部、替换指定前几个、替换第N个
:param filePath: 文档路径
Expand All @@ -97,7 +97,7 @@ def replaceFileContent(cls, filePath, old, new, replaceNum=-1, replaceOffset=0):
:param replaceOffset: 替换第几个,下标从0开始,
:return:
"""
with open(filePath, 'r') as f:
with open(filePath, 'r',encoding=encoding) as f:
content = f.read()
if int(replaceNum) == -1:
content = content.replace(old, new)
Expand Down Expand Up @@ -133,12 +133,12 @@ def replaceFileContent(cls, filePath, old, new, replaceNum=-1, replaceOffset=0):
content = preContent + centerContent + suffContent
break

with open(filePath, 'w+') as f:
with open(filePath, 'w+',encoding=encoding) as f:
f.writelines(content)
f.close()

@classmethod
def replaceFileContentWithLBRB(cls, filePath, new, lbStr, rbStr, replaceOffset=0):
def replaceFileContentWithLBRB(cls, filePath, new, lbStr, rbStr, replaceOffset=0,encoding='utf-8'):
"""
根据左右字符串匹配要替换的文档内容,支持多处匹配只替换一处的功能
:param filePath: 文档路径
Expand All @@ -152,7 +152,7 @@ def replaceFileContentWithLBRB(cls, filePath, new, lbStr, rbStr, replaceOffset=0
return
regex = '([\\s\\S]*?)'
r = re.compile(lbStr + regex + rbStr)
with open(filePath, 'r') as f:
with open(filePath, 'r',encoding=encoding) as f:
content = f.read()
match_results = r.findall(content)
if int(replaceOffset) == -1:
Expand All @@ -177,12 +177,12 @@ def replaceFileContentWithLBRB(cls, filePath, new, lbStr, rbStr, replaceOffset=0
break
f.close()

with open(filePath, 'w+') as f:
with open(filePath, 'w+',encoding=encoding) as f:
f.writelines(content)
f.close()

@classmethod
def appendContent(cls, filePath, content):
with open(filePath, 'a') as f:
def appendContent(cls, filePath, content,encoding='utf-8'):
with open(filePath, 'a',encoding=encoding) as f:
f.write(content)
f.close()
21 changes: 21 additions & 0 deletions common/pytest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# @Author : yanchunhuo
# @Time : 2020/1/15 14:08
import platform

def deal_pytest_ini_file():
"""
由于当前(2020/1/15)pytest运行指定的pytest.ini在Windows下编码有bug,故对不同环境进行处理
"""
with open('config/pytest.conf','r',encoding='utf-8') as pytest_f:
content=pytest_f.read()
if 'Windows'==platform.system():
with open('config/pytest.ini','w+',encoding='gbk') as tmp_pytest_f:
tmp_pytest_f.write(content)
tmp_pytest_f.close()
else:
with open('config/pytest.ini','w+',encoding='utf-8') as tmp_pytest_f:
tmp_pytest_f.write(content)
tmp_pytest_f.close()
pytest_f.close()


12 changes: 7 additions & 5 deletions config/app_ui_devices_info_template.conf
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ systemports = 8200 ||
# ios并行测试使用,端口建议从5400开始,不用可注释,并行设备都在同一个appium server上时确保每个设备唯一
# wdaLocalPorts = 5400||

# appActivity、appPackage和app(安装包路径)两者选一,不选的放空,多设备仅需填写一个
# 查看当前应用的的appActivity、appPackage
appPackage = com.moji.mjweather
appActivity = com.moji.mjweather.MainActivity
app =
# appActivitys、appPackages和apps_dirs(安装包路径)两者选一,不选的放空,多设备仅需填写一个
# 查看当前应用的的appActivity、appPackage的命令:adb shell dumpsys window | findstr mCurrentFocus
# 单台设备串行测试多个app,使用"##"分割,如appPackages = com.moji.mjweather##com.moji.debug.mjweather ||
appPackages = com.moji.mjweather ||
appActivitys = com.moji.mjweather.MainActivity ||
# app安装包存放的路径,将会遍历目录下所有app包进行串行测试
apps_dirs =
12 changes: 7 additions & 5 deletions config/demoProject/app_ui_devices_info_demoProject.conf
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ systemports = 8200 ||
# ios并行测试使用,端口建议从5400开始,不用可注释,并行设备都在同一个appium server上时确保每个设备唯一
# wdaLocalPorts = 5400||

# appActivity、appPackage和app(安装包路径)两者选一,不选的放空,多设备仅需填写一个
# 查看当前应用的的appActivity、appPackage
appPackage = com.moji.mjweather
appActivity = com.moji.mjweather.MainActivity
app =
# appActivitys、appPackages和apps_dirs(安装包路径)两者选一,不选的放空,多设备仅需填写一个
# 查看当前应用的的appActivity、appPackage的命令:adb shell dumpsys window | findstr mCurrentFocus
# 单台设备串行测试多个app,使用"##"分割,如appPackages = com.moji.mjweather##com.moji.debug.mjweather ||
appPackages = com.moji.mjweather ||
appActivitys = com.moji.mjweather.MainActivity ||
# app安装包存放的路径,将会遍历目录下所有app包进行串行测试
apps_dirs =
2 changes: 1 addition & 1 deletion config/pytest.conf
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ log_file_format=%(asctime)s %(levelname)s %(message)s
log_file_date_format=%Y-%m-%d %H:%M:%S

markers=
search_kw:搜索关键字
search_kw:cases/api/demoProject/api/test_demoProject_login.py 搜索关键字
60 changes: 38 additions & 22 deletions pojo/app_ui_devices_info.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# 作者 yanchunhuo
# 创建时间 2019/12/26 9:17
# github https://github.com/yanchunhuo
import os

class APP_UI_Devices_Info:
def __init__(self):
Expand All @@ -16,9 +16,9 @@ def __init__(self):
self.chromeDriverPorts = []
self.systemports = []
self.wdaLocalPorts = []
self.appPackage = None
self.appActivity = None
self.app = None
self.appPackages = []
self.appActivitys = []
self.apps_dirs = []

def get_devices_info(self):
devices_info = []
Expand All @@ -29,24 +29,40 @@ def get_devices_info(self):
device_info.update({'server_ip':self.server_ips[i].strip()})
device_info.update({'system_auth_alert_label': self.system_auth_alert_labels[i]})
# 构建desired_capabilities
desired_capabilities={}
desired_capabilities.update({'udid':self.udids[i].strip()})
desired_capabilities.update({'platformName': self.platformNames[i].strip()})
if len(self.automationNames):
desired_capabilities.update({'automationName': self.automationNames[i].strip()})
desired_capabilities.update({'platformVersion': self.platformVersions[i].strip()})
if len(self.deviceNames):
desired_capabilities.update({'deviceName': self.deviceNames[i].strip()})
desired_capabilities.update({'chromeDriverPort':self.chromeDriverPorts[i].strip()})
desired_capabilities.update({'systemport': self.systemports[i].strip()})
if len(self.wdaLocalPorts):
desired_capabilities.update({'wdaLocalPort': self.wdaLocalPorts[i].strip()})
if self.appActivity and self.appPackage:
desired_capabilities.update({'appActivity': self.appActivity.strip()})
desired_capabilities.update({'appPackage': self.appPackage.strip()})
if self.app:
desired_capabilities.update({'app': self.app.strip()})
device_info.update({'capabilities':desired_capabilities})
a_device_capabilities_num=0
a_device_appActivitys=[]
a_device_appPackages=[]
a_device_apps=[]
if self.appActivitys and self.appPackages:
a_device_appActivitys=self.appActivitys[i].split('&&')
a_device_appPackages=self.appPackages[i].split('&&')
a_device_capabilities_num=len(a_device_appActivitys)
if self.apps_dirs:
a_device_capabilities_num=len(self.apps_dirs)
paths=os.walk(self.apps_dirs[i])
for dirPath,dirName,fileName in paths:
a_device_apps.append(os.path.join(dirPath,fileName))
a_devices_desired_capabilities=[]
for j in range(a_device_capabilities_num):
desired_capabilities={}
desired_capabilities.update({'udid':self.udids[i].strip()})
desired_capabilities.update({'platformName': self.platformNames[i].strip()})
if len(self.automationNames):
desired_capabilities.update({'automationName': self.automationNames[i].strip()})
desired_capabilities.update({'platformVersion': self.platformVersions[i].strip()})
if len(self.deviceNames):
desired_capabilities.update({'deviceName': self.deviceNames[i].strip()})
desired_capabilities.update({'chromeDriverPort':self.chromeDriverPorts[i].strip()})
desired_capabilities.update({'systemport': self.systemports[i].strip()})
if len(self.wdaLocalPorts):
desired_capabilities.update({'wdaLocalPort': self.wdaLocalPorts[i].strip()})
if self.appActivitys and self.appPackages:
desired_capabilities.update({'appActivity': a_device_appActivitys[j].strip()})
desired_capabilities.update({'appPackage': a_device_appPackages[j].strip()})
if self.apps_dirs:
desired_capabilities.update({'app': a_device_apps[j]})
a_devices_desired_capabilities.append(desired_capabilities)
device_info.update({'capabilities': a_devices_desired_capabilities})
# 完成一台设备构建
devices_info.append(device_info)
return devices_info
7 changes: 6 additions & 1 deletion run_api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# 作者 yanchunhuo
# 创建时间 2018/01/19 22:36
# github https://github.com/yanchunhuo

from common.pytest import deal_pytest_ini_file
from init.api.api_init import api_init
import argparse
import pytest
Expand All @@ -17,13 +19,16 @@
parser.add_argument('-lf', '--lf', help='是否运行上一次失败的用例,1:是、0:否,默认为0')
args=parser.parse_args()

# 处理pytest文件
deal_pytest_ini_file()

# 初始化
print('开始初始化......')
api_init()
print('初始化完成......')

# 执行pytest前的参数准备
pytest_execute_params=['-c', 'config/pytest.conf', '-v', '--alluredir', 'output/api/']
pytest_execute_params=['-c', 'config/pytest.ini', '-v', '--alluredir', 'output/api/']
# 判断目录参数
dir = 'cases/api/'
if args.dir:
Expand Down
Loading

0 comments on commit 4c43e0d

Please sign in to comment.