Pytest的 conftest.py + selenium 基本使用
程序员文章站
2024-02-27 13:49:51
...
项目结构如图
文件 conftest.py 代码
import os
import pytest
from selenium import webdriver
medriver = None
@pytest.fixture(scope='session', autouse=True)
def medrivers(request):
global medriver
basedir = os.getcwd()
chrome_driver = basedir + "/Scripts/chromedriver.exe" # 驱动器位置
chrome_position = basedir + "/Chrome/Chrome.exe" # 浏览器位置
chrome_option_set = webdriver.ChromeOptions()
chrome_option_set.binary_location = chrome_position # 设置谷歌浏览器EXE的位置
# chrome_option_set.add_argument('--headless') # 无头模式运行浏览器
if medriver is None:
print("\n---- Start Chrome -----")
medriver = webdriver.Chrome(executable_path=chrome_driver, options=chrome_option_set) # 启动浏览器
medriver.maximize_window()
def Exit_Chrome():
print("\n---- End Chrome -----")
medriver.quit()
request.addfinalizer(Exit_Chrome)
return medriver
文件 test_01.py 的代码
import time
def test_getinfo(medrivers):
print("------ 外部函数 获取 BETA URL ------")
medrivers.get("https://www.baidu.com/")
time.sleep(10)
class Test_Get(object):
def test_url(self, medrivers):
print("------ CLASS里面的函数,获取 JIRA URL ------")
medrivers.get("http://www.sogo.com/")
time.sleep(10)
文件 run.py 的代码
import pytest
if __name__ == "__main__":
pytest.main(['-s', '../PytestAllure'])
运行结果如下
============================= test session starts =============================
platform win32 -- Python 3.7.5, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: D:\InstanceProject\Python\PytestAllure
plugins: allure-pytest-2.8.40, assume-2.4.3
collected 2 items
test_01.py
---- Start Chrome -----
------ 外部函数 获取 URL ------
.------ CLASS里面的函数,获取 URL ------
.
---- End Chrome -----
============================= 2 passed in 25.43s ==============================
Process finished with exit code 0