code: def run_test(
      test_module: ShardedTest,
      test_directory,
      options,
      launcher_cmd=None,
      extra_unittest_args=None,
      env=None,
  ) -> int:
      maybe_set_hip_visible_devies()
      unittest_args = options.additional_unittest_args.copy()
      test_file = test_module.name
      stepcurrent_key = test_file
  
      is_distributed_test = test_file.startswith(
          DISTRIBUTED_TEST_PREFIX
      )
      is_cpp_test = test_file.startswith(CPP_TEST_PREFIX)
      # NB: Rerun disabled tests depends on pytest-flakefinder and it doesn't work with
      # pytest-cpp atm. We also don't have support to disable C++ test yet, so it's ok
      # to just return successfully here
      if is_cpp_test and RERUN_DISABLED_TESTS:
          print_to_stderr(
              "Skipping C++ tests when running under RERUN_DISABLED_TESTS mode"
          )
          return 0
  
      if is_cpp_test:
          stepcurrent_key = f"{test_file}_{os.urandom(8).hex()}"
      else:
          unittest_args.extend(
              [
                  f"--shard-id={test_module.shard - 1}",
                  f"--num-shards={test_module.num_shards}",
              ]
          )
          stepcurrent_key = f"{test_file}_{test_module.shard - 1}_{os.urandom(8).hex()}"
  
      if options.verbose:
          unittest_args.append(
              f'-{"v"*options.verbose}'
          )  # in case of pytest
  
      if test_file in RUN_PARALLEL_BLOCKLIST:
          unittest_args = [
              arg
              for arg in unittest_args
              if not arg.startswith("--run-parallel")
          ]
  
      if extra_unittest_args:
          assert isinstance(extra_unittest_args, list)
          unittest_args.extend(extra_unittest_args)
  
      # If using pytest, replace -f with equivalent -x
      if options.pytest:
          unittest_args.extend(
              get_pytest_args(
                  options,
                  stepcurrent_key,
                  is_cpp_test=is_cpp_test,
                  is_distributed_test=is_distributed_test,
              )
          )
          unittest_args.extend(test_module.get_pytest_args())
          unittest_args = [
              arg if arg != "-f" else "-x" for arg in unittest_args
          ]
  
      # TODO: These features are not available for C++ test yet
      if IS_CI and not is_cpp_test:
          ci_args = ["--import-slow-tests", "--import-disabled-tests"]
          if RERUN_DISABLED_TESTS:
              ci_args.append("--rerun-disabled-tests")
          # use the downloaded test cases configuration, not supported in pytest
          unittest_args.extend(ci_args)
  
      if test_file in PYTEST_SKIP_RETRIES:
          if not options.pytest:
              raise RuntimeError(
                  "A test running without pytest cannot skip retries using "
                  "the PYTEST_SKIP_RETRIES set."
              )
          unittest_args = [
              arg for arg in unittest_args if "--reruns" not in arg
          ]
  
      # Extra arguments are not supported with pytest
      executable = get_executable_command(
          options, is_cpp_test=is_cpp_test
      )
      if not executable:
          # If there is no eligible executable returning here, it means an unsupported
          # case such as coverage for C++ test. So just returning ok makes sense
          return 0
  
      if test_file.startswith(CPP_TEST_PREFIX):
          # C++ tests are not the regular test directory
          if CPP_TESTS_DIR:
              cpp_test = os.path.join(
                  CPP_TESTS_DIR,
                  test_file.replace(f"{CPP_TEST_PREFIX}/", ""),
              )
          else:
              cpp_test = os.path.join(
                  pathlib.Path(test_directory).parent,
                  CPP_TEST_PATH,
                  test_file.replace(f"{CPP_TEST_PREFIX}/", ""),
              )
  
          argv = [
              cpp_test if sys.platform != "win32" else cpp_test + ".exe"
          ] + unittest_args
      else:
          # Can't call `python -m unittest test_*` here because it doesn't run code
          # in `if __name__ == '__main__': `. So call `python test_*.py` instead.
          argv = [test_file + ".py"] + unittest_args
  
      os.makedirs(REPO_ROOT / "test" / "test-reports", exist_ok=True)
      if IS_CI:
          log_fd, log_path = tempfile.mkstemp(
              dir=REPO_ROOT / "test" / "test-reports",
              prefix=f"{sanitize_file_name(str(test_module))}_",
              suffix="_toprint.log",
          )
          os.close(log_fd)
  
      command = (launcher_cmd or []) + executable + argv
      num_retries = (
          0 if "--subprocess" in command or RERUN_DISABLED_TESTS else 2
      )
      is_slow = "slow" in os.environ.get(
          "TEST_CONFIG", ""
      ) or "slow" in os.environ.get("BUILD_ENVRIONMENT", "")
      timeout = (
          THRESHOLD * 6
          if is_slow
          else THRESHOLD * 3
          if num_retries > 0
          and isinstance(test_module, ShardedTest)
          and test_module.time is not None
          else None
      )
      print_to_stderr(f"Executing {command} ... [{datetime.now()}]")
  
      with ExitStack() as stack:
          output = None
          if IS_CI:
              output = stack.enter_context(open(log_path, "w"))
  
          if (
              options.continue_through_error
              and "--subprocess" not in command
          ):
              # I think subprocess is better handled by common_utils? but it's not working atm
              ret_code, was_rerun = run_test_continue_through_error(
                  command,
                  test_directory,
                  env,
                  timeout,
                  stepcurrent_key,
                  output,
              )
          else:
              ret_code, was_rerun = retry_shell(
                  command,
                  test_directory,
                  stdout=output,
                  stderr=output,
                  env=env,
                  timeout=timeout,
                  retries=num_retries,
              )
  
              # Pytest return code 5 means no test is collected. This is needed
              # here as we use pytest directly when running C++ tests. Return
              # code 4 is ok too as this happens when the binary is not a C++
              # test executable. All binary files under build/bin that are not
              # C++ test at the time of this writing have been excluded, but we
              # can accept code 4 too just in case a new non-test binary file
              # comes up in the future.
              ret_code = (
                  0 if ret_code == 5 or ret_code == 4 else ret_code
              )
  
      if IS_CI:
          handle_log_file(
              test_module,
              log_path,
              failed=(ret_code != 0),
              was_rerun=was_rerun,
          )
      return ret_code
  
