fixture初始化了driver,但是钩子函数每次都会报driver为空

问题

这一行报错none没有screenshot的方法,driver没有初始化

原因

  • 调用顺序错误,pytest_runtest_protocol会在fixtrue前执行

解决方案

1.创建一个 fixture 初始化 driver

import pytest
from selenium import webdriver

@pytest.fixture(scope="session")
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

2.修改 pytest_runtest_protocol 函数

为了使 driver 可用于 pytest_runtest_protocol 钩子函数,可以将 driver 存储在 pytestitem 对象上,并从中检索:

import os
import pytest
from _pytest.runner import runtestprotocol

def pytest_runtest_protocol(item, nextitem):
    # 获取driver
    driver = getattr(item, 'driver', None)
    
    if driver is None:
        raise ValueError("Driver is not initialized. Ensure the driver is set properly.")
    
    reports = runtestprotocol(item, nextitem=nextitem)
    cur_path = os.path.abspath(__file__)
    logs_path = os.path.join(os.path.abspath(os.path.dirname(cur_path) + os.path.sep + '../Report'), '')
    case_mark = item.instance.pytestmark[0].name
    
    for report in reports:
        if report.outcome != 'passed':
            if '::' in report.nodeid:
                file_name = report.nodeid.split('/')[-1].replace("::", "_") + ".png"
                file_name = file_name.encode('utf-8').decode('unicode_escape')
            else:
                file_name = report.nodeid + ".png"
                
            MintBlueLogger.info(file_name)
            folder = os.path.exists(logs_path + case_mark)
            
            if not folder:
                os.makedirs(logs_path + case_mark)
                
            MintBlueLogger.info(os.path.join(logs_path + case_mark, file_name))
            driver.get_screenshot_as_file(os.path.join(logs_path + case_mark, file_name))
    
    return True

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_setup(item):
    driver = item.session.driver
    setattr(item, 'driver', driver)
    yield

3.在 pytest_configure 中初始化 driver 并存储在 session

def pytest_configure(config):
    driver = webdriver.Chrome()
    config.session.driver = driver

def pytest_unconfigure(config):
    driver = getattr(config.session, 'driver', None)
    if driver:
        driver.quit()

1 个赞