UI自动化测试

selenium4

selenium2.0=seleium1.0+webdriver

selenium4.0

基于WEBUI的自动化测试框架 支持主流的编程语言(Python,java,c#,php,js),支持针对主流的浏览器进行UI的自动化测试(EDGE,Chrome,Firefox)。

 

selenium环境搭建:

1、下载chrome的浏览器

2pip install selenium

3、下载与浏览器版本匹配的驱动文件

      A、查看chrome浏览器的版本(例如:105.0.5195.102

      Bhttp://chromedriver.storage.googleapis.com/index.html

4、管理员的身份启动driver的程序

5、把它配置到path的环境变量

 

找到元素的属性,然后才能够定位到它,下来针对它来进行各种UI交互的操作。

 

8种常用的元素属性:

IDname,class_name,tag_name,css,xpath,超链接

ID = "id"

XPATH = "xpath"

LINK_TEXT = "link text"

PARTIAL_LINK_TEXT = "partial link text"

NAME = "name"

TAG_NAME = "tag name"

CLASS_NAME = "class name"

CSS_SELECTOR = "css selector"

我们针对这8种元素属性操作方式,都是有不同的方法来进行操作的

 

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# id:每个元素属性的ID都是唯一的
#针对webdriver进行实例化,同时指定Chrome的浏览器,浏览器首字母大写driver=webdriver.Chrome()
#打开被测试的网站
driver.get('http://www.baidu.com')
time.sleep(1)

#定位到搜索框,ID
driver.find_element(By.ID,'kw').send_keys('')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)

#name
driver.find_element(By.NAME,'wd').send_keys('pig')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)

#class_name
driver.find_element(By.CLASS_NAME,'s_ipt').send_keys('pig')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)
'''
xpath:使用路径
当使用xpath的时候,ID是动态的,那么使用fullpath(被定位元素属性的完整路径)
'''
driver.find_element(By.XPATH,'//*[@id="kw"]').send_keys('pig')
time.sleep(3)
driver.find_element(By.ID,'su').click()
time.sleep(3)

# css:基于样式
driver.find_element(By.CSS_SELECTOR,'#kw').send_keys('pig')
time.sleep(3)
driver.find_element(By.CSS_SELECTOR,'#su').click()
time.sleep(3)

# 2种类超链接的查询LINK_TEXTPARTIAL_LINK_TEXT
# 精确超链接匹配
driver.find_element(By.LINK_TEXT,'新闻').click()
time.sleep(3)
#模糊匹配
driver.find_element(By.PARTIAL_LINK_TEXT,'').click()
time.sleep(3)

#关闭浏览器
driver.close()

#tagname,单个元素定位、多个元素索引定位
driver=webdriver.Chrome()
driver.get('file:///C:/Users/Administrator/Desktop/tagTest.html')
time.sleep(3)
driver.find_element(By.TAG_NAME,'input').send_keys('admin')
time.sleep(3)
driver.close()


'''
元素定位的分类:
1、单个元素定位:find_element()
2、多个元素定位:find_elements()

有单个为什么还有多个?
这是因为,当开发写的IDname,class_name一模一样的时候,这个时候无法区分,
那么只能使用多个元素定位的方式。

多个元素定位方式使用?
它获取的对象是一个列表,我们可以被定位的元素属性在列表中是第几位,根据它的
索引信息来定位它。
'''
driver=webdriver.Chrome()
driver.get('https://baidu.com/')
time.sleep(2)
tags=driver.find_elements(By.TAG_NAME,'input')
print(type(tags))
for item in tags:
    print(item)
tags[7].send_keys('pug')
time.sleep(2)
driver.close()

 

 


driver=webdriver.Chrome()
driver.get('file:///C:/Users/Administrator/Desktop/tagTest(1).html')
time.sleep(2)
ids=driver.find_elements(By.ID,'asd')
ids[0].send_keys('username')
ids[1].send_keys('passward')
time.sleep(2)
driver.close()

 

打开网页,点击检查,点击左上角的箭头,将鼠标放入搜索框和百度一下内即可得到元素属性对应的信息

 

中间有空格的都是错的,所以使用ID

 

 

 

xpath的获取方法

 

full xpath

 

css的获取方法

 

 

 

 

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
'''
先获取当前窗口句柄
然后点击链接,打开一个新的窗口句柄
然后获取到所有的窗口句柄
循环所有的窗口句柄,判断如果不是当前窗口句柄,那么就切换到新的窗口句柄(如果当前的,就只能是新的窗口了)
切换到新的窗口后,进行操作完成后,然后关闭新的窗口,再切换到当前窗口句柄
'''

