python+selenium+unittest 实现自动化测试

时间:2023-12-11 16:33:32

示例代码:

baidu.py

import csv #导入csv模块
from itertools import islice #从itertools导入islice,后边让其默认跳过第一行使用
from time import sleep
from selenium import webdriver
from module import baidumodule
driver = webdriver.Chrome()
search = baidumodule(driver) #将driver传给aidumodule这个类
with open("file.csv","r") as name:
lines = name.readlines()#以行读取整个文件
for i in islice(lines,1,None): #每次从第二行读取:
search.login(i) #调用aidumodule下的login函数
sleep(2) start.login_out()

module.py

class baidumodule():
def __init__(self,driver,):
self.dr = driver #不能在类中再次导入webdriver 两边的driver等于两个窗口,直接让调用方传入driver即可
def login(self,values):
login_dr = self.dr
login_dr.get("https://www.baidu.com/")
login_dr.find_element_by_xpath("//*[@id='kw']").send_keys(values)
login_dr.find_element_by_xpath("//*[@id='su']").click() def login_out(self):
self.dr.quit()

file.csv

selenium
selenium2
selenium3
webdriver

可以看到我们上面写的代码,虽然是自动帮我们搜索多个值,但并不能算测试用例,顶多算线性测试,既然是测试那我们就需要加入用例计算及结果断言,我们这里介绍使用unittest框架进行自动化测试组建。

unittest简单介绍:

import unittest #导入unittest
class baidu(unittest.TestCase):#TestCase测试用例集 def setUp(self):#setUp在unittest固定写法setUp首先执行
pass
def tearDown(self):#tearDown在unittest固定写法setUp会最后执行
pass
def test_baidu(self):#测试用例1,可定义多个必须以test开头
pass

注:用例名称不是以test开头不会被执行,多条用例名称一致只会执行一条

开始改写我们上面的baidu.py内容:

# _*_ coding:utf-8 _*_
import csv,unittest #导入unittest 模块
from time import sleep
from selenium import webdriver
from module import baidumodule
class baidu(unittest.TestCase):#创建测试用例集
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()#最大化窗口
self.driver.implicitly_wait(10)#隐式等待
self.search = baidumodule(self.driver) #将driver传给aidumodule这个类
with open("file.csv","r") as name:
self.lines = name.readlines()#以行读取整个文件
def tearDown(self):
self.search.login_out()#调用登出函数 def test_search(self):#测试用例一
search = self.search
lines = self.lines
driver = self.driver
search.login(lines[0])
sleep(1)
title = driver.title
self.assertEqual(title,'selenium_百度搜索')#判断当前title是否等于selenium_百度搜索
sleep(2)
def test_search1(self):#测试用例二
search = self.search
lines = self.lines
driver = self.driver
search.login(lines[1])
sleep(1)
title = driver.title
self.assertEqual(title,'selenium2_百度搜索')
sleep(2)
def test_search2(self):#测试用例三
search = self.search
lines = self.lines
driver = self.driver
search.login(lines[2])
sleep(1)
title = driver.title
self.assertEqual(title,'selenium3_百度搜索')
sleep(2)
def test_search3(self):#测试用例四
search = self.search
lines = self.lines
driver = self.driver
search.login(lines[3])
sleep(1)
title = driver.title
self.assertEqual(title,'webdriver_百度搜索')
sleep(2) if __name__ == "__main__":
unittest.main()

执行结果:

....
----------------------------------------------------------------------
Ran 4 tests in 51.427s OK

可以看到执行结果中成功返回我们的测试用例数,并成功执行退出(项目中善用sleep,这里只是做演示,sleep太多执行时间太长)

如果执行失败

self.assertEqual(title,'selenium_百度搜索2')
AssertionError: 'selenium_百度搜索' != 'selenium_百度搜索2'
Ran 4 tests in 23.518s FAILED (failures=1)