如何在Bazel编写java测试的扩展规则?

时间:2017-05-28 08:25:31

标签: bazel

我现在想到的是创建AllTest并使用junit运行它。但是,我对此并不满意。我希望这个规则可以创建与在codebase中创建的许多java测试文件一样多的测试。

def junit_suite_test(name, srcs, deps, size="small", resources=[], classpath_resources=[], jvm_flags=[], tags=[], data=[]):
tests = []
package = PACKAGE_NAME.replace("src/test/java/", "").replace("/", ".")
for src in srcs:
  if src.endswith("Test.java"):
    if "/" in src:
       src = package + "." + src.replace("/", ".")
    tests += [src.replace(".java", ".class")]


native.genrule(
name = name + "-AllTests-gen",
outs = ["AllTests.java"],
cmd = """
  cat <<EOF >> $@
package %s;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({%s})
public class AllTests {}
EOF
   """ % (package, ",".join(tests))
)

native.java_test(
  name = name,
  srcs = srcs + ["AllTests.java"],
  test_class = package + ".AllTests",
  resources = resources,
  classpath_resources = classpath_resources,
  data = data,
  size = size,
  tags = tags,
  jvm_flags = jvm_flags,
  deps = deps + [
  ],
)

1 个答案:

答案 0 :(得分:2)

嗨,你可以这样做:

[java_test(name = s[:-5], srcs = s) for s in glob(["*.java"])]

这将在每个java文件的测试目标上创建。

使用该方法,您的宏看起来像:

def junit_suite_test(name, srcs, deps, size="small", resources=[], classpath_resources=[], jvm_flags=[], tags=[], data=[]):
    [native.java_test(
        name = name,
        srcs = src,
        resources = resources,
        classpath_resources = classpath_resources,
        data = data,
        size = size,
        tags = tags,
        jvm_flags = jvm_flags,
        deps = deps,
  ) for src in srcs if src.endswith("Test.java")]

当然,您可能需要进行一些调整以获得良好的资源。

但是,我建议不要对你的解决方案这样做,因为过多的并行性实际上可能会更慢。测试日志和XML文件将报告实际失败的测试用例,您可以使用shard_count来增加并行性。