driver=webdriver.Chrome()
#窗口最大化
driver.maximize_window()
driver.get('https://www.baidu.com/')

time.sleep(1)
#获取当前测试的地址
print(driver.current_url)
#获取当前页面的源码
# print(driver.page_source)
#获取title
print(driver.title)
time.sleep(1)

driver.get('http://news.baidu.com/')
time.sleep(1)

#回退
driver.back()
print(driver.current_url)
time.sleep(1)
#前进
driver.forward()
print(driver.current_url)
time.sleep(1)

driver.close()

driver=webdriver.Chrome()
#窗口最大化
driver.maximize_window()
driver.get('https://www.baidu.com/')
time.sleep(1)
# #获取当前的窗口
nowHandler=driver.current_window_handle
driver.find_element(By.LINK_TEXT,'新闻').click()
time.sleep(2)
#获取所有的窗口
allHandlers=driver.window_handles
#对所有的窗口进行循环
for hander in allHandlers:
    if hander!=nowHandler:
        #切换到新的窗口
        driver.switch_to.window(hander)
        time.sleep(2)
        driver.find_element(By.ID,'ww').send_keys('百度新闻')
        time.sleep(1)
        driver.close()
#切换到当前窗口
driver.switch_to.window(nowHandler)
time.sleep(2)
driver.find_element(By.ID,'kw').send_keys('ok')
time.sleep(2)

so=driver.find_element(By.ID,'kw')
so.send_keys('why')
time.sleep(1)
#清理搜索框
so.clear()
#获取属性值
print(so.get_attribute('value'))
print(so.get_attribute('maxlength'))

#是否可见
obj=driver.find_element(By.LINK_TEXT,'关于百度')
print(obj.is_displayed())
#是否可编辑
obj=driver.find_element(By.ID,'kw')
print(obj.is_enabled())
driver.close()

#新浪登录页面自动登录勾选
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('https://mail.sina.com.cn/')
time.sleep(1)
obj=driver.find_element(By.ID,'store1')
print(obj.is_selected())
time.sleep(2)
obj.click()
time.sleep(1)
print(obj.is_selected())
time.sleep(2)
driver.close()

 

readonly只读不写

 

 

 

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time

'''
下拉框选项:
1、首先对Select进行实例化,这样可以调用里面的方法
2、三种方式:
   文本
   索引
   value值
'''

driver=webdriver.Chrome()
driver.maximize_window()
driver.get('file:///C:/Users/Administrator/Desktop/select(1).html')
time.sleep(1)
sel=driver.find_element(By.ID,'nr')
obj=Select(sel)
time.sleep(1)
#文本模式
# obj.select_by_visible_text('Go语言')
#索引模式
obj.select_by_index(2)
#value值模式
# obj.select_by_value('Go')
time.sleep(2)
driver.close()

#拉勾网的下拉框
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.lagou.com/')
time.sleep(3)
#输入搜索关键字
driver.find_element(By.ID,'search_input').send_keys('测试开发工程师')
time.sleep(1)
driver.find_element(By.ID,'search_button').click()
time.sleep(1)
#点击学历要求
driver.find_element(By.XPATH,'//*[@id="jobsContainer"]/div[2]/div[1]/div[1]/div[2]/div/ul/li[2]/div/span').click()
time.sleep(1)
#选择大专
driver.find_element(By.XPATH,'//*[@id="jobsContainer"]/div[2]/div[1]/div[1]/div[2]/div/ul/li[2]/div/div/ul[2]/li[1]/span').click()
time.sleep(2)
driver.close()

 

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
import time

'''
text:获取弹出框的文本信息
accept是接受Confirm弹出框
dismiss是拒绝接受Confirm弹出框
send_keys是在Prompt消息对话框里面输入想要输入的内容
'''

driver=webdriver.Chrome()
driver.maximize_window()
#警告框
driver.get('file:///C:/Users/Administrator/Desktop/%E8%AD%A6%E5%91%8A%E6%A1%86(2).html')
#获取警告框里面的文本信息
print(driver.switch_to.alert.text)
#点击确定按钮
driver.switch_to.alert.accept()
time.sleep(1)


# 确认消息
driver.get('file:///C:/Users/Administrator/Desktop/%E7%A1%AE%E5%AE%9A%E6%B6%88%E6%81%AF(2).html')
time.sleep(1)
driver.find_element(By.XPATH,'/html/body/center/input').click()
time.sleep(1)
driver.switch_to.alert.accept()
time.sleep(1)
# 刷新
driver.refresh()
driver.find_element(By.XPATH,'/html/body/center/input').click()
time.sleep(1)
# 点击取消
driver.switch_to.alert.dismiss()
time.sleep(1)

