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()
ステートメント以外に次の 2 つの主要部分があります。
テスト自体は、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)
また、テスト対象のターゲットに必ず「manual」タグを付けてください。そうしないと、: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
ルールタイプのターゲットを作成できます。テストの種類に固有のルールを使用できます。
テスト ターゲットを使用する
アーティファクトを検証する最も簡単な方法は、スクリプトを作成して *_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"],
)
カスタムルールの使用
より複雑な別の方法として、シェル スクリプトをテンプレートとして記述し、新しいルールによってインスタンス化することもできます。この方法は間接性と 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 独自のテストをご覧ください。