python实现ecshop开源商城登陆自动化测试
2022-07-20 14:23:40 237
Python 软件测试 自动化脚本
python实现ecshop开源商城账号登陆自动化测试,需求:提取excel表格里的测试数据进行自动化登陆账号,判断实际结果与预期结果是否匹配。 导入包: ```python import xlrd from selenium import webdriver from time import sleep ``` 获取自动化测试数据: ```python def get_test_data(path): date = xlrd.open_workbook(path) sheet_names = date.sheet_names() table = date.sheet_by_name(sheet_names[0]) rows = table.nrows for i in range(1, rows): row_content = table.row_values(i) tcid = (row_content[0]) username = (row_content[1]) password = int(row_content[2]) expected = (row_content[3]) test_case(tcid, username, password, expected) ``` 测试用例部分: ```python def test_case(tcid, username, password, expected): driver = webdriver.Chrome() driver.get('http://localhost/user.php') sleep(4) driver.find_element_by_name('username').send_keys(username) sleep(2) driver.find_element_by_name('password').send_keys(password) sleep(2) driver.find_element_by_name('submit').click() sleep(4) a = isElementExist(driver, '/html/body/div[6]/div[2]/div/div/div/font') if a: b = "登陆成功" if expected == b: print(tcid + "\t预期结果为:" + expected + ",实际结果:登陆成功。测试结果Pass") else: print(tcid + "\t预期结果为:" + expected + ",实际结果:登陆失败。测试结果Fail") else: b = "登陆失败" if expected == b: print(tcid + "\t预期结果为:" + expected + ",实际结果:登陆失败。测试结果Pass") else: print(tcid + "\t预期结果为:" + expected + ",实际结果:登陆成功。测试结果Fail") driver.quit() ``` 异常处理: ```python def isElementExist(a, element): flag = True driver = a try: driver.find_element_by_xpath(element) return flag except: flag = False return flag ``` 执行测试: ```python if __name__ == '__main__': get_test_data("D:\\MY_TEST\\selenium\\login\\info.xlsx") ``` 测试数据: ![在这里插入图片描述](https://img-blog.csdnimg.cn/2020032622155419.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDU0NjM0MA==,size_16,color_FFFFFF,t_70) 最后: **人生苦短,我用python.....** 哈哈继续努力学习!
uiautomator2+adb shell input tap 实现微博自动取消关注
2022-07-20 14:22:53 365
Python 自动化脚本
很久没有玩微博了,最近无意间打开微博想刷刷新闻,不看不知道一看吓一跳,我关注的人既然超过了一千多人,我的天,我什么时候关注了这么多人?我立即进入我关注的人寻找批量取消关注按钮,当时我恨不得直接全部删除,遗憾的是,我找了半小时都没有找到能一键取消所有的关注,555…… ,百度一番,网友介绍可以使用微博反垃圾修正关注,于是我抱着信心去修正我的关注了,可是……一个月只能修正一次,而且一次只修掉了几个或十几个人…………我……,于是乎我被迫打开sublime,然后写下了import uiautomator2…… **首先导入需要的库:** ```python import uiautomator2 as u2 import time import subprocess import re ``` **第一步,打开微博进入我的关注页面,获取‘已关注“按钮的坐标:** ```python def auto(): subprocess.run("adb shell am start com.sina.weibo/com.sina.weibo.MainTabActivity") time.sleep(1) device(description="我").click() device(resourceId="com.sina.weibo:id/cabFollow").click() device(text="关注的人").click() time.sleep(0.5) #获取所有”已关注“按钮信息 for i in device(text="已关注"): data = i.info data = str(data) #通过正则获取x和y坐标 com = re.compile(".*?left':(.*?),.*?") com_1 = re.compile(".*?top':(.*?)}.*?") left = re.findall(com, data) top = re.findall(com_1, data) return left[0], top[0] ``` 在auto方法里,我开始是使用uiautomator2 库去点击”已关注“按钮,本以为这样就可以愉快的自动取消关注了,可……人算不如天算啊!uiautomator2点不上”已关注“这个按钮,后面经过多轮的测试,我发现原来是uiautomator2里点击方法**压下按钮到松开按钮时间太久了**,也就是点击太慢……这这这 怎么办了? 于是无奈使用”adb shell input tap“,通过按钮的x y 坐标去点击按钮,但又有一个新的问题,我并不能确定每把手机的屏幕都是相同分辨率,在沉思了片刻后,我突然想到uiautomator2虽然无法点击”已关注“按钮,但我可以通过它获取”已关注“按钮的坐标啊!话落就干,盘它…… **第二步,点击”已关注“按钮,如果当前页面没有”已关注“按钮,就滑动屏幕:** ```python def main(): while True: try: while True: data = auto() subprocess.run("adb shell input tap {} {}".format(data[0], data[1])) device(text="确定").click() except: subprocess.run("adb shell input swipe 100 400 100 100") ``` **效果:** ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200331232458757.gif) 最后还是那句话,人生苦短,我用python,预祝我们早日成为大神……………… 更多文章、小工具请访问我的个人博客:https://www.zztdd.cn/
python + selenium + unittest 实现网站登录注册自动化测试
2022-07-20 14:22:19 234
Python Selenium 自动化脚本 软件测试
推荐一个在线工具网站:[在线工具大全](https://www.zztdd.cn) 登录封装: ```python from selenium import webdriver import time class Auto(object): def __init__(self, *args): login_url = 'https://snail.zhuozhuo.io/?n=fastCat.fcFrontSnail.NewFront.NewFront.PCLoginPage' register_url = "https://getsuwo.com/?n=fastCat.fcFrontSnail.NewFront.NewFront.PCRegisterPage" InRegisterAuto_url = "https://getsuwo.com/?n=fastCat.fcFrontSnail.NewFront.NewFront.PCInternationalRegisterPage" driver = webdriver.Chrome() self.driver = driver self.login_url = login_url self.register_url = register_url self.InRegisterAuto_url = InRegisterAuto_url self.args = args #登录页面 def loginAuto(self): self.driver.implicitly_wait(5) self.driver.get(self.login_url) self.error('self.driver.find_element_by_name("Username").send_keys(self.args[0])') self.error('self.driver.find_element_by_name("Password").send_keys(self.args[1])') self.driver.find_element_by_css_selector("[type='submit']").click() try: time.sleep(0.5) result = self.driver.find_element_by_class_name("ErrorMsg").text return result except: return finally: self.driver.quit() ``` 登录用例执行: ```python import unittest import warnings from Tool import Auto class ExecuteCase(unittest.TestCase): def setUp(self): warnings.simplefilter('ignore', ResourceWarning) # 处理unittest警告信息 # 测试账号(test_1 -- test_8),登录页面账号未作格式校验 def test_1(self): '''所有输入框为空''' expectResult = "帐号不能为空" login = Auto() actualResult = login.loginAuto() self.assertEqual(expectResult, actualResult) def test_2(self): '''输入12位手机号,密码为空,值为:184883658555''' expectResult = "手机号码格式不正确" login = Auto("184883658555") actualResult = login.loginAuto() self.assertEqual(expectResult, actualResult) def test_3(self): '''输入10位手机号,密码为空,值为:1848365858''' expectResult = "手机号码格式不正确" login = Auto("1848365858") actualResult = login.loginAuto() self.assertEqual(expectResult, actualResult) ``` 等等…… [详细源码,请访问github](https://github.com/ZhongTian5/selenium) 推荐一个免费的在线小工具网站:https://www.zztdd.cn/
对于谷歌认证测试(xTS),分享一下自己在工作中编写的一些脚本。
2022-07-20 14:20:55 328
Python xTS(谷歌认证测试) 自动化脚本
算上实习,我在安卓测试工作岗位上已经做了近4年了,而在xTS模块测试中有差不多2年多时间。如今我已经换工作岗位,我想这辈子或许再也不会接触xTS、GTS、VTS、STS、Verififer等等测试了吧,曾经很努力很努力的学习相关知识,想想过程中付出的所有,对于我来说都是一种收获!现在我已经重新启航,进入了一个新的工作岗位。加油! 推荐一个在线工具网站:[在线工具大全](https://www.zztdd.cn) **xTS自动化执行:** 1.配置文件: ``` [config] test_item = GTS executed_file = ../tools/gts-tradefed executed_command = run gts -m GtsSimAppDialogTestCases -t com.google.android.simappdialog.gts.InstallCarrierAppActivityTest#testNotificationOnlyDuringSetupWizard -s BH950020JN executed_command_1 = gts full_run_number = 1 device_number = 3 device1 = device2 = device3_uicc = 设备SN号 device4_se = 设备SN号 device5_sim = 设备SN号 device_set_all = 设备SN号 ``` 2.python 部分代码(全部代码请访问:[all code](https://github.com/zztroot/xtsTest)) ```python import os import time import re try: from bs4 import BeautifulSoup import configparser from prettytable import PrettyTable except: os.system("pip3 install bs4") os.system("pip3 install configparser") os.system("pip3 install prettytable") time.sleep(1) from bs4 import BeautifulSoup import configparser from prettytable import PrettyTable def executed_xts(runfile, command, seconds): time.sleep(2) run = 'gnome-terminal -- ' + runfile + ' ' + command width = os.get_terminal_size().columns print("*".center(width, '*')) os.system(run) time.sleep(seconds) files = os.listdir("../results/") files = sorted(files) if len(files) % 2 == 0: if len(files) >= 2: return files[-2] else: return files[0] elif len(files) % 2 == 1: return files[-1] def if_result_done(resul_file): files_zip = "../results/" + resul_file + ".zip" if os.path.exists(files_zip): return resul_file else: return "not done" def check_results(file_name): filepath = os.getcwd() path = re.findall("(.*?).autoXts", filepath) new_path = path[0] url = os.path.join(new_path + "/results/" + file_name + "/test_result_failures_suite.html") with open(url, 'r') as f: soup = BeautifulSoup(f.read(), 'lxml').html result_pass = re.findall('.*?<td class="rowtitle">Tests Passed</td>.*?>(.*?)</.*?', str(soup)) result_fail = re.findall('.*?<td class="rowtitle">Tests Failed</td>.*?>(.*?)</.*?', str(soup)) result_module_done = re.findall('.*?<td class="rowtitle">Modules Done</td>.*?>(.*?)</.*?', str(soup)) result_module_total = re.findall('.*?<td class="rowtitle">Modules Total</td>.*?>(.*?)</.*?', str(soup)) results_list = [result_pass[0], result_fail[0], result_module_done[0], result_module_total[0]] if result_fail[0] == "0": return results_list, "done" fail_module_name = re.findall('.*?<td class="module" colspan="3"><a.*?>.*?(C.*?)</a>.*?', str(soup)) se_cases = "CtsSecureElementAccessControlTestCases1" or \ "CtsSecureElementAccessControlTestCases2" or \ "CtsSecureElementAccessControlTestCases3" or \ "CtsSecureElementAccessControlTestCases1[instant]" or \ "CtsSecureElementAccessControlTestCases2[instant]" or \ "CtsSecureElementAccessControlTestCases3[instant]" or \ "VtsHalSecureElementV1_0Target" if se_cases in fail_module_name: return results_list, "se" sim_cases = "CtsTelecomTestCases" or \ "CtsTelecomTestCases2" or \ "CtsTelecomTestCases3" or \ "CtsTelephony2TestCases" or \ "CtsTelephony2TestCases[instant]" or \ "CtsTelephony3TestCases" or \ "CtsTelephonyProviderTestCases" or \ "CtsTelephonySdk28TestCases" or \ "CtsTelephonyTestCases" or \ "CtsPermissionTestCasesTelephony" or \ "CtsPermissionTestCasesTelephony[instant]" or \ "GtsTelephonyTestCases" or \ "GtsTelecomManagerTests" or \ "VtsHalAudioEffectV5_0Target" or \ "VtsHalAudioV2_0Target" or \ "VtsHalAudioV5_0Target" or \ "VtsHalRadioConfigV1_0Target" if sim_cases in fail_module_name: return results_list, "sim" uicc_cases = "CtsCarrierApiTestCases" or "GtsSimAppDialogTestCases" if uicc_cases in fail_module_name: return results_list, "uicc" return results_list, "all" ```
Python手机自动化脚本
2022-07-20 14:19:31 252
Python 自动化脚本
```python # !/usr/bin/python # _*_ coding:utf-8 _*_ import os import re import time from colorama import init init(autoreset=True) # 获取电脑屏幕的宽度 width = os.get_terminal_size().columns # 自动wifi连接 def auto_wifi_connect(): print("\033[0;32;40m自动连接wifi\033[0m".center(width, '*')) os.popen("adb push WifiConfigStore.xml /data/misc/wifi/") os.popen("adb reboot") # 计时 index = 1 while True: time.sleep(1) if len(get_devices_sn()) > 0: break else: # 最大等待时间1分钟 if index == 90: print("\033[0;31;40m手机重启超时\033[0m".center(width, '*')) return index += 1 continue os.popen("adb root") # 打开飞行模式 def open_flight_mode(): print("\033[0;32;40m打开飞行模式\033[0m".center(width, '*')) os.popen("adb shell settings put global airplane_mode_on 1") os.popen("adb shell am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true") # 设置熄屏 def rest_screen(): # 等待30分钟 time.sleep(1800) print("\033[0;32;40m熄灭屏幕-等待30秒\033[0m".center(width, '*')) os.popen("adb shell input keyevent 26") # 执行命令 def execute_command(): print("\033[0;32;40m执行命令(location off and duraspeed off)\033[0m".center(width, '*')) os.popen("location off") os.popen("duraspeed off") # 主函数 def main(): print('''* 1.手机需要先连上wifi,然后输入"adb pull /data/misc/wifi/WifiConfigStore.xml"拉取出"WifiConfigStore.xml"文件。''') print('''* 2.将"WifiConfigStore.xml"文件放在zzt_auto.py(脚本)或zzt_auto.exe同级目录,未push文件的手机必须做一次。''') input_data = input('''* 请告诉我,需要push "WifiConfigStore.xml"文件到手机吗?这个过程会重启手机(Y/Enter)''') # 检测手机是否连接和获取sn号 sn_list = get_devices_sn() if len(sn_list) < 1: print("\033[0;31;40m没有手机连接\033[0m".center(width, '*')) return print("\033[0;32;40mSN:{}\033[0m".format(sn_list[0]).center(width, '*')) # adb root os.popen("adb root") # 自动连接wifi if input_data == "Y" or input_data == "y": auto_wifi_connect() os.popen("adb shell svc wifi enable") # 打开飞行模式 open_flight_mode() # 熄灭屏幕 rest_screen() # 执行命令 execute_command() # 结束 print("\033[0;32;40m测试完成\033[0m".format(sn_list[0]).center(width, '*')) # 获取SN号 def get_devices_sn(): sn_list = [] device_info = os.popen('adb devices').read() for line in device_info.splitlines(): if line == 'List of devices attached': continue else: com = re.compile('(.*?)\tde.*?') sn = re.findall(com, line) for i in sn: sn_list.append(i) return sn_list if __name__ == '__main__': try: main() except: input("输入任意字符结束") ```