#消息对话框
driver.get('file:///C:/Users/Administrator/Desktop/%E6%B6%88%E6%81%AF%E5%AF%B9%E8%AF%9D%E6%A1%86(2).html')
time.sleep(1)
driver.find_element(By.XPATH,'/html/body/center/input').click()
time.sleep(1)
#输入内容
driver.switch_to.alert.send_keys('xc')
time.sleep(1)
driver.switch_to.alert.accept()
time.sleep(2)

driver.close()

'''
ActionChains:主要是针对鼠标事件的处理,在鼠标事件中常用的交互为悬浮,双击,以及右键等操作
如果想使用ActionChains的类,首先需要导入它,导入的命令为:
from selenium.webdriver.common.action_chains import ActionChains
'''
#右键搜索框
driver.get('http://www.baidu.com/')
# 针对ActionChains类进行实例化操作
obj=ActionChains(driver=driver)
time.sleep(2)
so=driver.find_element(By.ID,'kw')
#右键点击搜索框(perform()也是点击的意思,与click()不同)
obj.context_click(so).perform()
time.sleep(1)
driver.close()

# 双击
driver.get('http://www.baidu.com/')
obj=ActionChains(driver=driver)
time.sleep(1)
driver.find_element(By.ID,'kw').send_keys('pug')
button=driver.find_element(By.ID,'su')
#double_click()点击两次百度搜索按钮
obj.double_click(button).perform()
time.sleep(2)
driver.close()


#百度设置
driver.get('http://www.baidu.com/')
obj=ActionChains(driver=driver)
time.sleep(1)
#获取到百度设置的元素属性
settings=driver.find_element(By.XPATH,'//*[@id="s-usersetting-top"]')
#鼠标悬浮到设置按钮
obj.move_to_element(settings).perform()
time.sleep(1)
#点击搜索设置
driver.find_element(By.XPATH,'//*[@id="s-user-setting-menu"]/div/a[1]/span').click()
time.sleep(2)
#点击保存设置
driver.find_element(By.XPATH,'//*[@id="se-setting-7"]/a[2]').click()
time.sleep(2)
print(driver.switch_to.alert.text)
driver.switch_to.alert.accept()
driver.close()

 

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time

#键盘事件
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.baidu.com/')
time.sleep(1)
so=driver.find_element(By.ID,'kw')
so.send_keys('娃哈哈')
time.sleep(1)
so.send_keys(Keys.CONTROL,'a')
time.sleep(1)
so.send_keys(Keys.CONTROL,'c')
time.sleep(1)
so.send_keys(Keys.BACKSPACE)
time.sleep(1)
so.send_keys(Keys.CONTROL,'v')
so.send_keys(1)
driver.close()

 

 

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as es
from selenium.webdriver.support.ui import WebDriverWait
import time

'''
1、固定等待,也就是使用sleep()方法

2、隐式等待,使用到的方法是implicitly_wait的方法,可以把它理解为设置最长等待时间

3、显式等待,主要指的是程序每隔一段时间执行自定义的程序判断条件,如果判断成立,程序就会继

续执行,那么如果判断失败,就会报TimeOutException的异常信息。

'''

driver=webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.baidu.com/')
driver.implicitly_wait(20)
obj=WebDriverWait(
    driver=driver,
    timeout=10).until(
    method=es.element_to_be_clickable((By.ID,'kw')))
obj.send_keys('cs')
time.sleep(1)
driver.close()

