1.测试用例在不同的py文件下,首先看一下我的项目结构,case里放着测试用例,report是存放测试报告,run_main文件为执行用例。用到HTMLTestRunner
2.case里面,如图,t_single是driver,使用的是单例模式
import threading
from selenium import webdriver
class Sin(object):
_instance_lock=threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Sin,'_instance'):
with Sin._instance_lock:
if not hasattr(Sin, '_instance'):
Sin._instance=object.__new__(cls)
opt=webdriver.ChromeOptions()
opt.add_argument('headless') #无头模式,可以使用
opt.add_argument('disable-infobars')
#chrome_options.add_argument('--disable-gpu')
cls.driver=webdriver.Chrome() #chrome_options=opt
cls.driver.get('https://www.baidu.com')
return Sin._instance
3.测试用例
1).test_baidu
from t_single import Sin
import unittest
from selenium import webdriver
from time import sleep
class Ceshi(unittest.TestCase):
def test_home(self):
Sin().driver.get('https://www.baidu.com')
title=Sin().driver.title
print(title)
sleep(2)
self.assertEqual(u'百度一下,你就知道',title)
def test_search(self):
sleep(2)
Sin().driver.get('https://www.baidu.com')
Sin().driver.find_element_by_id('kw').send_keys('python')
Sin().driver.find_element_by_id('su').click()
sleep(2)
title1=Sin().driver.title
sleep(2)
self.assertEqual(u'python_百度搜索',title1)
2).test_bokeyuan
from selenium import webdriver
from t_single import Sin
import unittest
class Bo(unittest.TestCase):
def setUp(self):
print('bokeyuan start...')
def test_shouye(self):
Sin().driver.get('https://www.cnblogs.com/')
title2=Sin().driver.title
self.assertIn(u'博客园',title2)
def tearDown(self):
print('bokeyuan end...')
4.run_main()
#coding: utf - 8
from case.t_single import Sin
from case.test_baidu import Ceshi
from case.test_bokeyuan import Bo
from unittest import TestSuite,TestLoader
import unittest,time,os
import HTMLTestRunner
import smtplib#发送邮件模块
from email.mime.text import MIMEText#定义邮件neir
from email.header import Header#定义邮件标题
def run_main():
suit = unittest.TestSuite() #添加测试套件
suit.addTest(Bo('test_shouye'))
suit.addTest(Ceshi('test_search')) #将测试用例添加到测试套件里
suit.addTest(Ceshi('test_home'))
file=r'report/report.html' #测试报告
fb=open(file,'wb')
runner = HTMLTestRunner.HTMLTestRunner(stream=fb,title='test_report',description='detail')
runner.run(suit)
fb.close()
if __name__ == '__main__':
run_main()
4.查看生成的测试报告