python - 在 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 设为全局,它仍在显示。如何解决这个问题?
解决方案
Fixtures 在pytest_csv_register_columns
hook 执行后被评估,所以你不能在 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}, ...]"
推荐阅读
- responsive-design - 在 Google App Maker 中加入响应式设计
- python - 如何根据日期字符串输入获取月份中的天数
- elasticsearch - Elasticsearch 自定义映射定义
- slider - Foundation 6 - 滑块输入值?
- scons - SCONS env.Library() 没有得到预期的环境编译标志
- ruby-on-rails - 如何修复 ngrok 权限被拒绝?
- swift - 创建自定义嵌套表格视图单元格
- apache-spark - 如何进行循环和计算以在 spark scala 数据框中查找多次行程的距离
- c# - 从 Sharepoint CSOM 下载文件时访问被拒绝
- c++ - Laplacian Sharpening result is kinda greyish C++