[英]How do I use pytest with bazel?
我有一個實現my_module
的my_module.py
文件和一個import my_module
並運行一些用pytest編寫的測試的文件test_my_module.py
。
通常我通過cd
進入包含這兩個文件的目錄運行測試,然后執行
pytest
現在我想使用 Bazel。 我已將my_module.py
添加為py_binary
但我不知道調用測試的正確方法是什么。
將以下代碼添加到test_my_module.py
並在BUILD
文件中將測試腳本標記為py_test
而不是py_binary
:
if __name__ == "__main__":
import pytest
raise SystemExit(pytest.main([__file__]))
然后您可以使用bazel test test_my_module
運行您的測試
如果要創建可重用代碼,則不需要添加對 pytest 的調用,並在每個 python 文件的末尾添加測試。 您可以創建調用 python 文件的 py_test 調用,該文件包含對pytest
的調用並保留所有參數。 然后圍繞 py_test 創建一個宏。 我在 Bazel 的實驗中解釋了詳細的解決方案: Python (3), linter & pytest ,並附有源代碼鏈接。
在tools/pytest/pytest_wrapper.py
中創建 python 工具(包裝調用 pytest,或僅 pylint)
import sys
import pytest
# if using 'bazel test ...'
if __name__ == "__main__":
sys.exit(pytest.main(sys.argv[1:]))
在tools/pytest/defs.bzl
中創建宏
"""Wrap pytest"""
load("@rules_python//python:defs.bzl", "py_test")
load("@my_python_deps//:requirements.bzl", "requirement")
def pytest_test(name, srcs, deps = [], args = [], data = [], **kwargs):
"""
Call pytest
"""
py_test(
name = name,
srcs = [
"//tools/pytest:pytest_wrapper.py",
] + srcs,
main = "//tools/pytest:pytest_wrapper.py",
args = [
"--capture=no",
"--black",
"--pylint",
"--pylint-rcfile=$(location //tools/pytest:.pylintrc)",
# "--mypy",
] + args + ["$(location :%s)" % x for x in srcs],
python_version = "PY3",
srcs_version = "PY3",
deps = deps + [
requirement("pytest"),
requirement("pytest-black"),
requirement("pytest-pylint"),
# requirement("pytest-mypy"),
],
data = [
"//tools/pytest:.pylintrc",
] + data,
**kwargs
)
從tools/pytest/BUILD.bazel
暴露一些資源
exports_files([
"pytest_wrapper.py",
".pylintrc",
])
從您的 package BUILD.bazel
調用它
load("//tools/pytest:defs.bzl", "pytest_test")
...
pytest_test(
name = "test",
srcs = glob(["*.py"]),
deps = [
...
],
)
然后調用bazel test //...
意味着pylint
、 pytest
和black
都是測試流程的一部分。
繼@David Bernard 之后,他在一系列很棒的博客文章中寫了他的答案順便說一句,那里有一個曲線球 pytest + bazel + Windows ...
長話短說,您需要將legacy_create_init = 0
添加到py_test
規則調用中。
這是一個“功能”的解決方法,即使您的存儲庫https://github.com/bazelbuild/rules_python/issues/55中沒有任何文件,bazel 也會在沙箱中創建__init__.py
文件
似乎這里的一堆建議現在已經打包到https://github.com/caseyduquettesc/rules_python_pytest中。
load("@rules_python_pytest//python_pytest:defs.bzl", "py_pytest_test")
py_pytest_test(
name = "test_w_pytest",
size = "small",
srcs = ["test.py"],
deps = [
# TODO Add this for the user
requirement("pytest"),
],
)
編輯:我是上述存儲庫的作者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.