1.在项目下创建一个python包(Baidu),在包下创建一个py文件(baidutest.py);
2.在baidutest.py文件中创建一个类(BaiduWeb),并将常用方法放在类下;
from selenium.webdriver.common.by import By
from time import sleep
class BaiduWeb:
# 构造函数创建webdriver驱动
def __init__(self,driver):
self.driver = driver
# 访问浏览器
def open(self,url):
self.driver.get(url)
# 关闭浏览器
def quit(self):
self.driver.quit()
# 输入数据
def input(self,value,txt):
el = self.driver.find_element(by=By.ID,value=value)
el.clear()
el.send_keys(txt)
# 强制等待
def wait(self,time_):
sleep(time_)
# 断言
def assert_att(self,word):
try:
att = self.driver.find_element(by=By.XPATH,value='//*[contains(text(),\"' + word + '\")]').text
assert word in att
except Exception as e:
return e
# 切换窗口
def switch(self,n):
self.driver.switch_to.window(self.driver.window_handles[n])
# 关闭页签
def close_switch(self,n):
self.driver.switch_to.window(self.driver.window_handles[n])
self.driver.close()
self.driver.switch_to.window(self.driver.window_handles[0])
3.继续在项目下创建一个python包(data),在包下创建一个yaml文件(baidudata.yaml),在yaml文件中录入测试数据;
-
url: https://www.baidu.com
value: kw
txt: python
-
url: https://www.baidu.com
value: kw
txt: java
-
url: https://www.baidu.com
value: kw
txt: 软件测试
4.封装一个数据驱动,继续在项目下创建一个python包(yaml_data),在包下创建一个py文件(yamltest.py)
import yaml
def load_yaml(path):
file = open(path,'r',encoding='gb18030',errors='ignore')
data = yaml.load(file,Loader=yaml.FullLoader)
return data
5.创建page.py文件来存储搜索,继续在项目下创建一个python包(Page),在包下创建一个py文件(baidu_page.py)
from pythonProject.study.Baidu.baidutest import BaiduWeb
from selenium.webdriver.common.by import By
class BaudiPage(BaiduWeb):
url = 'https://www.baidu.com'
def search_input(self,search_key):
self.driver.find_element(by=By.ID,value='kw').send_keys(search_key)
def search_button(self):
self.driver.find_element(by=By.ID,value='su').click()
6.继续在项目下创建一个python包(test_case),在包下创建一个py文件(test_case2.py),并写入执行代码
import pytest
from selenium import webdriver
from pythonProject.study.Baidu.baidutest import BaiduWeb
from pythonProject.study.yaml_date.yamltest import load_yaml
from pythonProject.study.Page.baidu_page import BaudiPage
import os
class Testbaidu():
@classmethod
def setup_class(cls):
cls.driver = webdriver.Chrome()
@pytest.mark.parametrize('data',load_yaml('../data/baidudata.yaml'))
def test_baudiweb(self,data):
page = BaudiPage(self.driver)
page.open(data['url'])
page.wait(2)
page.search_input(data['txt'])
page.wait(1)
page.assert_att(data['txt'])
page.wait(1)
@classmethod
def steardown_class(cls):
cls.driver.quit()
if __name__ == '__main__':
pytest.main(["test_case2.py","--alluredir",'../test_report/result'])
os.system("allure generate ../test_report/result/ -o ../test_report/report_allure/ --clean")
# allure generate 命令,固定的
# ../test_report/result/ 临时的json格式报告的路径
# -o 输出output
# ../test_report/report_allure/ 生成的allure报告路径
# --clean 清空report_allure文件夹下原来的报告
7.继续在项目下创建一个python包(test_report),在包下创建一个目录(result)
8.运行后查看生成的报告