project > test_po > conftest.py
project > test_po > test_baidu.py
# project > test_po > conftest.py
import allure
import pytest
from selenium import webdriver
@pytest.fixture(scope="session")
def driver():
driver = webdriver.Chrome()
driver.maximize_window()
print("打开浏览器")
yield driver
print("关闭浏览器")
driver.close()
driver.quit()
@pytest.fixture()
def fixture():
print("我是前置步骤")
yield "XXX"
print("我是后置步骤")
# baidu网页,登录与未登录,两种场景各不相同。
from selenium.webdriver.common.by import By
class TestBaidu:
def test_baidu1(self, driver):
#未登录测试
driver.get("https://www.baidu.com/")
title = driver.title
url = driver.current_url
text = driver.find_element(By.CSS_SELECTOR, 'a[href="http://news.baidu.com"]').text
button_text = driver.find_element(By.ID, 'su').accessible_name
assert title == "百度一下,你就知道"
assert url == "https://www.baidu.com/"
assert text == "新闻"
assert button_text == "百度一下"
def test_baidu2(self, driver):
# 登录测试
driver.get("https://www.baidu.com/")
title = driver.title
url = driver.current_url
text = driver.find_element(By.CSS_SELECTOR, 'a[href="http://news.baidu.com"]').text
button_text = driver.find_element(By.ID, 'su').accessible_name
assert title == "百度一下,你就知道"
assert url == "https://www.baidu.com/"
assert text == "新闻"
assert button_text == "百度一下"
CSS的五种定位方式 (baidu.com)
selenium 用By定位元素 - 知乎 (zhihu.com)
image.png
上面案例,如果访问网页发生变化,则后续所有case都会fail,如何维护?
# Page Object解决什么问题
可以解决元素定位改变带来的维护成本的增加
元素定位与用例分离
代码冗余
是不是可以把网页提取为一个公用的东西?如果定位链接发生改变,只需要在一个地方更改即可
news = (By.CSS_SELECTOR, 'a[href="http://news.baidu.com"]')
button = (By.ID, 'su')
这两句放到类下面的公共部分,让类里面的每个函数去调用。调用的使用用 类.方法
如 TestBaidu.su
为了避免数据类型等不明报错,在类名前面需要加*, * 执行元组解包的动作,则可执行通过
a=(1,2)
print(a)
> (1, 2)
print(*a)
> 1 2
from selenium.webdriver.common.by import By
class TestBaidu:
news = (By.CSS_SELECTOR, 'a[href="http://news.baidu.com"]')
button = (By.ID, 'su')
def test_baidu1(self, driver):
#未登录测试
driver.get("https://www.baidu.com/")
title = driver.title
url = driver.current_url
text = driver.find_element(*TestBaidu.news).text
button_text = driver.find_element(*TestBaidu.button).accessible_name
assert title == "百度一下,你就知道"
assert url == "https://www.baidu.com/"
assert text == "新闻"
assert button_text == "百度一下"
def test_baidu2(self, driver):
# 登录测试
driver.get("https://www.baidu.com/")
title = driver.title
url = driver.current_url
text = driver.find_element(*TestBaidu.news).text
button_text = driver.find_element(*TestBaidu.button).accessible_name
assert title == "百度一下,你就知道"
assert url == "https://www.baidu.com/"
assert text == "新闻"
assert button_text == "百度一下"
网友评论