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ルールタイプのターゲットを作成します。実行するテストの種類に特化したルールを使用します。
テストターゲットを使用する
アーティファクトを検証する最も簡単な方法は、スクリプトを作成し、
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's
unittest.bzl
フレームワークを使用して、ユーティリティ関数(つまり、
マクロでもルール実装でもない関数)をテストできます。unittest.bzl's
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 独自の テストをご覧ください。