python+selenium简易自动化框架,包含生成测试报告以及发送结果至Email
Selenium+python环境搭建见虫师的pdf文档,非常详尽
简易框架:
1.文件目录:
report目录中存放测试结果,如:
Test_case中存放所有用例case,以及public公共目录,和Data(测试数据)
当然测试数据如果不复杂,我们可以直接写在config中
2.testcase内容编写
在test_case下新增一个.py的文件
第一步:引用文件
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re,ConfigParser import sys sys.path.append('\public') from public import login
第二步:新建类
固定的那个方法 setUp,tearDown,包含了python中config的读取.,类里面的方法调用时前面加上self.
class Cyt(unittest.TestCase): def setUp(self): cf=ConfigParser.RawConfigParser() cf.read("config.conf") self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = cf.get("info","url") print self.base_url self.verificationErrors = [] self.accept_next_alert = True self.username=cf.get("info","username") self.pwd=cf.get("info","pwd") self.cytpwd=cf.get("info","cytpwd") def test_cyt01_index(self): u'''首页加载''' driver=self.driver driver.set_window_size(414,736) driver.get(self.base_url) driver.find_element_by_xpath('/html/body/div[1]/div[3]/div[2]/a').click() driver.set_page_load_timeout(30) time.sleep(2) title=driver.title catched=False try: self.assertEqual(u'XXXX',title) except AssertionError as e: catched=True self.verificationErrors.append(str(e)) if catched: print u'XX界面异常' else: print u'XX界面正常' driver.back() self.cyt02_investlist()
......中间若干方法或者若干testcase,结尾处加上tearDown,以及main。。
def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == '__main__': unittest.main()
登录模块写在public里,别的模块直接引入包 就可直接调用
#coding=utf-8 from selenium import webdriver from selenium.common.exceptions import NoSuchElementException import unittest, time #登陆模块(函数) def login(self): driver = self.driver driver.get(self.base_url + "/") print self.base_url account=driver.find_element_by_xpath("/html/body/div[2]/ul/li[4]/a").click() time.sleep(2) driver.find_element_by_name("username").clear() driver.find_element_by_name("username").send_keys(self.username) driver.find_element_by_name("password").clear() driver.find_element_by_name("password").send_keys(self.pwd) driver.find_element_by_xpath("/html/body/div/div/form[1]/div[4]/input").submit() time.sleep(5) title=driver.title error1=True try: self.assertEqual(u"账号登录", title) except AssertionError as e: error1=False if error1: driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys(self.cytpwd) driver.find_element_by_id("login_btn").submit() time.sleep(2)
第三步,生成测试结果,并发送测试结果至指定的邮箱
#coding=utf-8 import unittest import HTMLTestRunner import os ,time,datetime import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage import ConfigParser #=============定义发送邮件========== cf=ConfigParser.RawConfigParser() cf.read("config.conf") mdir= cf.get("info","dir") result_dir=mdir+"report" case_dir=mdir+"test_case" def sentmail(file_new): mail_from=cf.get("info","mail_from") mail_to=cf.get("info","mail_to") f = open(file_new, 'rb') mail_body = f.read() f.close() msg=MIMEText(mail_body,_subtype='html',_charset='utf-8') msg['From']=u'自动化测试' msg['Subject']=u"XX测试报告" msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z') str_smtp=cf.get("info","smtp") smtp=smtplib.SMTP_SSL(str_smtp,465) email_pwd=cf.get("info","email_pwd") smtp.login(mail_from,email_pwd) smtp.sendmail(mail_from,mail_to,msg.as_string()) smtp.quit() print 'email has send out !' def sendreport(): lists=os.listdir(result_dir) lists.sort(key=lambda fn: os.path.getmtime(result_dir+"\\"+fn) if not os.path.isdir(result_dir+"\\"+fn) else 0) print (u'最新测试生成的报告: '+lists[-1]) file_new = os.path.join(result_dir,lists[-1]) print file_new sentmail(file_new) listaa=mdir+"test_case" def creatsuit(): testunit=unittest.TestSuite() discover=unittest.defaultTestLoader.discover(listaa, pattern ='*.py',top_level_dir=None) for test_suite in discover: for test_case in test_suite: testunit.addTests(test_case) print testunit return testunit if __name__ == "__main__": now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time())) filename = result_dir+'\\'+now+'result.html' fp = file(filename, 'wb') runner =HTMLTestRunner.HTMLTestRunner( stream=fp, title=u'XX测试报告', description=u'用例执行情况:') runner.run(creatsuit()) fp.close() sendreport()
测试报告: