テスト

問題を報告 ソースを表示

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_testprovider_contents_test)という名前にする必要があります。

  • このルールタイプのターゲットのラベルは foo_testprovider_contents_test)にする必要があります。

  • テストルールの実装関数の名前は _foo_test_impl_provider_contents_test_impl)とします。

  • テスト対象のルールのターゲットのラベルとその依存関係には、接頭辞 foo_provider_contents_)を付ける必要があります

すべてのターゲットのラベルは、同じビルド パッケージ内の他のラベルと競合する可能性があるため、テストには一意の名前を付けることをおすすめします。

障害テスト

特定の入力または特定の状態でルールが失敗することを確認すると便利です。これは、分析テスト フレームワークを使用して行うことができます。

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 を使用してパッケージ内のすべてのターゲットをビルドすると、意図的にエラーとなるターゲットのビルドが発生し、ビルドが失敗します。「手動」の場合、テスト対象のターゲットは、明示的に指定された場合、または手動以外のターゲット(テストルールなど)の依存関係としてのみビルドされます。

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 ユーティリティのテスト

Skylibunittest.bzl フレームワークを使用すると、ユーティリティ関数(マクロでもルール実装でもない関数)をテストできます。unittest.bzlanalysistest ライブラリを使用する代わりに、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 独自のテストをご覧ください。