driver.get('https://mail.sina.com.cn/')
driver.implicitly_wait(20)
time.sleep(1)
driver.find_element(By.CLASS_NAME,'loginBtn').click()
obj=WebDriverWait(
    driver=driver,
    timeout=10).until(
    method=es.text_to_be_present_in_element((By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]'),'请输入邮箱名'))
time.sleep(1)
driver.close()

driver.get('http://www.baidu.com/')
driver.implicitly_wait(20)
time.sleep(1)
obj=WebDriverWait(
    driver=driver,
    timeout=10).until(
    method=es.visibility_of_element_located((By.LINK_TEXT,'关于百度')))
print(obj.is_displayed())
obj.click()
time.sleep(1)
driver.close()

'''
iframe的框架,哪些通过方式:
ID
name
索引
当我们使用八种常用元素的方法无法寻找到目标时可能会出现iframe的框架
'''

driver.get('https://file.qq.com/')
driver.implicitly_wait(20)
#进入第一层
# driver.switch_to.frame(0)
driver.switch_to.frame("login_frame1")
time.sleep(1)
#进入到第二层
# driver.switch_to.frame(0)
driver.switch_to.frame('ptlogin_iframe')
time.sleep(1)
driver.find_element(By.XPATH,'//*[@id="switcher_plogin"]').click()
time.sleep(1)
driver.close()

 

 

import yaml
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as es
from selenium.webdriver.support.ui import WebDriverWait
import time
import json

# 浏览器的滑动
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('http://www.baidu.com/')
driver.implicitly_wait(20)
driver.find_element(By.ID,'kw').send_keys('测试')
driver.find_element(By.ID,'su').click()
time.sleep(1)
#滑动到浏览器底部
js='var q=document.documentElement.scrollTop=10000'
#调用js语言
driver.execute_script(js)
time.sleep(2)
#滑动到浏览器顶部
js1='var q=document.documentElement.scrollTop=0'
driver.execute_script(js1)
time.sleep(1)
driver.close()

#富文本
def richText(driver,content):
'''
实现在富文本里面输入内容
:param driver: webdriver实例化后的对象信息
:param content: 富文本里面需要输入的文字内容
:return:
'''
js="document.getElementById('ueditor_0').contentWindow.document.body.innerHTML='{0}'".format(content)
driver.execute_script(js)

driver=webdriver.Chrome()
driver.maximize_window()
driver.get('https://uutool.cn/ueditor/')
driver.implicitly_wait(20)
time.sleep(2)
richText(driver=driver,content='自动化测试')
time.sleep(3)
driver.close()

#时间控件
def startTime(driver,content):
'''开始时间控件'''
js="$(\"input[placeholder='开始时间≥当前时间']\").removeAttr('readonly');" \
"$(\"input[placeholder='开始时间≥当前时间']\").attr('value','{0}')".format(content)
driver.execute_script(js)

def endTime(driver,content):
'''结束时间控件'''
js="$(\"input[placeholder='结束时间>开始时间']\").removeAttr('readonly');" \
"$(\"input[placeholder='结束时间>开始时间']\").attr('value','{0}')".format(content)
driver.execute_script(js)


driver = webdriver.Chrome()
driver.maximize_window()
driver.get('C:/Users/Administrator/Desktop/Time/index.html')
time.sleep(2)
startTime(driver=driver,content='2022-12-12 00:00:20')
time.sleep(2)
endTime(driver=driver,content='2022-12-21 00:11:11')
time.sleep(2)
driver.close()

'''
UI自动化测试主要测试什么?
1、页面交互
2、表单错误提示信息的验证
3、业务场景

数据驱动:在自动化测试中,把测试中的数据分离到文件中,
这样的一个过程叫数据驱动。
JSON:json
CSV:csv
EXCEL:xlrd pip install xlrd
YAML:pyyaml pip install pyyaml
mysql:pymysql pip install pymysql
json的内容必须要双引号
yaml的文件冒号后必须空格
'''
创建sina.yaml文件

 

 创建sina.txt文件

 

 

def readJson():
return json.load(open('sina.txt', 'r',encoding='utf-8'))
print(readJson())
def readYaml():
with open('sina.yaml','r',encoding='utf-8') as f:
return yaml.safe_load(f)
print(readYaml())

driever=webdriver.Chrome()
driever.get('https://mail.sina.com.cn/')
driever.implicitly_wait(20)
driever.find_element(By.CLASS_NAME,'loginBtn').click()
time.sleep(1)
jtext=driever.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]')
#python原生断言assert
assert jtext.text==readJson()['emailFormat']
assert jtext.text==readYaml()['sina']['emailNull']
time.sleep(2)
driever.refresh()
driever.find_element(By.CLASS_NAME,'username').send_keys('asdasd')
driever.find_element(By.CLASS_NAME,'loginBtn').click()
time.sleep(1)
jtext=driever.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]')
# assert jtext.text==readJson()['emailFormat']
assert jtext.text==readYaml()['sina']['emailFormat']
time.sleep(1)
driever.close()

 

#腾讯文件练习

创建tx.json文件

 

创建tx.yaml文件

 

 

 

 

