自动化测试python selenium案例_Python selenium自动化测试框架入门实战--登录测试案例...

本文为Python自动化测试框架基础入门篇,主要帮助会写基本selenium测试代码又没有规划的同仁。

本文应用到POM模型、selenium、unittest框架、configparser配置文件、smtplib邮件发送、HTMLTestRunner测试报告模块结合登录案例实现简单自动化测试框架

项目主要包括以下几个部分

conif.ini 放置配置文件

例如:

myunit.py文件放置的浏览器操作代码

import unittest

from selenium import webdriver

class MyTest(unittest.TestCase):

def setUp(self):

self.driver = webdriver.Chrome()

self.driver.implicitly_wait(10)

self.driver.maximize_window()

def tearDown(self):

self.driver.quit()

if __name__=='__main__':

unittest.main()

base.py中放置浏览器对象操作代码

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.support.wait import WebDriverWait

import os,configparser

class Page(object):

path = os.path.dirname(os.path.abspath("."))

cfpath = os.path.join(path, 'autoparker\config\conf.ini')

conf = configparser.ConfigParser()

conf.read(cfpath)

url=conf.get('base','url')

def __init__(self,driver,url=url):

self.driver=driver

self.url=url

def open(self):

self.driver.get(self.url)

def find_element(self,*loc):#传入参数为元组需要加*,本身就是元组的不需要*

#print(*loc)

try:

WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc))

return self.driver.find_element(*loc)

except:

print('页面中未找到 %s 元素'%(self,loc))

def find_elements(self,*loc):

return self.driver.find_elements(*loc)

def send_keys(self,loc,value):

self.find_element(*loc).send_keys(value)

def click(self,loc):

self.find_element(*loc).click()

def clear(self,loc):

self.find_element(*loc).clear()

loginpage.py中放置通用登录模块代码(尽量避免重复代码)

from selenium.webdriver.common.by importByfrom time importsleepfrom objpage.base importPageclasslogin(Page):

username_loc=(By.NAME,'accounts')

password_loc=(By.NAME,'pwd')

login_button_loc=(By.XPATH,'/html/body/div[5]/div/form/fieldset/p/button')

login_error_loc=(By.XPATH,'//*[@id="common-prompt"]/p')deflogin_username(self,username):

self.find_element(*self.username_loc).clear()

self.find_element(*self.username_loc).send_keys(username)deflogin_password(self,password):

self.find_element(*self.password_loc).clear()

self.find_element(*self.password_loc).send_keys(password)deflogin_button(self):

self.find_element(*self.login_button_loc).click()#统一登录入口

defuser_login(self,username,password):

self.open()

self.login_username(username)

self.login_password(password)

self.login_button()

sleep(2)#登录提示信息

deflogin_error_text(self):return self.find_element(*self.login_error_loc).text

parker.py中放置公共元素操作代码(parker是我随便命名的,不纠结)

from selenium importwebdriverfrom selenium.webdriver.common.action_chains importActionChainsfrom selenium.webdriver.support.select importSelectclassParker(object):def __init__(self,browser='chrome'):if browser=='ie' or browser=='internet explorer':

driver=webdriver.Ie()elif browser=='firefox' or browser=='ff':

driver=webdriver.Firefox()elif browser=='chrome':

driver=webdriver.Chrome()try:

self.driver=driverexceptException:raise NameError('没有找到浏览器,请输入"ie","chrome","ff"')def wait(self,secs=5): #隐式等待

self.driver.implicitly_wait(secs)def to_element(self,key):#元素定位

if '->' not in key: #如果key里面不包含=就执行下列语句

raise NameError('参数类型输入错误')

by=key.split('->')[0] #通过分隔获取[0]对应的值

val=key.split('->')[1]#通过分隔获取[1]对应的值

if by=='id':

element=self.driver.find_element_by_id(val)elif by=='name':

element=self.driver.find_element_by_name(val)elif by=='class':

element=self.driver.find_element_by_class_name(val)elif by=='link_text':

element=self.driver.find_element_by_link_text(val)elif by=='xpath':

element=self.driver.find_element_by_xpath(val)elif by=='css':

element=self.driver.find_element_by_css_selector(val)else:raise NameError('请输入正确的定位方式:id,name,class,link_text,xpath,css')returnelementdef open(self,url):#打开一个URL

self.driver.get(url)def max_window(self):#最大化窗口(浏览器)

self.driver.maximize_window()def set_windows(self,wide,high):#设置窗口大小