imports: import argparse
  import copy
  import glob
  import json
  import os
  import pathlib
  import re
  import shutil
  import signal
  import subprocess
  import sys
  import tempfile
  import time
  from collections import defaultdict
  from contextlib import ExitStack
  from datetime import datetime
  from typing import Any, cast, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
  import pkg_resources
  import torch
  import torch.distributed
  from torch.multiprocessing import current_process, get_context
  from torch.testing._internal.common_utils import FILE_SCHEMA, get_report_path, IS_CI, parser, retry_shell, set_cwd, shell, TEST_WITH_ASAN, TEST_WITH_ROCM, TEST_WITH_SLOW_GRADCHECK
  from tools.stats.import_test_stats import ADDITIONAL_CI_FILES_FOLDER, TEST_CLASS_TIMES_FILE, TEST_TIMES_FILE
  from tools.stats.upload_metrics import add_global_metric, emit_metric
  from tools.testing.target_determination.determinator import AggregatedHeuristics, get_prediction_confidences, get_test_prioritizations
  from tools.testing.test_run import TestRun
  from tools.testing.test_selections import calculate_shards, get_test_case_configs, NUM_PROCS, ShardedTest, THRESHOLD
label_desc: Use image node_id 7 for calling a global function with example usage: run_test(test_module, test_directory, options, launcher_cmd, extra_unittest_args, env) and returns: ret_code, int, int