#腾讯文件练习
# def TX1():
# return json.load(open('tx.json', 'r', encoding='utf-8'))
# print(TX1())
def TX1():
with open('tx.yaml','r',encoding='utf-8') as f:
return yaml.safe_load(f)
def readYaml():
with open('qq.yaml','r',encoding='utf-8') as z:
return yaml.safe_load(z)
driver=webdriver.Chrome()
driver.maximize_window()
driver.get('https://file.qq.com/')
driver.implicitly_wait(20)
driver.switch_to.frame(0)
driver.switch_to.frame(0)
driver.find_element(By.ID,'switcher_plogin').click()
time.sleep(1)
driver.find_element(By.CLASS_NAME,'btn').click()
f1=driver.find_element(By.XPATH,'//*[@id="err_m"]')
# print(f1.text)
# print(TX1()["qqNull"])
assert f1.text==TX1()['tx']['qqNull']
# assert f1.text==TX1()["qqNull"]
time.sleep(1)
driver.find_element(By.CLASS_NAME,'inputstyle').send_keys('123')
driver.find_element(By.ID,'login_button').click()
f1=driver.find_element(By.XPATH,'//*[@id="err_m"]')
# print(f1.text)
# print(TX1()["qqZH"])
assert f1.text==TX1()['tx']["qqZH"]
# assert f1.text==TX1()["qqZH"]
time.sleep(1)

nowHandler=driver.current_window_handle
driver.find_element(By.LINK_TEXT,'注册帐号').click()
time.sleep(2)
#获取所有的窗口
allHandlers=driver.window_handles
#对所有的窗口进行循环
for hander in allHandlers:
if hander!=nowHandler:
#切换到新的窗口
driver.switch_to.window(hander)
time.sleep(1)
driver.find_element(By.XPATH, '//*[@id="password"]').send_keys('124567890000000')
time.sleep(1)
driver.find_element(By.ID, 'phone').send_keys('bn')
time.sleep(1)
driver.find_element(By.ID, 'get_acc').click()
time.sleep(1)
devTest1 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[1]/div[3]/div')
devTest2 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[2]/div[4]/div')
devTest3 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[3]/div[2]/div')
devTest4 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[4]/div[2]/div')
devTest5 = driver.find_element(By.XPATH, '/html/body/div[3]/div[2]/div[1]/form/div[6]/div/div')
time.sleep(2)
assert devTest1.text == readYaml()["qq"]["qqname"]
assert devTest2.text == readYaml()["qq"]["password"]
assert devTest3.text == readYaml()["qq"]["phone"]
assert devTest4.text == readYaml()["qq"]["yanzheng"]
assert devTest5.text == readYaml()["qq"]["privace"]
time.sleep(3)
driver.close()
driver.switch_to.window(nowHandler)
driver.close()

初始化    打开浏览器

测试步骤  百度搜索

测试断言  验证搜索结果

测试清理  关闭浏览器

 

 

 

 

 

 

 

 

 

 

测试固件:初始化和清理,使用到的方法分别是setUp()tearDown()

测试用例:TestCase就是测试类里面编写的测试方法

测试套件:TestSuite就是测试用例的集合,在一个测试套件可以有很多的测试用例

测试执行:TestRunner执行测试套件或者测试用例

测试报告:TestReport就是执行所有测试用例后的结果信息

 

 

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

'''
    测试用例注意事项
    1、所有测试方法必须是以test开头的
    2、每个测试点都必须有标题
    3、每个测试用例都必须得有断言
    4、测试点的名称不能一致
    5、执行顺序:
        ①先执行setUp()
        ②执行测试点的代码
        
    '''
class TestSina(unittest.TestCase):
    #初始化(大开要测试的浏览器)
    def setUp(self) -> None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://mail.sina.com.cn/')
        self.driver.implicitly_wait(20)



    def test_sina_username(self):
        '''验证用户名为空的错误提示信息'''
        self.driver.find_element(By.CLASS_NAME,'loginBtn').click()
        time.sleep(1)
        divTest=self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]').text
        # assertEqual ---> ==:比较两个对象的值
        self.assertEqual(divTest,'请输入邮箱名')
        # assertIn方法
        self.assertIn(divTest,'请输入邮箱名')

    def test_isAtuo_login(self):
        #验证自动登录已勾选
        isLogin=self.driver.find_element(By.ID,'store1')
        self.assertTrue(isLogin.is_selected())
    def test_isNotAtuo_login(self):
        #验证自动登录没有勾选
        isLogin = self.driver.find_element(By.ID, 'store1')
        isLogin.click()
        self.assertFalse(isLogin.is_selected())

#清理
    def tearDown(self) -> None:
        self.driver.close()

if __name__=='  main  ':
    unittest.main()

