binhonglee/GlobeTrotte

View on GitHub
build_defs/npm/vitest.build_defs

Summary

Maintainability
Test Coverage
subinclude("//build_defs/npm")

def vitest_dir(
  name:str,
  srcs:list=[],
  deps:list=[],
  visibility:list=[],
):
  cmd = "zip -r " + name + ".vitest_dir ./"

  return build_rule(
    name = name,
    srcs = srcs,
    cmd = cmd,
    outs = [name + ".vitest_dir"],
    deps = deps,
    test_only = True,
    visibility = visibility
  )

def vitest_tests(
  name:str,
  srcs:list=[],
  vitest_dirs:list=[],
  config:str=CONFIG.VITEST_CONFIG,
  root:str=None,
  deps:list=[],
  visibility:list=[],
  # pnpm complains about  ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL  without first running install
  run_install:bool=False,
):
  test_rules = []

  for src in srcs:
    test = vitest_test(
      name = src[:-8].replace("/", "_"),
      src = src,
      config = config,
      root = root,
      vitest_dirs = vitest_dirs,
      deps = deps,
      visibility = visibility,
      run_install = run_install,
    )
    test_rules += [test]

  return build_rule(
    name = name,
    data = test_rules + srcs,
    test_cmd = "echo 'test'",
    test_only = True,
    visibility = visibility,
    requires = ["npm-test"],
  )

def vitest_test(
  name:str,
  src:str,
  vitest_dirs:list=[],
  config:str=CONFIG.VITEST_CONFIG,
  root:str=None,
  deps:list=[],
  visibility:list=[],
  # pnpm complains about  ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL  without first running install
  run_install:bool=False,
):
  pre_build = _set_node_modules()
  if len(vitest_dirs) > 0:
    pre_build = " && ".join([
      pre_build,
      "; ".join([
        "for z in $(find . -name '*.vitest_dir' -type f)",
        "do unzip -o $z",
        "done",
      ]),
    ])

  if root is not None:
    pre_build += " && cd " + root
  
  if run_install:
    pre_build += " && $TOOLS_NPM i"

  out_dir = _vitest_out_dir(name)
  if CONFIG.CORE_FILES != "":
    deps += [CONFIG.CORE_FILES]

  return build_rule(
    name = name,
    data = [src] + vitest_dirs + deps,
    test_cmd = " && ".join([
      pre_build,
      " ".join([
        _get_npx_tool(),
        "vitest",
        "--coverage",
        "--threads=false",
        "--reporter=junit",
        "--run",
        "$PKG_DIR/" + src,
        "-c",
        "$TOOLS_CONFIG",
      ]),
      "cp vitest_junit test.results",
      "cp vitest_coverage/coverage-final.json test.coverage",
      "mkdir -p " + out_dir,
      "mv vitest_coverage/* " + out_dir,
    ]),
    test_outputs = [out_dir],
    test = True,
    test_only = True,
    test_tools = {
      "config": config,
      "npm": _get_npm_tool(),
    },
    visibility = visibility,
    labels = ['vitest'],
  )

def _vitest_out_dir(name: str):
  return name + "/.nyc_output"

CONFIG.setdefault("VITEST_CONFIG", "vite.config.ts")