測試

回報問題 查看來源 夜間 7.2 7.1 7.0 6.5 6.4

在 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 公用程式

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 本身的測試