# 类测试固件:不管一个类里面有多少个测试用例,测试固件只执行一次,执行完一个测试点,要设置到首页的页面
class TestSina(unittest.TestCase):
    #初始化(大开要测试的浏览器)
    def setUpClass(cls) -> None:
        cls.driver=webdriver.Chrome()
        cls.driver.maximize_window()
        cls.driver.get('https://mail.sina.com.cn/')
        cls.driver.implicitly_wait(20)

        # 清理
        @classmethod
        def tearDown(cls) -> None:
            cls.driver.close()

if __name__=='  main  ':
    unittest.main()

 

百度练习

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
import time


class TestSina(unittest.TestCase):
    #初始化(大开要测试的浏览器)
    def setUp(self) -> None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://www.baidu.com/')
        self.driver.implicitly_wait(20)

    def tsetDown(self) -> None:
        self.driver.close()

    def test_so_value(self):
        '''验证输入框里面的文字信息'''
        so=self.driver.find_element(By.ID,'kw')
        so.send_keys('接口测试')
        self.assertEqual(so.get_attribute('value'),'接口测试')

    def test_baidu_title(self):
        #验证title
        self.assertEqual(self.driver.title,'百度一下,你就知道')
    def test_baidu_url(self):
        #验证当前地址
        self.assertTrue(self.driver.current_url.endswith('baidu.com/'))

if __name__=='  main  ':
    unittest.main()

 

qq文件的练

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
import time


class TestSina(unittest.TestCase):
    #初始化(打开要测试的浏览器)
    def setUp(self) -> None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://file.qq.com/')
        self.driver.implicitly_wait(20)



    def tearDown(self) -> None:
        self.driver.close()
    def test_qq_name(self):
        self.driver.switch_to.frame(0)
        self.driver.switch_to.frame(0)
        self.driver.find_element(By.ID, 'switcher_plogin').click()
        time.sleep(1)

        #验证qq帐号是否正确
        self.driver.find_element(By.CLASS_NAME, 'inputstyle').send_keys('123')
        self.driver.find_element(By.ID, 'login_button').click()
        time.sleep(1)
        divTest=self.driver.find_element(By.XPATH,'//*[@id="err_m"]').text
        self.assertEqual(divTest,'请输入正确的帐号!')

    def test_qq_allchick(self):
        '''验证全选按钮勾选'''
        self.driver.switch_to.frame(0)
        ischick=self.driver.find_element(By.XPATH,'//*[@id="accredit_info"]/ul/li[1]/label')
        self.assertFalse(ischick.is_selected())

    def test_qq_zc(self):
        #qq注册
        self.driver.switch_to.frame(0)
        self.driver.switch_to.frame(0)
        self.nowHandler = self.driver.current_window_handle
        self.driver.find_element(By.LINK_TEXT, '注册帐号').click()
        time.sleep(2)
        # 获取所有的窗口
        self.allHandlers = self.driver.window_handles
        # 对所有的窗口进行循环
        for hander in self.allHandlers:
            if hander != self.nowHandler:
                # 切换到新的窗口
                self.driver.switch_to.window(hander)
                time.sleep(1)
        self.driver.find_element(By.ID, 'get_acc').click()
        time.sleep(1)
        divTest1=self.driver.find_element(By.XPATH,'/html/body/div[3]/div[2]/div[1]/form/div[1]/div[3]/div').text
        self.assertEqual(divTest1,'昵称不可以为空')


if __name__=='  main  ':
    unittest.main()

创建自动化测试报告

创建一个和tests同级的文件夹report

 

 

 

 

 

在创建一个python文件run.py,run.py中编写代码

import os
import time
import unittest
import HTMLTestRunner
#
def allTests():
    #使用测试套件来加载所有的模块
    suite=unittest.TestLoader().discover(
        start_dir=os.path.dirname(__file__),
        pattern='test_*.py')
    return suite


def base_dir():
    return os.path.dirname(os.path.dirname(__file__))

def run():
    filename=os.path.join(base_dir(),'report','report.html')
    fp=open(filename,'wb')
    runner=HTMLTestRunner.HTMLTestRunner(
        stream=fp,
        title='自动化测试报告',
        description='UI自动化测试报告'
    )
    runner.run(allTests())

if __name__ == '__main__':
    run()

执行后结果:

 

e:错误

 

f:失败

 

. :成功

 

 

 

 

 

 

右键report,在浏览器中打开文件

 

 

 

 

自动化测试报告

 

 

pip3 install parameterized

参数化:相同的测试步骤,不同的测试数据,那么这样的场景可以使用参数化,使用参数化可以有效的提升测试的效率

