테스트

문제 신고 <ph type="x-smartling-placeholder"></ph> 소스 보기 1박 · 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) 다음 코드 선언, 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 프레임워크로 유틸리티 함수 (즉, 자체 API를 사용할 수 있는 매크로도 규칙 구현도 아님). 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의 자체 테스트를 참고하세요.