self.driver.set_window_size(wide,high)def input(self,key,text):#对文本框进行输入

el=self.to_element(key)

el.send_keys(text)def click(self,key):#点击

el=self.to_element(key)

el.click()def clear(self,key):#清除文本框内容

el=self.to_element(key)

el.clear()def right_click(self,key):#右键操作

el=self.to_element(key)

ActionChains(self.driver).context_click(el).perform()def move_to_element(self,key):#鼠标悬停

el=self.to_element(key)

ActionChains(self.driver).move_to_element(el).perform()def drag_and_drop(self,el_key,ta_key):#拖拽 从一个元素拖到另外一个元素

el=self.to_element(el_key)

target=self.to_element(ta_key)

ActionChains(self.driver).drag_and_drop(el,target).perform()defclick_text(self,text):

self.driver.find_element_by_partial_link_text(text).click()def close(self):#关闭当前浏览器窗口

self.driver.close()def quit(self):#退出浏览器

self.driver.quit()def submit(self,key):#提交事件

el=self.to_element(key)

el.submit()def F5(self):#刷新

self.driver.refresh()def js(self,script):#执行js

self.driver.execute_script(script)def get_attribute(self,key,attribute):#获取元素属性

el=self.to_element(key)returnel.get_attribute(attribute)def get_text(self,key):#获取text

el=self.to_element(key)returnel.textdef get_title(self):#获取title

returnself.driver.titledef get_url(self):#获取url

returnself.driver.current_urldef to_frame(self,key):#窗口切换

el=self.to_element(key)

self.driver.switch_to.frame(el)def alert_accept(self):#对话框确认操作

self.driver.switch_to.alert.accept()def alert_dismiss(self):#对话框取消操作

self.driver.switch_to.alert.dismiss()def img(self,fp):#截图

self.driver.get_screenshot_as_file(fp)def select_by_value(self,key,value):#下拉框操作

el=self.to_element(key)

Select(el).select_by_value(value)

send_email.py放置邮件发送代码

importsmtplibfrom email.mime.text importMIMETextfrom email.mime.multipart importMIMEMultipartimportconfigparserimportosdefsendEmail(file_path):

path=os.path.dirname(os.path.abspath("."))

cfpath=os.path.join(path,'autoparker\config\conf.ini')

conf=configparser.ConfigParser()

conf.read(cfpath)

smtpserver= conf.get('emailqq','smtpserver')

sender= conf.get('emailqq','sender')

pwd= conf.get('emailqq','pwd')

receiver=[]

email_to=conf.get('emailqq','receiver')

email_array=email_to.split(';')for i inrange(len(email_array)):

receiver.append(email_array[i])print(receiver)

with open(file_path,'rb') as fp:

mail_boby=fp.read()

msg=MIMEMultipart()

msg['From']=sender

msg['To']=",".join(receiver)

msg['Subject']='我曾把完整的镜子打碎'body=MIMEText(mail_boby,'html','utf-8')

msg.attach(body)

att=MIMEText(mail_boby,'html','utf-8')

att['Content-Type']='application/octet-stream'att['Content-Disposition']='attachment;filename="test_reuslt.html"'msg.attach(att)try:

smtp=smtplib.SMTP()

smtp.connect(smtpserver)

smtp.login(sender,pwd)except:

smtp=smtplib.SMTP_SSL(smtpserver,465)

smtp.login(sender,pwd)

smtp.sendmail(sender,receiver,msg.as_string())

smtp.quit()

sendEmail('D:\\report.html')

最后main.py文件放置的就是运行代码(执行这个文件进行测试就可以)

importHTMLTestRunnerimportunittestfrom test_case.login importloginTestfrom public.send_email importsendEmailif __name__=='__main__':

testunit=unittest.TestLoader().loadTestsFromTestCase(loginTest)

suite=unittest.TestSuite(testunit)

file_path="D:\\html_report.html"fp=open(file_path,'wb')

runner=HTMLTestRunner.HTMLTestRunner(stream=fp,title='登录测试',description='测试执行结果')

runner.run(suite)

fp.close()

sendEmail(file_path)

今天就先到这里,一个入门级的自动化测试框架,由于是非专业开发自学,拿出来给大家分享,编程代码可能有点不规范,命名也很随意。大家先将就着看吧!回头慢慢完善。

还要多向大佬们学习。

备注:有想一起自学的朋友可以看配置文件代码,一起交流。三人行必有我师焉

你可能感兴趣的:(自动化测试python,selenium案例)