在 Bazel 中测试 Starlark 代码有几种不同的方法。本页面按用例收集了当前的最佳做法和框架。
测试规则
Skylib 具有一个名为 unittest.bzl
的测试框架,用于检查规则的分析时行为,例如其操作和提供程序。此类测试称为“分析测试”,目前是测试规则内部工作的最佳选择。
一些注意事项:
测试断言在 build 内发生,而不是在单独的测试运行程序进程中进行。测试创建的目标必须命名,使其不会与其他测试或 build 的目标冲突。在测试期间发生的错误会由 Bazel 视为构建中断,而非测试失败。
它需要使用大量样板来设置被测规则以及包含测试断言的规则。此样板最初可能令人望而生畏。请注意,宏会在加载阶段进行评估和生成目标,而规则实现函数要到稍后才在分析阶段运行。
分析测试旨在相当小且轻量。分析测试框架的某些功能仅限验证具有最大传递依赖项(目前为 500 个)的目标。这是由于将这些功能与更大的测试搭配使用会对性能造成影响。
基本原则是定义依赖于被测规则的测试规则。这让测试规则可以访问被测规则的提供方。
测试规则的实现函数会执行断言。如果出现任何失败情况,这些错误不会通过调用 fail()
(这将触发分析时构建错误)立即引发,而是将错误存储在测试执行失败的生成脚本中。
请参见下文,了解最基本的玩具示例以及随后用于检查操作的示例。
极简示例
//mypkg/myrules.bzl
:
MyInfo = provider(fields = {
"val": "string value",
"out": "output File",
})
def _myrule_impl(ctx):
"""Rule that just generates a file and returns a provider."""
out = ctx.actions.declare_file(ctx.label.name + ".out")
ctx.actions.write(out, "abc")
return [MyInfo(val="some value", out=out)]
myrule = rule(
implementation = _myrule_impl,
)
//mypkg/myrules_test.bzl
:
load("@bazel_skylib//lib:unittest.bzl", "asserts", "analysistest")
load(":myrules.bzl", "myrule", "MyInfo")
# ==== Check the provider contents ====
def _provider_contents_test_impl(ctx):
env = analysistest.begin(ctx)
target_under_test = analysistest.target_under_test(env)
# If preferred, could pass these values as "expected" and "actual" keyword
# arguments.
asserts.equals(env, "some value", target_under_test[MyInfo].val)
# If you forget to return end(), you will get an error about an analysis
# test needing to return an instance of AnalysisTestResultInfo.
return analysistest.end(env)
# Create the testing rule to wrap the test logic. This must be bound to a global
# variable, not called in a macro's body, since macros get evaluated at loading
# time but the rule gets evaluated later, at analysis time. Since this is a test
# rule, its name must end with "_test".
provider_contents_test = analysistest.make(_provider_contents_test_impl)
# Macro to setup the test.
def _test_provider_contents():
# Rule under test. Be sure to tag 'manual', as this target should not be
# built using `:all` except as a dependency of the test.
myrule(name = "provider_contents_subject", tags = ["manual"])
# Testing rule.
provider_contents_test(name = "provider_contents_test",
target_under_test = ":provider_contents_subject")
# Note the target_under_test attribute is how the test rule depends on
# the real rule target.
# Entry point from the BUILD file; macro for running each test case's macro and
# declaring a test suite that wraps them together.
def myrules_test_suite(name):
# Call all test functions and wrap their targets in a suite.
_test_provider_contents()
# ...
native.test_suite(
name = name,
tests = [
":provider_contents_test",
# ...
],
)
//mypkg/BUILD
:
load(":myrules.bzl", "myrule")
load(":myrules_test.bzl", "myrules_test_suite")
# Production use of the rule.
myrule(
name = "mytarget",
)
# Call a macro that defines targets that perform the tests at analysis time,
# and that can be executed with "bazel test" to return the result.
myrules_test_suite(name = "myrules_test")
可使用 bazel test //mypkg:myrules_test
运行测试。
除了初始的 load()
语句之外,该文件还包含两个主要部分:
测试本身,每个测试都包含 1) 针对测试规则的分析时实现函数,2) 通过
analysistest.make()
声明测试规则,3) 用于声明被测规则(及其依赖项)和测试规则的加载时间函数(宏)。如果断言在测试用例之间不会发生变化,则 1) 和 2) 可能会被多个测试用例共享。测试套件函数,用于为每个测试调用加载时间函数,并声明一个将所有测试捆绑在一起的
test_suite
目标。
为了保持一致性,请遵循建议的命名惯例:让 foo
代表测试名称,用于描述测试要检查的内容(上面示例中的 provider_contents
)。例如,JUnit 测试方法将命名为 testFoo
。
那么:
用于生成测试和被测目标的宏应命名为
_test_foo
(_test_provider_contents
)其测试规则类型应命名为
foo_test
(provider_contents_test
)此规则类型的目标标签应为
foo_test
(provider_contents_test
)测试规则的实现函数应命名为
_foo_test_impl
(_provider_contents_test_impl
)被测规则的目标标签及其依赖项应带有
foo_
(provider_contents_
) 前缀
请注意,所有目标的标签都可能会与同一 build 软件包中的其他标签发生冲突,因此最好为测试使用一个独一无二的名称。
故障测试
验证在输入某些内容时或在特定状态下失败时,规则可能会很有用。这可以使用分析测试框架来完成:
使用 analysistest.make
创建的测试规则应指定 expect_failure
:
failure_testing_test = analysistest.make(
_failure_testing_test_impl,
expect_failure = True,
)
测试规则实现应就发生的失败的性质(具体而言,就是失败消息)做出断言:
def _failure_testing_test_impl(ctx):
env = analysistest.begin(ctx)
asserts.expect_failure(env, "This rule should never work")
return analysistest.end(env)
此外,还要确保被测目标明确标记为“人工”。
否则,使用 :all
构建软件包中的所有目标将会导致有意失败的目标构建,并且会显示构建失败。如果设置为“manual”,则只有明确指定,或者要作为非手动目标的依赖项(例如测试规则)才能构建被测目标:
def _test_failure():
myrule(name = "this_should_fail", tags = ["manual"])
failure_testing_test(name = "failure_testing_test",
target_under_test = ":this_should_fail")
# Then call _test_failure() in the macro which generates the test suite and add
# ":failure_testing_test" to the suite's test targets.
验证已注册的操作
您可能需要编写对规则注册的操作的断言,例如,使用 ctx.actions.run()
。这可以在分析测试规则实现函数中完成。示例如下:
def _inspect_actions_test_impl(ctx):
env = analysistest.begin(ctx)
target_under_test = analysistest.target_under_test(env)
actions = analysistest.target_actions(env)
asserts.equals(env, 1, len(actions))
action_output = actions[0].outputs.to_list()[0]
asserts.equals(
env, target_under_test.label.name + ".out", action_output.basename)
return analysistest.end(env)
请注意,analysistest.target_actions(env)
会返回 Action
对象的列表,这些对象表示由受测目标注册的操作。
验证不同标志下的规则行为
您可能需要验证特定规则在给定特定 build 标志时的行为方式。例如,如果用户指定了以下规则,您的行为方式可能会有所不同:
bazel build //mypkg:real_target -c opt
对比
bazel build //mypkg:real_target -c dbg
乍一看,这可以通过使用所需的 build 标志测试被测目标来实现:
bazel test //mypkg:myrules_test -c opt
但是,您的测试套件不可能同时包含一个用于验证 -c opt
下规则行为的测试和另一个用于验证 -c dbg
下规则行为的测试。这两个测试无法在同一 build 中运行!
这可以通过在定义测试规则时指定所需的 build 标志来解决:
myrule_c_opt_test = analysistest.make(
_myrule_c_opt_test_impl,
config_settings = {
"//command_line_option:compilation_mode": "opt",
},
)
通常,系统会根据当前 build 标志分析受测目标。指定 config_settings
会替换指定命令行选项的值。(任何未指定的选项都将保留其在实际命令行中的值)。
在指定的 config_settings
字典中,命令行标志必须以特殊占位符值 //command_line_option:
为前缀,如上所示。
验证工件
检查生成的文件是否正确的主要方法有:
您可以使用 shell、Python 或其他语言编写测试脚本,并创建适当的
*_test
规则类型的目标。您可以针对要执行的测试使用专用规则。
使用测试目标
验证工件的最直接方法是编写脚本并将 *_test
目标添加到 BUILD 文件中。您要检查的特定工件应该是此目标的数据依赖项。如果验证逻辑可重复用于多个测试,则应该是一个采用命令行参数(由测试目标的 args
属性控制)的脚本。下面的示例将验证上述 myrule
的输出是否为 "abc"
。
//mypkg/myrule_validator.sh
:
if [ "$(cat $1)" = "abc" ]; then
echo "Passed"
exit 0
else
echo "Failed"
exit 1
fi
//mypkg/BUILD
:
...
myrule(
name = "mytarget",
)
...
# Needed for each target whose artifacts are to be checked.
sh_test(
name = "validate_mytarget",
srcs = [":myrule_validator.sh"],
args = ["$(location :mytarget.out)"],
data = [":mytarget.out"],
)
使用自定义规则
一种更复杂的方法是将 shell 脚本编写为可通过新规则实例化的模板。这会涉及更多间接性和 Starlark 逻辑,但会使 build 文件更简洁。这样做的好处是,任何参数预处理都可以在 Starlark 而不是脚本中完成,并且该脚本会略微多一些自我记录,因为它使用符号占位符(用于替换)而不是数字占位符(用于参数)。
//mypkg/myrule_validator.sh.template
:
if [ "$(cat %TARGET%)" = "abc" ]; then
echo "Passed"
exit 0
else
echo "Failed"
exit 1
fi
//mypkg/myrule_validation.bzl
:
def _myrule_validation_test_impl(ctx):
"""Rule for instantiating myrule_validator.sh.template for a given target."""
exe = ctx.outputs.executable
target = ctx.file.target
ctx.actions.expand_template(output = exe,
template = ctx.file._script,
is_executable = True,
substitutions = {
"%TARGET%": target.short_path,
})
# This is needed to make sure the output file of myrule is visible to the
# resulting instantiated script.
return [DefaultInfo(runfiles=ctx.runfiles(files=[target]))]
myrule_validation_test = rule(
implementation = _myrule_validation_test_impl,
attrs = {"target": attr.label(allow_single_file=True),
# You need an implicit dependency in order to access the template.
# A target could potentially override this attribute to modify
# the test logic.
"_script": attr.label(allow_single_file=True,
default=Label("//mypkg:myrule_validator"))},
test = True,
)
//mypkg/BUILD
:
...
myrule(
name = "mytarget",
)
...
# Needed just once, to expose the template. Could have also used export_files(),
# and made the _script attribute set allow_files=True.
filegroup(
name = "myrule_validator",
srcs = [":myrule_validator.sh.template"],
)
# Needed for each target whose artifacts are to be checked. Notice that you no
# longer have to specify the output file name in a data attribute, or its
# $(location) expansion in an args attribute, or the label for the script
# (unless you want to override it).
myrule_validation_test(
name = "validate_mytarget",
target = ":mytarget",
)
或者,您也可以将模板以字符串形式内嵌到 .bzl 文件中,而不是使用模板扩展操作,并在分析阶段使用 str.format
方法或 %
格式将其展开。
测试 Starlark 实用程序
Skylib 的 unittest.bzl
框架可用于测试实用函数(即既不是宏也不是规则实现的函数)。您可以使用 unittest
代替 unittest.bzl
的 analysistest
库。对于此类测试套件,可以使用便捷函数 unittest.suite()
来减少样板文件。
//mypkg/myhelpers.bzl
:
def myhelper():
return "abc"
//mypkg/myhelpers_test.bzl
:
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load(":myhelpers.bzl", "myhelper")
def _myhelper_test_impl(ctx):
env = unittest.begin(ctx)
asserts.equals(env, "abc", myhelper())
return unittest.end(env)
myhelper_test = unittest.make(_myhelper_test_impl)
# No need for a test_myhelper() setup function.
def myhelpers_test_suite(name):
# unittest.suite() takes care of instantiating the testing rules and creating
# a test_suite.
unittest.suite(
name,
myhelper_test,
# ...
)
//mypkg/BUILD
:
load(":myhelpers_test.bzl", "myhelpers_test_suite")
myhelpers_test_suite(name = "myhelpers_tests")
如需查看更多示例,请参阅 Skylib 自己的测试。