示例:
# -*- coding: utf-8 -*- from selenium import webdriver import pytest import time from selenium.webdriver import ActionChains def setup_module(): global driver print("\n执行初始化") driver = webdriver.Chrome() driver.maximize_window() # 打开浏览器并访问目标页面 driver.get('https://www.mi.com/') def teardown_module(): global driver # 退出浏览器 print("执行清除") driver.quit() pass def test_xiaomi1(): # 执行1 global driver menu = driver.find_element_by_link_text(u'小米手机') ac = ActionChains(driver) ac.move_to_element(menu).perform() time.sleep(2) items = driver.find_elements_by_css_selector('#J_navMenu .title') titles = [] for item in items: titles.append(item.text) print(titles) assert titles == ['Xiaomi MIX 4', '小米MIX FOLD', '小米11 Ultra', '小米11 Pro', '小米11 青春版', '小米10S'] def test_xiaomi2(): # 执行2 global driver menu = driver.find_element_by_link_text(u'Redmi 红米') ac = ActionChains(driver) ac.move_to_element(menu).perform() time.sleep(3) items = driver.find_elements_by_css_selector('#J_navMenu .title') titles = [] for item in items: titles.append(item.text) print(titles) assert titles == ['Redmi Note 10 Pro', 'Redmi Note 10 5G', 'K40 游戏增强版', 'K40 Pro 系列', 'Redmi K40', 'Redmi Note 9 4G'] if __name__ == '__main__': pytest.main(['xiaomi_page.py','-s','--alluredir=tmp/test_reports']) # pytest框架中测试用例要以test开头,如test01(),或者test_01() # '-s', 输出日志 # '--alluredir=tmp/test_reports' 指定生成allure测试报告路径 # 控制台输入 allure serve tmp/test_reports 打开allure测试报告 # 控制台输入 allure serve tmp/test_reports 打开allure测试报告
控制台输出 :
D:\Python3.8.2\python.exe D:/PycharmProjects/Python-Excel/xiaomi_page.py ============================= test session starts ============================= platform win32 -- Python 3.8.2, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 rootdir: D:\PycharmProjects\Python-Excel plugins: allure-pytest-2.8.40, html-3.1.1, metadata-1.11.0 collected 2 items xiaomi_page.py 执行初始化 ['Xiaomi MIX 4', '小米MIX FOLD', '小米11 Ultra', '小米11 Pro', '小米11 青春版', '小米10S'] .['Redmi Note 10 Pro', 'Redmi Note 10 5G', 'K40 游戏增强版', 'K40 Pro 系列', 'Redmi K40', 'Redmi Note 9 4G'] .执行清除 ============================= 2 passed in 16.61s ==============================
注意 :
# pytest框架中测试用例要以test开头,如test01(),或者test_01() # '-s', 输出日志 # '--alluredir=tmp/test_reports' 指定生成allure测试报告路径 # 控制台输入 allure serve tmp/test_reports 打开allure测试报告 # 控制台输入 allure serve tmp/test_reports 打开allure测试报告 查看测试报告, pycharm teminal 中输入allure serve tmp/test_reports