导入from parameterized import param,parameterized

 

sina自动化测试代码: 

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from parameterized import param,parameterized

#分离继承
class Night(unittest.TestCase):
    def setUp(self) -> None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://mail.sina.com.cn/')
        self.driver.implicitly_wait(20)

    def tearDown(self) -> None:
        self.driver.close()

class Eight(unittest.TestCase):
    def setUp(self) -> None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://mail.sina.com.cn/')
        self.driver.implicitly_wait(20)
        #切换页面
        self.nowHandler = self.driver.current_window_handle
        self.driver.find_element(By.CLASS_NAME, 'registerBtn').click()
        time.sleep(2)
        # 获取所有的窗口
        self.allHandlers = self.driver.window_handles
        # 对所有的窗口进行循环
        for hander in self.allHandlers:
            if hander != self.nowHandler:
                # 切换到新的窗口
                self.driver.switch_to.window(hander)
                time.sleep(1)
        self.driver.find_element(By.ID, 'agreement1').click()
        time.sleep(1)
        self.driver.find_element(By.CLASS_NAME, 'subIco').click()
        time.sleep(1)

    def tearDown(self) -> None:
        self.driver.close()

class TestSina(Night):
    # def test_sina_email(self):
    #     '''验证不输入账号情况下的错误信息提示'''
    #     self.driver.find_element(By.CLASS_NAME,'loginBtn').click()
    #     time.sleep(1)
    #     divTest=self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]').text
    #     self.assertEqual(divTest,'请输入邮箱名')
    #
    # def test_sina_Femail(self):
    #     '''验证输入错误账号时的错误提示信息'''
    #     self.driver.find_element(By.ID,'freename').send_keys('4562')
    #     self.driver.find_element(By.CLASS_NAME, 'loginBtn').click()
    #     time.sleep(1)
    #     divTest=self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]').text
    #     self.assertEqual(divTest,'您输入的邮箱名格式不正确')
    #
    # def test_sina_Temail(self):
    #     '''验证输入正确账号时的错误提示信息'''
    #     self.driver.find_element(By.ID,'freename').send_keys('21331sd@sina.com')
    #     self.driver.find_element(By.CLASS_NAME,'loginBtn').click()
    #     time.sleep(1)
    #     divTest=self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[2]').text
    #     self.assertEqual(divTest,'请输入密码')



    def test_sina_Fpassword(self):
        '''验证密码都错误是时返回的错误信息'''
        self.driver.find_element(By.ID, 'freename').send_keys('21331sd@sina.com')
        self.driver.find_element(By.ID,'freepassword').send_keys('123')
        self.driver.find_element(By.CLASS_NAME, 'loginBtn').click()
        time.sleep(1)
        divTest=self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]').text
        self.assertEqual(divTest, '登录名或密码错误')
   
    #参数化
    @parameterized.expand([
        param('', '', '请输入邮箱名'),
        param('1235', '', '您输入的邮箱名格式不正确'),
        param('121331sd@sina.com', '23165', '登录名或密码错误')

    ])
    def test_sina_login_param(self, username, passward, result):
        '''使用参数化覆盖上面三个场景'''
        self.driver.find_element(By.ID, 'freename').send_keys(username)
        self.driver.find_element(By.ID, 'freepassword').send_keys(passward)
        self.driver.find_element(By.CLASS_NAME, 'loginBtn').click()
        time.sleep(1)
        divTest = self.driver.find_element(By.XPATH,
                                           '/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]').text
        self.assertEqual(divTest, result)
    #
    #
    def test_sina_isAuto(self):
        '''验证自动登录是否勾选'''
        islogin=self.driver.find_element(By.ID,'store1')
        self.assertTrue(islogin.is_selected())


