有幾種不同的方法可以在 Bazel 中測試 Starlark 程式碼。本頁依用途收集目前的最佳做法和架構。
測試規則
Skylib 有名為 unittest.bzl
的測試架構,用於檢查規則的分析時間行為,例如規則的動作和提供者。這類測試稱為「分析測試」,目前是測試規則內部運作的最佳選項。
注意事項:
測試宣告會在建構作業中執行,而不是單獨的測試執行器程序。您在測試建立的目標必須命名,以免與其他測試或版本的目標衝突。測試期間發生的錯誤將由 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
物件清單,代表受測試的目標登錄的動作。
驗證不同旗標下的規則行為
建議您根據特定建構旗標,確認實際規則的行為是否符合特定規範。舉例來說,如果使用者指定了下列使用者,規則的運作方式可能會不同:
bazel build //mypkg:real_target -c opt
相較於
bazel build //mypkg:real_target -c dbg
一開始,您可以使用想要的建構標記測試要測試的目標:
bazel test //mypkg:myrules_test -c opt
但是,測試套件不可同時包含測試來驗證 -c opt
下的規則行為,以及另一項可驗證 -c dbg
下規則行為的測試。這兩項測試都不能在同一個版本中執行!
定義測試規則時,您可以指定所需的建構標記來解決這個問題:
myrule_c_opt_test = analysistest.make(
_myrule_c_opt_test_impl,
config_settings = {
"//command_line_option:compilation_mode": "opt",
},
)
通常,系統會根據目前的建構旗標分析受測試的目標。指定 config_settings
會覆寫指定指令列選項的值。(任何未指定的選項都會保留實際指令列中的值)。
在指定的 config_settings
字典中,指令列標記的前面必須加上特殊的預留位置值 //command_line_option:
,如上所示。
驗證構件
檢查產生的檔案是否正確的主要方法如下:
您可以使用殼層、Python 或其他語言編寫測試指令碼,以及建立適當的
*_test
規則類型目標。您可以針對想要執行的測試類型使用專屬規則。
使用測試目標
驗證構件最簡單的方式,就是編寫指令碼,然後在 BUILD 檔案中加入 *_test
目標。您要檢查的特定構件應為此目標的資料依附元件。如果驗證邏輯可供多項測試重複使用,其指令碼應採用由測試目標的 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"],
)
使用自訂規則
比較複雜的替代做法,是將殼層指令碼編寫為範本,以新規則例項化。這涉及到更多間接性和 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.bzl
的 analysistest
程式庫,而是使用 unittest
。對於這類測試套件,便可以使用便利函式 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 專屬的測試。