首页 > 解决方案 > 在 pytest-csv 中添加 selenium 的浏览器日志作为自定义列

问题描述

我想将浏览器日志添加为所有测试的单独列pytest

pytest-csv用于存储日志。

我的pytest夹具是这样的:

@pytest.fixture(scope='module')
def browser(request):
  chrome_options = Options()
  global b
  b = selenium.webdriver.Chrome(chrome_options=chrome_options)
  b.implicitly_wait(10)
  yield b
  b.quit()

为了添加自定义列,我在 conftest.py 中添加了这个函数

def pytest_csv_register_columns(columns):
   columns['ConsoleOutput'] = b.get_log('browser')

NameError: name 'b' is not defined即使我已将 b 设为全局,它仍在显示。如何解决这个问题?

标签: pythonseleniumpytest

解决方案


Fixtures 在pytest_csv_register_columnshook 执行后被评估,所以你不能在 hook 中引用它们。如果您需要访问pytest列数据的固定装置或其他内部结构,请改为传递函数。pytest-csv 来源示例:

>>> columns['my_simple_column'] = lambda item, report: {'my column': report.nodeid}

在您的情况下,这可以实现为:

@pytest.fixture
def browser(request):
    ...


def _output_column_builder(item, report):
    # check if the test case requests the browser fixture
    if "browser" in item.fixturenames:
        # get browser fixture value
        browser_fixture_value = item.funcargs["browser"]
        logs = browser_fixture_value.get_log('browser')
    else:
        logs = []
    return {"chrome_console": logs}


def pytest_csv_register_columns(columns):
   columns["ConsoleOutput"] = _output_column_builder

样品测试:

def test_yt(browser):
    browser.get('https://www.youtube.com')

运行测试现在将以 JSON 格式记录浏览器日志:

$ pytest --csv out.csv --csv-columns ConsoleOutput
...
$ cat out.csv
chrome_console
"[{'level': 'WARNING', 'message': 'https://www.youtube.com/ - A cookie associated with a cross-site resource at https://accounts.google.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.', 'source': 'other', 'timestamp': 1586104294304}, ...]"

推荐阅读