智造喵地址:https://chat.plexpt.com/i/511440
以下是一个简单的Python pytest selenium单元测试框架的示例:
代码语言:javascript复制import pytest
from selenium import webdriver
class TestWebPage:
@pytest.fixture(scope="class")
def setup_class(self):
self.driver = webdriver.Chrome()
self.driver.get("http://www.example.com")
yield
self.driver.quit()
def test_page_title(self, setup_class):
assert self.driver.title == "Example Domain"
def test_page_heading(self, setup_class):
assert self.driver.find_element_by_tag_name("h1").text == "Example Domain"
def test_page_link(self, setup_class):
link = self.driver.find_element_by_link_text("More information...")
assert link.text == "More information..."
assert link.get_attribute("href") == "https://www.iana.org/domains/example"
if __name__ == '__main__':
pytest.main()
另外,pytest还提供了很多有用的特性,例如参数化、标记、夹具等,可以更加灵活地组织和运行测试用例。以下是一个使用参数化的示例
import pytest
from selenium import webdriver
class TestWebPage:
@pytest.fixture(scope="class")
def setup_class(self):
self.driver = webdriver.Chrome()
self.driver.get("http://www.example.com")
@pytest.mark.parametrize("link_text,link_url", [("More information...", "https://www.iana.org/domains/example"), ("IANA", "https://www.iana.org/")])
def test_page_link(self, setup_class, link_text, link_url):
link = self.driver.find_element_by_link_text(link_text)
assert link.text == link_text
assert link.get_attribute("href") == link_url
def teardown_class(self):
self.driver.quit()
if __name__ == '__main__':
pytest.main()