class ceshi(Eight):

    @parameterized.expand([
        param('','','','','','','请输入邮箱名','请输入密码'),
        param('sdsa','1','','','','', '该邮箱名禁止注册,请换一个再试','密码的长度应该在6-16个字符之间'),
        param('1','','','','','', '邮箱名必须是4-16个字符之间(包括416','请输入密码'),
        param('!@#$%', '','','','','','邮箱名仅允许使用小写英文、数字或下划线','请输入密码'),
        param('XZCZX', '','','','','','不能有大写字母','请输入密码'),
        param('!!!!!','','','','','','不能有全角字符','请输入密码'),
        param('哈哈哈哈哈', '', '', '', '', '', '不能有中文','请输入密码')
    ])
    def test_email_address(self, email,passward,aginpassward,phone,photo,note, result,result1):
        self.driver.find_element(By.CLASS_NAME,'inputStyle').send_keys(email)
        self.driver.find_element(By.NAME,'psw').send_keys(passward)
        self.driver.find_element(By.NAME,'npsw').send_keys(aginpassward)
        self.driver.find_element(By.NAME,'phonenumber').send_keys(phone)
        self.driver.find_element(By.NAME,'imgvcode').send_keys(photo)
        self.driver.find_element(By.NAME,'msgvcode').send_keys(note)
        self.driver.find_element(By.CLASS_NAME, 'subIco').click()
        time.sleep(1)
        divTest=self.driver.find_element(By.XPATH,'/html/body/div[2]/div/div/div/div/form[1]/div[2]/ul/li[1]/div[3]/p/abbr').text
        divTest1=self.driver.find_element(By.XPATH,'/html/body/div[2]/div/div/div/div/form[1]/div[2]/ul/li[2]/div[1]/p/abbr').text
        self.assertEqual(divTest,result)
        self.assertEqual(divTest1,result1)

if __name__ == '__main__':
    unittest.main()

 

 

#执行全部关于sina的测试案例

import os
import time
import unittest
import HTMLTestRunner

def allTest():
    suite=unittest.TestLoader().discover(
        start_dir=os.path.dirname(__file__),
        pattern='test_*.py'
    )
    return suite

def base_dir():
    return os.path.dirname(os.path.dirname(__file__))

def run():
    sinatestsname=os.path.join(base_dir(),'report','sinareport.html')
    sinam=open(sinatestsname,'wb')
    runnner=HTMLTestRunner.HTMLTestRunner(
        stream=sinam,
        title='sina自动化测试报告',
        description='sina登录的自动化测试报告'
    )
    runnner.run(allTest())

if __name__ == '__main__':
    run()

 

sina的自动化测试报告:

 

 

csv文件

 

创建一个excel的表格

 

 

 

将后缀改为.csv的格式

 

再将此文件拷贝到自动化测试的包内

  

 

JSON的格式

 

 

 

 

创建并写入读取表的代码data1

import csv

#列表
def readCsvList():
    lists=[]
    with open('data.csv','r',encoding='utf-8') as f:
        reader=csv.reader(f)
        #取消读取第一行
        next(reader)
        for item in reader:
            lists.append(item[0])
        return lists
# print(readCsvList())

#字典
def readCsvDict():
    lists=[]
    with open('data.csv','r',encoding='utf-8-sig') as f:
        reader=csv.DictReader(f)
        for item in reader:
            lists.append(dict(item))
        return lists
# print(readCsvDict())

 

#excel

def readExcel():
    lists=[]
    book=xlrd.open_workbook('data.xlsx')
    sheet=book.sheet_by_index(0)
    for item in range(1,sheet.nrows):
        lists.append(sheet.row_values(item)[0])
    return lists
# print(readExcel())

 

#json

def readJson():
    return json.load(open('sina.json', 'r', encoding='utf-8'))

 

data1导入到自动化测试的包中

导入代码为:from data_list.data1 import *

 

然后再进行测试

import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from data_list.data1 import *

class Init(unittest.TestCase):
    def setUp(self) -> None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://mail.sina.com.cn/')
        self.driver.implicitly_wait(20)

    def tearDown(self) -> None:
        self.driver.close()

class TestSina(Init):

    def test_username_n(self):
        '''用户名为空'''
        self.driver.find_element(By.CLASS_NAME,'loginBtn').click()
        time.sleep(1)
        

divTest=self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]').text
        # self.assertEqual(divTest,readCsvList()[0])  #表的方式
        # self.assertEqual(divTest,readCsvDict()[0]['result'])  #字典的方式
        #self.assertEqual(divTest, readExcel()[0])  #excel的方式
        self.assertEqual(divTest, readJson()["sinaNull"])  #json的方式

 



    def test_username_f(self):
        '''用户名错误'''
        self.driver.find_element(By.ID,'freename').send_keys('1234')
        self.driver.find_element(By.CLASS_NAME,'loginBtn').click()
        time.sleep(1)
        divTest=self.driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]').text
        # self.assertEqual(divTest,readCsvList()[1])  #表的方式
        # self.assertEqual(divTest, readCsvDict()[1]['result'])  #字典的方式
        #self.assertEqual(divTest, readExcel()[1])  #excel的方式
        self.assertEqual(divTest, readJson()["emailF"])  #json的方式



if __name__ == '__main__':
    unittest.main()

 

 

 

 

 

posted @   丶空·  阅读(834)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示