Pytest-selenium简单使用示例


Pytest-selenium是Pytest的一个插件, 安装方法:

pip3 install pytest pytest-selenium

用例编写时只需要在测试函数中传入selenium参数作为driver使用即可, 如下:
# test_baidu.py
def test_baidu(selenium):
    selenium.get("https://www.linuxboy.net")  # selenium即driver

然后在运行时指定通过--driver指定浏览器即可:
pytest test_baidu.py --driver Chrome

需要提前配置好selenium环境及chromedriver

下面是一个Django后台添加课程的简单使用示例:
# test_add_course.py
import pytest
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.expected_conditions import presence_of_element_located as element_exist

@pytest.fixture  # 指定为fixture方法(测试准备/清理方法)
def login(selenium):  # selenium为使用pytest-selenium固定参数, 相当于driver, 运行时通过--driver指定浏览器
    selenium.get("http://linuxboy.net:8000/admin/")
    selenium.find_element_by_id("id_username").send_keys("hanzhichao")
    selenium.find_element_by_id("id_password").send_keys("hanzhichao123")
    selenium.find_element_by_class_name("submit-row").click()


@pytest.fixture
def del_course(selenium):  # 用于测试完删除新建的文章
    yield  # yield以下为teardown清理代码, 用例执行完运行
    selenium.find_element_by_link_text("Python接口测试教程").click()
    selenium.find_element_by_class_name("deletelink").click()
    selenium.find_element_by_css_selector("input[type='submit']").click()


def test_add_course(selenium, login, del_course):  # 通过参数使用fixtures方法login及del_course
    selenium.find_element_by_link_text("Courses").click()  # 点击'Courses'链接
    selenium.find_element_by_class_name("addlink").click()  # 点击'新增 COURSE'按钮
    Select(selenium.find_element_by_id("id_owner")).select_by_visible_text("hanzhichao")  # 选择作者
    Select(selenium.find_element_by_id("id_subject")).select_by_visible_text("接口测试")  # 选择主题
    selenium.find_element_by_id("id_title").send_keys("Python接口测试教程")  # 输入文章标题
    selenium.find_element_by_id("id_overview").send_keys("作者:临渊")  # 输入描述
    selenium.find_element_by_class_name("default").click()  # 点击保存
    assert element_exist(("link text", "Python接口测试教程"))  # 断言返回的页面存在标题名的链接

运行方法:
pytest test_add_course.py --driver Chrome

linuxboy的RSS地址:https://www.linuxboy.net/rssFeed.aspx

本文永久更新链接地址:https://www.linuxboy.net/Linux/2019-06/158957.htm

相关内容

    暂无相关文章