本文為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 import By from time import sleep from objpage.base import Page class login(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') def login_username(self,username): self.find_element(*self.username_loc).clear() self.find_element(*self.username_loc).send_keys(username) def login_password(self,password): self.find_element(*self.password_loc).clear() self.find_element(*self.password_loc).send_keys(password) def login_button(self): self.find_element(*self.login_button_loc).click() #統一登錄入口 def user_login(self,username,password): self.open() self.login_username(username) self.login_password(password) self.login_button() sleep(2) #登錄提示信息 def login_error_text(self): return self.find_element(*self.login_error_loc).text
parker.py中放置公共元素操作代碼(parker是我隨便命名的,不糾結)
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.select import Select class Parker(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=driver except Exception: 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') return element def 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() def click_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) return el.get_attribute(attribute) def get_text(self,key):#獲取text el=self.to_element(key) return el.text def get_title(self):#獲取title return self.driver.title def get_url(self):#獲取url return self.driver.current_url def 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放置郵件發送代碼
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import configparser import os def sendEmail(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 in range(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文件放置的就是運行代碼(執行這個文件進行測試就可以)
import HTMLTestRunner import unittest from test_case.login import loginTest from public.send_email import sendEmail if __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)
今天就先到這里,一個入門級的自動化測試框架,由於是非專業開發自學,拿出來給大家分享,編程代碼可能有點不規范,命名也很隨意。大家先將就着看吧!回頭慢慢完善。
還要多向大佬們學習。
備注:有想一起自學的朋友可以看配置文件代碼,一起交流。三人行必有我師焉
