第一个python&selenium自动化测试实战项目

说明:本项目采用流程控制思想,未引用unittest&pytest等单元测试框架

一.项目介绍

目的

测试某官方网站登录功能模块可以正常使用

用例

1.输入格式正确的用户名和正确的密码,验证是否登录成功;
2.输入格式正确的用户名和不正确的密码,验证是否登录失败,并且提示信息正确;
3.输入格式正确的用户名和任意密码,验证是否登录失败,并且提示信息正确;
4.用户名和密码两者都为空,验证是否登录失败,并且提示信息正确;
5.用户名和密码两者之一为空,验证是否登录失败,并且提示信息正确;

环境

Windows10 +Python3.6+selenium3.13+Pycharm

环境我想大多数人都会搭建,有事没事找百度,一搜一箩筐,哈哈!我自己刚学的时候也是各种问题各种百度,好在都解决了,感谢有度娘这么强大的存在!这里就不写环境怎么搭建了,直接进入主题

二.脚本设计

目的

我们的测试脚本需要达到:脚本可移植,脚本模块化,测试数据分离,输出测试报告 等目的

脚本设计模式

    第一个python&selenium自动化测试实战项目

代码实现

项目目录结构

    第一个python&selenium自动化测试实战项目

注:下面的文件存放在同一个目录下

 #! user/bin/python
'''
代码说明:麦子学院登录模块自动化测试用例脚本
编写日期:
设置者:linux超
''' import time
from selenium import webdriver
from webinfo import webinfo
from userinfo import userinfo
from log_fiile import login_log
from pathlib import Path def open_web():
driver = webdriver.Firefox()
driver.maximize_window()
return driver def load_url(driver,ele_dict):
driver.get(ele_dict['Turl'])
time.sleep(5) def find_element(driver,ele_dict):
# find element
driver.find_element_by_class_name(ele_dict['image_id']).click()
if 'text_id' in ele_dict:
driver.find_element_by_link_text('登录').click() user_id = driver.find_element_by_id(ele_dict['userid'])
pwd_id = driver.find_element_by_id(ele_dict['pwdid'])
login_id = driver.find_element_by_id(ele_dict['loginid'])
return user_id,pwd_id,login_id def send_val(ele_tuple,arg):
# input userinfo
listkey = ['uname','pwd']
i = 0
for key in listkey:
ele_tuple[i].send_keys('')
ele_tuple[i].clear()
ele_tuple[i].send_keys(arg[key])
i+=1
ele_tuple[2].click()
def check_login(driver,ele_dict,log,userlist):
result = False
time.sleep(3)
try:
err = driver.find_element_by_id(ele_dict['error'])
driver.save_screenshot(err.text+'.png')
log.log_write('账号:%s 密码:%s 提示信息:%s:failed\n' %(userlist['uname'],userlist['pwd'],err.text))
print('username or password error')
except:
print('login success!')
log.log_write('账号:%s 密码:%s :passed\n'%(userlist['uname'],userlist['pwd']))
#login_out(driver,ele_dict)
return True
return result
def login_out(driver,ele_dict):
driver.find_element_by_class_name(ele_dict['logout']).click()
'''
def screen_shot(err):
i = 0
save_path = r'D:\pythondcode\capture'
capturename = '\\'+str(i)+'.png'
wholepath = save_path+capturename
if Path(save_path).is_dir():
pass
else:
Path(save_path).mkdir()
while Path(save_path).exists():
i+=1
capturename = '\\'+str(i)+'.png'
wholepath = save_path + capturename
err.screenshot(wholepath)
'''
def login_test():
log = login_log()
#ele_dict = {'url': 'http://www.maiziedu.com/', 'text_id': '登录', 'user_id': 'id_account_l', 'pwd_id': 'id_password_l'
#, 'login_id': 'login_btn','image_id':'close-windows-btn7','error_id':'login-form-tips'}
ele_dict = webinfo(r'D:\pythoncode\webinfo.txt')
#user_list=[{'uname':account,'pwd':pwd}]
user_list = userinfo(r'D:\pythoncode\userinfo.txt')
driver = open_web()
# load url
load_url(driver,ele_dict)
#find element
ele_tuple = find_element(driver,ele_dict)
# send values
ftitle = time.strftime('%Y-%m-%d', time.gmtime())
log.log_write('\t\t\t%s登录系统测试报告\n' % (ftitle))
for userlist in user_list:
send_val(ele_tuple,userlist)
# check login success or failed
result = check_login(driver,ele_dict,log,userlist)
if result:
login_out(driver,ele_dict)
time.sleep(3)
ele_tuple = find_element(driver,ele_dict)
time.sleep(3)
log.log_close()
driver.quit() if __name__ == '__main__':
login_test()

login_test.py

 #! user/bin/python
'''
代码说明:从文本文档中读取用户信息
编写日期:
设置者:linux超
''' import codecs def userinfo(path):
file = codecs.open(path,'r','utf-8')
user_list = []
for line in file:
user_dict = {}
result = [ele.strip() for ele in line.split(';')]
for sult in result:
re_sult = [ele.strip() for ele in sult.split('=')]
user_dict.update(dict([re_sult]))
user_list.append(user_dict)
return user_list if __name__ == '__main__':
user_list = userinfo(r'D:\pythoncode\userinfo.txt')
print(user_list)

userinfo.py

 #! user/bin/python
'''
代码说明:从文本文档中读取web元素
编写日期:
设置者:linux超
''' import codecs def webinfo(path):
file = codecs.open(path,'r','gbk')
ele_dict = {}
for line in file:
result = [ele.strip() for ele in line.split('=')]
ele_dict.update(dict([result]))
return ele_dict if __name__ == '__main__':
ele_dict = webinfo(r'D:\pythoncode\webinfo.txt')
for key in ele_dict:
print(key,ele_dict[key])

webinfo.py

 #! user/bin/python
'''
代码说明:测试输出报告
编写日期:
设置者:linux超
''' import time class login_log(object):
def __init__(self,path='',mode='w'):
filename = path + time.strftime('%Y-%m-%d',time.gmtime())
self.log = open(path+filename+'.txt',mode)
def log_write(self,msg):
self.log.write(msg)
def log_close(self):
self.log.close()
if __name__ == '__main__':
log=login_log()
ftitle = time.strftime('%Y-%m-%d',time.gmtime())
log.log_write('xiaochao11520')
log.log_close()

log_file.py

 uname=273839363@qq.com;pwd=xiaochao11520
uname=273839363;pwd=xiaochao11520
uname= ;pwd=xiaochao11520
uname=273839363@qq.com;pwd=
uname=2738;pwd=xiaochao

userinfo.txt

 Turl=http://www.maiziedu.com/
text_id=登录
userid=id_account_l
pwdid=id_password_l
loginid=login_btn
error=login-form-tips
logout=sign_out
image_id=close-windows-btn7

webinfo.py

实在是不擅长写文章,写完感觉内容好少,其实这么一个小模块涉及到的知识还是挺多的,但是不知道该如何下手整理,想看的就对付看下把,实在抱歉!

上一篇:《手把手教你》系列技巧篇(四十六)-java+ selenium自动化测试-web页面定位toast-下篇(详解教程)


下一篇:python实战项目 — selenium登陆豆瓣