code: def discover_tests(
      base_dir: Optional[pathlib.Path] = None,
      cpp_tests_dir: Optional[pathlib.Path] = None,
      blocklisted_patterns: Optional[List[str]] = None,
      blocklisted_tests: Optional[List[str]] = None,
      extra_tests: Optional[List[str]] = None,
  ) -> List[str]:
      """
      Searches for all python files starting with test_ excluding one specified by patterns.
      If cpp_tests_dir is provided, also scan for all C++ tests under that directory. They
      are usually found in build/bin
      """
  
      def skip_test_p(name: str) -> bool:
          rc = False
          if blocklisted_patterns is not None:
              rc |= any(
                  name.startswith(pattern)
                  for pattern in blocklisted_patterns
              )
          if blocklisted_tests is not None:
              rc |= name in blocklisted_tests
          return rc
  
      cwd = (
          pathlib.Path(__file__).resolve().parent
          if base_dir is None
          else base_dir
      )
      # This supports symlinks, so we can link domain library tests to PyTorch test directory
      all_py_files = [
          pathlib.Path(p)
          for p in glob.glob(f"{cwd}/**/test_*.py", recursive=True)
      ]
  
      cpp_tests_dir = (
          f"{cwd.parent}/{CPP_TEST_PATH}"
          if cpp_tests_dir is None
          else cpp_tests_dir
      )
      # CPP test files are located under pytorch/build/bin. Unlike Python test, C++ tests
      # are just binaries and could have any name, i.e. basic or atest
      all_cpp_files = [
          pathlib.Path(p)
          for p in glob.glob(f"{cpp_tests_dir}/**/*", recursive=True)
      ]
  
      rc = [str(fname.relative_to(cwd))[:-3] for fname in all_py_files]
      # Add the cpp prefix for C++ tests so that we can tell them apart
      rc.extend(
          [
              parse_test_module(
                  f"{CPP_TEST_PREFIX}/{fname.relative_to(cpp_tests_dir)}"
              )
              for fname in all_cpp_files
          ]
      )
  
      # Invert slashes on Windows
      if sys.platform == "win32":
          rc = [name.replace("\\", "/") for name in rc]
      rc = [test for test in rc if not skip_test_p(test)]
      if extra_tests is not None:
          rc += extra_tests
      return sorted(rc)
  
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 4 for calling a global function with example usage: discover_tests(base_dir, cpp_tests_dir, blocklisted_patterns, blocklisted_tests, extra_tests) and returns: sorted, rc