提交 f0434247 编写于 作者: yuan.luo's avatar yuan.luo

auto test code

上级 a621d22f
文件已添加
此差异已折叠。
因为 它太大了无法显示 源差异 。您可以改为 查看blob
from appium_sync.start_appium import appium_auto_start
from common.caps import appium_caps
from appium_sync.check_port import *
from time import sleep
import multiprocessing
import logging
def start_appium_action(host, port):
if (check_port(host, port)):
logging.info('appium starting')
appium_auto_start(host, port)
return True
else:
release_port(port)
sleep(1)
if (check_port(host, port)):
logging.info('appium starting')
appium_auto_start(host, port)
return True
else:
logging.info('appium %s start fail' % port)
return False
def start_device_action(uuid, port):
host = '127.0.0.1'
if start_appium_action(host, port):
# 等待appium启动
sleep(3)
appium_caps(uuid, port)
else:
logging.info('start appium device fail')
import socket
import os
def check_port(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.shutdown(2)
except OSError as msg:
print('port %s is available' % port)
print(msg)
return True
else:
print('port %s is alrady be in used' % port)
return False
def release_port(port):
cmd_find = 'lsof -i tcp:%s' %port
print(cmd_find)
result = os.popen(cmd_find).read()
if str(port) and 'LISTEN' in result:
if isinstance(result, str):
index = result.split().index('node')
pid = result.split()[index+1]
if pid:
cmd_kill = 'kill %s' %pid
os.popen(cmd_kill)
else:
print('port %s is available' %port)
if __name__ == '__main__':
host = '127.0.0.1'
port = 4723
release_port(port)
import subprocess
from time import ctime
import multiprocessing
from util.tools import get_appium_log_dir
def appium_auto_start(host, port):
bp_port = str(port + 1)
cmd = 'appium -a ' + host + ' -p ' + str(port) + ' -bp ' + str(bp_port)
print('%s at %s' % (cmd, ctime()))
subprocess.Popen(cmd, shell=True, stdout=open(get_appium_log_dir(str(port)), 'a'), stderr=subprocess.STDOUT)
appium_process =[]
for i in range(1):
host = '127.0.0.1'
port = 4723 + 2 * i
appium = multiprocessing.Process(target=appium_auto_start, args=(host, port))
appium_process.append(appium)
if __name__ == '__main__':
# for process in appium_process:
# process.start()
# for process in appium_process:
# process.join()
host = '127.0.0.1'
port = 4723
appium_auto_start(host, port)
class BaseView(object):
def __init__(self, driver):
self.driver = driver
def find_element(self, *loc):
return self.driver.find_element(*loc)
def find_elements(self, *loc):
return self.driver.find_elements(*loc)
def get_window_size(self):
return self.driver.get_window_size()
def swipe(self, start_x, start_y, end_x, end_y, duration):
return self.driver.swipe(start_x, start_y, end_x, end_y, duration)
\ No newline at end of file
import logging
from common.common_fun import Common
from common.caps import appium_caps
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
class LoginView(Common):
mainMeBtn = (By.ID, 'tab_me_item')
loginBtn = (By.ID, 'btn_user_login')
userName = (By.ID, 'doc_name')
login_by_pwd = (By.ID, 'com.picahealth.yunque:id/ll_login_bypwd')
mobile = (By.ID, 'ed_phone')
password = (By.ID, 'ed_pwd')
login_by_wechat = (By.ID, 'iv_wx_login')
settingBtn = (By.ID, 'ic_me_shezhi')
logoutBtn = (By.ID, 'btn_logout')
sureBtn = (By.ID, 'cancel')
def login_pwd(self, userName, password):
if not self.check_login_status():
logging.info('start login')
self.driver.find_element(*self.login_by_pwd).click()
self.driver.find_element(*self.mobile).send_keys(userName)
self.driver.find_element(*self.password).send_keys(password)
self.driver.find_element(*self.loginBtn).click()
def login_wechat(self):
pass
def check_login_status(self):
self.checkActive()
# self.checkAppUpGrade()
try:
self.driver.find_element(*self.mainMeBtn).click()
self.driver.find_element(*self.userName)
except NoSuchElementException:
logging.info('current is not logined')
return False
else:
logging.info('current is logined')
self.getScreenShot('logined')
return True
def logout(self):
if self.check_login_status():
logging.info('start logout')
self.driver.find_element(*self.settingBtn).click()
self.driver.find_element(*self.logoutBtn).click()
self.driver.find_element(*self.sureBtn).click()
if __name__ == '__main__':
driver = appium_caps()
l = LoginView(driver)
l.login_pwd('15606680071', '15606680072')
l.check_login_status()
import logging
from common.caps import appium_caps
from selenium.webdriver.common.by import By
from businessView.loginView import LoginView
class ModifyEdu(LoginView):
mainMeTop = (By.ID, 'main_me_top')
modifyEduBtn = (By.ID, 'tv_edu_info_edit')
schoolInput = (By.ID, 'doc_school')
majorInput = (By.ID, 'doc_major')
majorListItem = (By.ID, 'item_layout')
eduInput = (By.ID, 'doc_education')
yearInput = (By.ID, 'admin_enrollment_year')
def modify_education(self, schoolName):
self.login_pwd('15606680071', '15606680072')
logging.info('go to myInfo activity')
self.driver.find_element(*self.mainMeTop).click()
self.driver.find_element(*self.modifyEduBtn).click()
self.driver.find_element(*self.schoolInput).send_keys(schoolName)
self.driver.find_element(*self.majorInput).click()
self.driver.find_elements(*self.majorListItem)[1].click()
self.driver.find_element(*self.eduInput).click()
self.driver.find_elements(*self.majorListItem)[3].click()
self.driver.find_element(*self.yearInput).click()
self.driver.find_elements(*self.majorListItem)[4].click()
self.driver.find_element(*self.modifyEduBtn).click()
def check_modify_edu(self, schoolName):
self.getScreenShot('modify_education')
if schoolName == self.driver.find_element(*self.schoolInput).get_attribute('text'):
logging.info('modify edu success')
return True
else:
logging.info('modify edu fail')
return False
if __name__ == '__main__':
driver = appium_caps()
m = ModifyEdu(driver)
m.modify_education('西安邮电大学')
m.check_modify_edu('西安邮电大学')
此差异已折叠。
import unittest
from common.caps import appium_caps
import logging
from time import sleep
class StartEnd(unittest.TestCase):
def setUp(self):
logging.info('test case setup')
self.driver = appium_caps()
def tearDown(self):
logging.info('test case tearDown')
sleep(5)
self.driver.close_app()
from appium import webdriver
import yaml
import logging
import logging.config
import os
import multiprocessing
from util.tools import get_config_dir
CON_LOG= get_config_dir() + "log.conf"
logging.config.fileConfig(CON_LOG)
logging=logging.getLogger()
# 多设备
device_list = []
# 保留参数,多设备使用
def appium_caps(uuid='', port=''):
with open(get_config_dir() + 'setting.yaml', 'r', encoding='utf-8') as f:
deviceInfo = yaml.load(f, Loader=yaml.FullLoader)
caps = {}
caps["platformName"] = deviceInfo['platformName']
caps["platformVersion"] = deviceInfo['platformVersion']
caps["deviceName"] = deviceInfo['deviceName']
caps["automationName"] = deviceInfo['automationName']
base_dir = os.path.dirname(os.path.dirname(__file__))
app_path = os.path.join(base_dir, 'app', deviceInfo['app'])
caps["app"] = app_path
caps["appPackage"] = deviceInfo['appPackage']
caps["appActivity"] = deviceInfo['appActivity']
caps["noReset"] = deviceInfo['noReset']
logging.info('start app...')
driver = webdriver.Remote("http://" + str(deviceInfo['host'] + ":" + str(deviceInfo['port']) + "/wd/hub"), caps)
driver.implicitly_wait(5)
return driver
caps_process = []
# for i in range(len(device_list)):
# port = 4723 + 2*i
# caps = multiprocessing.Process(target=appium_caps, args=())
# caps_process.append(caps)
for i in range(1):
port = 4723 + 2*i
caps = multiprocessing.Process(target=appium_caps)
caps_process.append(caps)
if __name__ == '__main__':
# appium_caps()
for cap in caps_process:
cap.start()
for cap in caps_process:
cap.join()
\ No newline at end of file
from baseView.baseView import BaseView
from common.caps import appium_caps
from selenium.common.exceptions import NoSuchElementException
import logging
import time
import os
from selenium.webdriver.common.by import By
import csv
class Common(BaseView):
skipBtn = (By.ID, 'adv_text')
activeBtn = (By.ID, 'notice_close')
upGradeBtn = (By.ID, 'btn_ignore')
def check_skip(self):
logging.info('check spnash activity')
try:
skip = self.driver.find_element(*self.skipBtn)
except NoSuchElementException:
pass
else:
logging.info('skip spnash button')
skip.click()
def get_size(self):
x = self.driver.get_window_size()['width']
y = self.driver.get_window_size()['height']
return x, y
def swipeLeft(self):
size = self.get_size()
x1 = int(size[0] * 0.9)
y1 = int(size[1] * 0.5)
x2 = int(size[0] * 0.1)
self.swipe(x1, y1, x2, y1, 1000)
def swipeRight(self):
size = self.get_size()
x1 = int(size[0] * 0.9)
y1 = int(size[1] * 0.5)
x2 = int(size[0] * 0.1)
self.swipe(x2, y1, x1, y1, 1000)
def swipeUp(self):
size = self.get_size()
x1 = int(size[0] * 0.5)
y1 = int(size[1] * 0.9)
y2 = int(size[1] * 0.1)
self.swipe(x1, y1, x1, y2, 1000)
def swipeDown(self):
size = self.get_size()
x1 = int(size[0] * 0.5)
y1 = int(size[1] * 0.9)
y2 = int(size[1] * 0.1)
self.swipe(x1, y2, x1, y1, 1000)
def getTime(self):
self.now = time.strftime("%Y-%m-%d %H_%M_%S")
return self.now
def getScreenShot(self, module):
time = self.getTime()
image_file=os.path.dirname(os.path.dirname(__file__))+'/screenshots/%s_%s.png' %(module, time)
logging.info('get %s screenshot' %module)
self.driver.save_screenshot(image_file)
def checkActive(self):
time.sleep(1)
logging.info('check active ad')
try:
active = self.driver.find_element(*self.activeBtn)
except NoSuchElementException:
logging.info('no active alive')
else:
logging.info('skip active button')
active.click()
def checkAppUpGrade(self):
time.sleep(1)
logging.info('check app upgrade')
try:
upgrade = self.driver.find_element(*self.upGradeBtn)
except NoSuchElementException:
logging.info('no app upgrade alive')
else:
logging.info('skip app upgrade button')
upgrade.click()
def get_csv_data(self, csc_file, line):
logging.info('get csv account')
with open(csc_file, 'r', encoding='utf-8-sig') as file:
reader = csv.reader(file)
for index, row in enumerate(reader,1):
if index == line:
return row
if __name__ == '__main__':
# driver=appium_caps()
# com = Common(driver)
# com.getScreenShot('start app')
csv_file = '../data/account.csv'
[loggers]
keys=root, info
[logger_root]
level=DEBUG
handlers=consoleHandler, fileHandler
[logger_info]
handlers=consoleHandler, fileHandler
qualname=info
propagate=0
[handlers]
keys=consoleHandler, fileHandler
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=form01
args=("../caseLogs/runlog.log", 'a')
[formatters]
keys=form01, form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
[formatter_form02]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
platformName: Android
platformVersion: 8.0.0
deviceName: SM-G9550
#uuid:
#deviceName:
app: yunqueyi.apk
noReset: False
unicodeKeyboard: True
automationName: uiautomator2
resetKeyboard: True
appPackage: com.picahealth.yunque
appActivity: .activitys.mainpage.InitWelcomeActivityVideo
host: 127.0.0.1
port: 4723
\ No newline at end of file
15606680071,15606680072
15606680072,abcdefg
15606680071,15606680071
\ No newline at end of file
import time
from unittest import TestCase
from appium import webdriver
from util import config
from util import tools
class Login(TestCase):
def setUp(self):
self.driver = webdriver.Remote(config.host, config.get_caps())
def tearDown(self):
pass
def test_login_code(self):
tools.get_app_log("test_login_code")
time.sleep(1)
try:
self.driver.find_element_by_id("tv_exist_account").click()
time.sleep(2)
self.driver.find_element_by_id("ll_login_bycode").click()
time.sleep(1)
self.driver.find_element_by_id("ed_phone").send_keys("15606680071")
self.driver.find_element_by_id("ed_code").send_keys("089898")
self.driver.find_element_by_id("btn_user_login").click()
except Exception as e:
self.driver.save_screenshot(tools.get_screenshot_dir("test_login_code"))
print(e)
tools.save_log(e)
def test_login_pwd(self):
time.sleep(1)
try:
self.driver.find_element_by_id("tv_exist_account").click()
time.sleep(2)
self.driver.find_element_by_id("ll_login_bypwd").click()
time.sleep(1)
self.driver.find_element_by_id("ed_phone").send_keys("15606680071")
self.driver.find_element_by_id("ed_pwd").send_keys("15606680072")
self.driver.find_element_by_id("btn_user_login").click()
except Exception as e:
self.driver.save_screenshot(tools.get_screenshot_dir("test_login_pwd"))
print(e)
tools.save_log(e)
def test_login_wechat(self):
time.sleep(2)
try:
self.driver.find_element_by_id("bt_next").click()
time.sleep(2)
self.driver.find_element_by_id("ed_phone").send_keys("15606680071")
# Tools.get_validate_code(self)
self.driver.find_element_by_id("ed_code").send_keys("245456")
self.driver.find_element_by_id("ed_pwd").send_keys("123456a")
time.sleep(1)
self.driver.find_element_by_id("btn_user_login").click()
self.driver.save_screenshot(tools.set_file_path('images/') + 'Login.png')
except Exception as e:
print(e)
\ No newline at end of file
import time
from unittest import TestCase
from appium import webdriver
from util import config
from util import tools
class Register(TestCase):
def setUp(self):
self.driver = webdriver.Remote(config.host, config.get_caps())
def tearDown(self):
pass
def test_register(self):
time.sleep(2)
try:
self.driver.find_element_by_id("bt_next").click()
time.sleep(2)
self.driver.find_element_by_id("ed_phone").send_keys("15606680071")
# Tools.get_validate_code(self)
self.driver.find_element_by_id("ed_code").send_keys("245456")
self.driver.find_element_by_id("ed_pwd").send_keys("123456a")
time.sleep(1)
self.driver.find_element_by_id("btn_user_login").click()
except Exception as e:
self.driver.save_screenshot(tools.get_screenshot_dir("test_login_code"))
print(e)
tools.save_log(e)
import unittest import unittest
import time import time, logging
import HTMLTestRunner import HTMLTestRunner
from functions.login import Login from test_case.test_login import TestLogin
from functions.register import Register from test_case.test_modify_edu import TestModifyEdu
from util import tools from appium_sync.appium_device import start_appium_action
from util.tools import get_dir_by_name
from appium_sync.check_port import release_port
from time import sleep
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(Login("test_login_code"))
suite.addTest(Login("test_login_pwd"))
suite.addTest(Register("test_register"))
filename = tools.get_report_dir() + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + '_result.html' test_dir = get_dir_by_name('test_case')
report_dir =get_dir_by_name('reports')
now = time.strftime("%Y_%m_%d_%H_%M_%S")
report_name = report_dir + '/' + now + '_result.html'
fp = open(filename, 'wb') with open(report_name, 'wb') as file:
runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='测试报告', description='用例执行情况:') start_appium_action('127.0.0.1', 4723)
sleep(2)
suite = unittest.TestSuite()
suite.addTest(TestLogin("test_login_by_psw"))
suite.addTest(TestModifyEdu("test_modify_edu"))
runner = HTMLTestRunner.HTMLTestRunner(stream=file, title='云鹊医测试报告', description='用例执行情况:')
logging.info('start run test case')
runner.run(suite) runner.run(suite)
fp.close() release_port('4723')
from common.baseUnit import StartEnd
from businessView.loginView import LoginView
import unittest
import logging
class TestLogin(StartEnd):
csv_file = '../data/account.csv'
def test_login_by_psw(self):
logging.info('test login by psw')
l = LoginView(self.driver)
data = l.get_csv_data(self.csv_file, 1)
l.login_pwd(data[0], data[1])
self.assertTrue(l.check_login_status())
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
from common.baseUnit import StartEnd
from businessView.modifyEdu import ModifyEdu
import unittest
import logging
class TestModifyEdu(StartEnd):
schoolName = '湖畔大学'
def test_modify_edu(self):
logging.info('test modify edu')
m = ModifyEdu(self.driver)
m.modify_education(schoolName=self.schoolName)
self.assertTrue(m.check_modify_edu(schoolName=self.schoolName))
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
CONFIG = {
'PHONE_VERSION': '6.0.1',
'HOST': "http://localhost:4723/wd/hub"
}
host = "http://localhost:4723/wd/hub"
def get_caps(version="8.0.0"):
caps = {}
caps["platformName"] = "Android"
caps["platformVersion"] = version
caps["deviceName"] = "SM-G9550"
caps["appPackage"] = "com.picahealth.yunque"
caps["appActivity"] = ".activitys.mainpage.InitWelcomeActivityVideo"
return caps
# class BasicCase(TestCase):
# def __init__(self):
# self.driver = webdriver.Remote(get_caps(CONFIG['PHONE_VERSION']), CONFIG['HSOT'])
import os import os
import time import time
# 捕获验证码 # 捕获验证码
def get_validate_code(self): def get_validate_code(self):
cmd_c = 'adb logcat -c' cmd_c = 'adb logcat -c'
...@@ -18,26 +19,47 @@ def get_validate_code(self): ...@@ -18,26 +19,47 @@ def get_validate_code(self):
raise ValueError raise ValueError
return code return code
#app running log
# app running log
def get_app_log(name): def get_app_log(name):
cmd_log = "adb logcat -c && adb logcat > " + get_app_log_dir(name) # cmd_log = "adb logcat -c && adb logcat > " + get_app_log_dir(name)
os.popen(cmd_log) # os.popen(cmd_log)
pass
def save_log(log): def save_log(log):
pass pass
# 保存截图地址 # 保存截图地址
def get_screenshot_dir(name): def get_screenshot_dir(name):
return set_file_path('images/') + name + '.png' return set_file_path('images/') + name + '.png'
# 保存app运行日志地址 # 保存app运行日志地址
def get_app_log_dir(name): def get_app_log_dir(name):
return set_file_path('appLogs/') + name + '.txt' return set_file_path('appLogs/') + name + '.log'
# 保存case运行日志地址 # 保存case运行日志地址
def get_case_log_dir(name): def get_case_log_dir(name):
return set_file_path('caseLogs/') + name + '.txt' return set_file_path('caseLogs/') + name + '.log'
# 保存appium运行日志地址
def get_appium_log_dir(name):
return set_file_path('appiumLogs/') + name + '.log'
# 获取配置地址
def get_config_dir():
return set_file_path('configs/')
# 获取绝对地址
def get_dir_by_name(name):
return set_file_path(name + '/')
# 保存报告地址 # 保存报告地址
def get_report_dir(): def get_report_dir():
...@@ -47,7 +69,8 @@ def get_report_dir(): ...@@ -47,7 +69,8 @@ def get_report_dir():
def get_project_path(): def get_project_path():
return os.path.abspath(os.path.join(os.path.dirname('__file__'), os.path.pardir)) return os.path.abspath(os.path.join(os.path.dirname('__file__'), os.path.pardir))
def set_file_path(pathname): def set_file_path(pathname):
par_dir = get_project_path() par_dir = get_project_path()
return os.path.join(par_dir, pathname) return os.path.join(par_dir, pathname)
\ No newline at end of file
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册