Skip to content

Java

langadapter.java.adapter

The Java adapter: the public operations for a Java project.

A context names the project's root and its JDK by its java executable (Interpreter.path). The build tool resolves the project once per adapter (project), and every operation runs on that model with the same tools.

JavaAdapter

JavaAdapter(context: ProjectContext, *, executor: Optional[Executor] = None)

Bases: JavaSources

A Java project's adapter.

language class-attribute instance-attribute

language = 'java'

display_name class-attribute instance-attribute

display_name = 'Java'

runtime class-attribute instance-attribute

runtime = 'java'

The program that runs the tests. The project's JDK is the context's.

test_file_name class-attribute instance-attribute

test_file_name = '{stem}Test.java'

scratch_stem class-attribute instance-attribute

scratch_stem = 'Candidate'

A class name, so that a scratch file is CandidateTest.java.

collection_unit class-attribute instance-attribute

collection_unit = COLLECTION_UNIT

validity_policy_version class-attribute instance-attribute

validity_policy_version = VALIDITY_POLICY_VERSION

The version of the generated-test validity policy whose findings analyze_validity reports.

unmatched_evidence_kept class-attribute instance-attribute

unmatched_evidence_kept = False

Per-test evidence leaves out the coverage contexts no reported test claims, a JUnit id naming no test (LanguageFacts.unmatched_evidence_kept).

source_merge_separator class-attribute instance-attribute

source_merge_separator = '//'

native_mutation_engines class-attribute instance-attribute

native_mutation_engines = ('pit',)

mutation_evidence_granularity class-attribute instance-attribute

mutation_evidence_granularity = ('aggregate', 'per_mutant', 'per_test')

test_evidence_granularity class-attribute instance-attribute

test_evidence_granularity = (('run_suite', ('aggregate', 'per_test')), ('run_as_delivered', ('aggregate', 'per_test')), ('benchmark', ('aggregate',)), ('per_test_evidence', ('per_test',)))

file_extensions class-attribute instance-attribute

file_extensions = ('.java',)

source_execution_kinds class-attribute instance-attribute

source_execution_kinds = ('local', 'container')

test_execution_kinds class-attribute instance-attribute

test_execution_kinds = ('local', 'container')

mutation_execution_kinds class-attribute instance-attribute

mutation_execution_kinds = ('local', 'container')

support class-attribute instance-attribute

support = SUPPORT

What the Java adapter supports (LanguageSupport).

own_mutant_timeout_rule class-attribute instance-attribute

own_mutant_timeout_rule = True

project_settings class-attribute instance-attribute

project_settings = (ProjectSetting('java_home', "A Java project's JDK: its home or its java executable. Blank uses JAVA_HOME, except in a container, where it must be named.", 'path', alias='JAVA_HOME', check='a JDK the release supports, read from its release file', host_path='path'), ProjectSetting('build_java_home', "The JDK the build tool runs on when it needs a newer Java than the project's (Gradle 9 runs on Java 17 or newer). Blank uses java_home.", 'path', check='a JDK whose release file names a version', host_path='path'), ProjectSetting('maven', 'The Maven launcher when the project has no Maven wrapper. Blank uses mvn on the path.', 'executable', check='an existing launcher file', host_path='command'), ProjectSetting('gradle', 'The Gradle launcher when the project has no Gradle wrapper. Blank uses gradle on the path.', 'executable', check='an existing launcher file', host_path='command'))

A Java project's settings.

file_rule

file_rule(source: str) -> Optional[str]

The class a Java file is named for: its public top-level class, else its first one. None when it declares none or does not parse.

rename_file_unit

rename_file_unit(source: str, new_name: str) -> Any

The source with its file's class renamed (rename_class): unsupported when unsafe, unchanged without a class or if already named.

test_id_prefix

test_id_prefix(source: str, stem: str) -> str

A test id's start: the file's declared package and class stem.

inspect_project

inspect_project(request)

Read the selected JDK, the build files and the tool cache, running nothing, and report what the project's setup has and lacks.

verify_project

verify_project(request)

In a prepared copy, run the JDK's java and javac version commands and, when a requested operation needs the build, the build's resolution, test compilation and test discovery, and report what the project's setup has and lacks.

project

project() -> Resolution

The project as its build tool resolved it, once. A container JDK probe that could not run is an infrastructure failure.

toolchain_identity

toolchain_identity(platform: Optional[str] = None, junit4: Optional[str] = None) -> ToolchainIdentity

The context's JDK, with the JUnit Platform version platform and the JUnit 4 version junit4 among its tools when they are given.

runtime_version

runtime_version() -> Optional[str]

The context's JDK version, or None when the path is no JDK.

choose_profile

choose_profile() -> JavaProfile

The context JDK's profile, classified against the Java declaration.

test_id_text

test_id_text(test) -> str

A test's dotted id: its class's qualified name, nested classes after dots, and its method.

coverage_texts

coverage_texts(coverage) -> Dict[str, Tuple[Any, ...]]

The covered lines, and per line the untaken branches JaCoCo counts ("line->k of n branches untaken"): its probes name no source branch.

request_options

request_options(purpose: str, *, target: Optional[str] = None, traceback: str = 'short', stop_at_first_failure: bool = False, record_leaks: bool = False, session_seed: Optional[int] = None, reverse_order: bool = False, leave_out_timing_plugins: bool = False) -> Dict[str, Any]

remove_created_files for test, failing-test, evidence and delivered runs, else nothing: JUnit takes no runner options, seed or order, and has no timing plugins to leave out.

delivered_order_refusal

delivered_order_refusal(reverse: bool) -> Optional[str]

Why a reverse order is refused: JUnit orders a class's tests itself.

collection_text

collection_text(run) -> str

"" for a completed collection, else its reason and output tail.

skip_removal

skip_removal(source: str)

The source after strip_module_level_skips and how many it removed.

discover_runtime classmethod

discover_runtime(root, values, *, container=False, environment=None, resolve_path=None)

The JDK of java_home, else (locally) JAVA_HOME, as its java executable. In a container: an absolute POSIX path without backslashes or parent traversal, its bin/java unless it names java. Locally: the path resolve_path gives when that is a file, else the existing java or java.exe in its bin. InvalidRequest names java_home when no JDK is selected or the selection breaks a rule.

describe_runtime classmethod

describe_runtime(root, values, *, container=False, environment=None, resolve_path=None)

The JDK as discover_runtime reads it, without checking that its java exists: no runtime when no JDK is selected. A container selection that breaks a rule is refused as there.

setup_questions classmethod

setup_questions(project_dir, probe, *, consumer='the caller')

The JDK home, then the build tool.

setup_problem classmethod

setup_problem(setting, value, project_dir, probe)

A JDK must name its version, the project's one support does not refuse, and a build tool's launcher must exist. The other settings are checked by their kind.

context_environment classmethod

context_environment(values, *, container=False)

build_java_home, maven and gradle as the variables Java operations read.

mutation_catalogue

mutation_catalogue(config)

pit_mutators: empty for PIT's default mutators, one PIT group (DEFAULTS, REMOVE_CONDITIONALS, REMOVE_SWITCH, RETURNS or STRONGER), or a comma list of mutator names.

import_statement classmethod

import_statement(target: str, root: str) -> str

The import hint for a test of target (none: it declares the named package and uses the classes directly), or "" for an unreadable file.

test_files

test_files(paths) -> List[str]

Each path, a directory replaced by its test files at any depth (_TEST_FILE_PATTERNS).

test_vocabulary

test_vocabulary() -> Dict[str, str]

Java's words for its tests under this project's JUnit version.

language_facts

language_facts() -> LanguageFacts

Java's facts for this project: its JUnit version, read from the resolved test classpath (JUnit 5 when it cannot be read).

capabilities

capabilities() -> CapabilityReport

What this adapter can do for its context: the JDK, the resolved project and the pinned tools' jars, fetched into the cache if missing.

run_suite

run_suite(request: SuiteRunRequest) -> SuiteRun

Run the suite's test files, compiled with the project's JDK for its release against its test classpath, by the JUnit Platform's console launcher with the project's test JVM settings. A coverage_target (a main source file under the project root) is measured with JaCoCo.

collect_suite

collect_suite(request: Any) -> Any

The suite files' tests as JUnit discovers them without running bodies (parameterized methods, factories, not invocations): a collection verdict.

run_as_delivered

run_as_delivered(request: SuiteRunRequest, *, sources: Any = None) -> SuiteRun

Run each declared test file alone with its declared helpers, in JUnit's own lifecycle and order. sources can replace a listed test's text in a private copy. Input files stay unchanged. Session seeding and reverse order are not offered for Java.

benchmark

benchmark(request: Any) -> Any

The Benchmark (BenchmarkRequest) of a suite over repeated runs. Raises InvalidRequest for an invalid request.

benchmark_warmed

benchmark_warmed(request: Any) -> Any

The WarmedSuiteBenchmark (WarmedSuiteBenchmarkRequest): per fork one JVM runs the warm-ups and measured iterations, each Launcher.execute timed. Raises InvalidRequest when invalid.

per_test_evidence

per_test_evidence(request: Any) -> Any

The PerTestEvidence of a green run (PerTestEvidenceRequest): each test method's covered target lines and branches, time, and with a mutation run its kills. Raises InvalidRequest when invalid.

mutation_engines

mutation_engines() -> Tuple[str, ...]

The engines this adapter offers: PIT, its jars fetched into the cache.

mutation_operators

mutation_operators(engine: str = 'pit') -> Any

PIT's default mutators by their reported ids, sorted, as an OperatorCatalogue: missing_setup when PIT cannot be obtained.

open_mutation_session

open_mutation_session(engine: str = 'pit', **options: Any) -> Any

A PIT session for the project. workers are a run's minion threads.

validate_mutation_session_options

validate_mutation_session_options(engine: str, *, workers: int, distributor: Any, allow_fewer_workers: bool, settings: Any) -> None

Refuse a PIT session's distributor, allow_fewer_workers and settings with InvalidRequest: it takes workers only.

execution_setup_issue

execution_setup_issue() -> str

A container run without the helper Python, which Java's runs in a container need, or "".

operation_context_issue

operation_context_issue(name: str) -> str

Why an execution-backed operation cannot run in this context, such as a local context with a container executor or a test framework override, and "" for an operation that runs no tool.

operation_readiness

operation_readiness(name: str, report: CapabilityReport)

An execution-backed operation's readiness from the probe: missing setup without a JDK or a completed project probe, PIT for the operator catalogue, the tree-sitter-java grammar for the source operations, and the probe's capabilities for runs and mutation.

check_structure

check_structure(source: str) -> Any

Whether source parses, with its first error (StructureCheck).

structural_parser_identity

structural_parser_identity() -> str

The structural parser and grammar used by source operations.

test_metrics

test_metrics(source: str) -> Any

A test source's counts (TestMetrics), absent if it does not parse.

skeleton

skeleton(source: str) -> Tuple[str, ...]

Qualified type and method names in source order.

same_skeleton

same_skeleton(first: str, second: str) -> Tuple[bool, str]

Whether sources declare the same types and methods, and why not.

function_fingerprints

function_fingerprints(source: str) -> Dict[str, str]

Static per-method fingerprints, excluding comments.

optimization_metrics

optimization_metrics(source: str) -> Dict[str, Any]

Static structural metrics. These are not execution measurements.

scoped_optimization_metrics

scoped_optimization_metrics(source: str) -> Any

The structural metrics of source per declaration.

call_statistics

call_statistics(source: str) -> Optional[Dict[str, int]]

The call sites of source by called method name, None when it does not parse: the call search of sources.call_statistics.

imports

imports(source: str) -> Tuple[str, ...]

Imported names in source order, none for an unparseable source.

import_path_candidates

import_path_candidates(name: str) -> Tuple[str, ...]

The source path of an imported class, without resolving it.

duplicate_test_names

duplicate_test_names(source: str) -> List[str]

Test methods a class declares twice.

merge_collisions

merge_collisions(first: str, second: str) -> Tuple[str, ...]

Member names two test classes share, without rewriting.

stage_pool

stage_pool(members: Any, *, setup: Any = ()) -> Any

Several suites' files as one StagedPool, types named for their suite.

is_test_file

is_test_file(path: Any) -> bool

Whether path is named as JUnit and the build tools name test files: a .java file ending in Test, Tests, TestCase or IT.

validate_source

validate_source(source: str) -> Any

Whether javac's parser of the project's JDK accepts source at the project's release (SourceValidation).

prune_tests

prune_tests(source: str, tests: Any) -> Any

source without the named tests (SourceResult).

merge_sources

merge_sources(first: str, second: str, *, separator: str) -> Any

Two test classes as one (SourceResult).

normalize_shadowed

normalize_shadowed(source: str) -> Any

source without declarations a class makes twice (SourceResult).

normalize_bindings

normalize_bindings(source: str) -> Any

Static full declaration report, without a JDK or build.

resolve_collisions

resolve_collisions(sources: Any, *, preference: Any = None, localize_autouse: bool = False) -> Any

Collisions among test classes resolved before they merge into the first one's class, as a SourceObservation of a CollisionResolution. Without a preference a conflict is reported and nothing dropped. localize_autouse keeps each source's per-test lifecycle methods on its own tests.

salvage_syntax

salvage_syntax(source: str) -> Any

A bounded repair of a source javac's parser rejects (SourceResult, a generated-suite operation).

prune_unresolvable_imports

prune_unresolvable_imports(source: str) -> Any

source without imports javac cannot resolve on the project's test classpath (SourceResult, a generated-suite operation).

prune_collection_breakers

prune_collection_breakers(source: str, *, timeout_s: float) -> Any

source without the declarations that keep a test class from compiling or initializing (SourceResult, a generated-suite operation).

strip_module_level_skips

strip_module_level_skips(source: str) -> Any

source without the annotations that skip a whole class (SourceResult, a generated-suite operation).

target_identity

target_identity(target: str) -> Any

The TargetIdentity of a file under test, for the validity policy.

analyze_validity

analyze_validity(source: str, target: Any) -> Any

The validity policy's findings on a generated test source (PolicyReport, a generated-suite operation).

screen_source

screen_source(source: str, target: Any) -> Any

The policy's review-only screening signals on a generated test source (PolicyReport, a generated-suite operation).

finalize_source

finalize_source(source: str) -> Any

source without detached comment blocks (SourceResult).

langadapter.java.source_analysis

Static analysis of Java test sources that needs no JDK: the normalization of declarations a class makes twice, the top-level class name, type renames, the static source operations and pooled staging.

A generated source can declare a method signature, a field or a nested type twice (a rewritten test that kept its old version), which Java rejects. The normalization keeps the last declaration, as Python keeps the last binding, and records each removal with the lines removed and kept.

A type rename changes the type's declaration, constructors and every use of its name, as a type or as the qualifier of a call, field access or method or constructor reference. Package and import declarations, strings, method names, annotation element names and labels keep their text. A source that also declares a method, variable, parameter, field or annotation element of the name cannot be renamed safely. rename_class, merge_sources, the merge repair and pooled staging share this rename.

Pooled staging (the adapter's stage_pool operation) appends its suite's slot to every top-level type a suite declares, since suites usually declare the same test class in one package. Uses in the suite's files follow, and each file takes its public class's new name. Strings and package and import declarations keep the old names, so a test that reads its own class name or statically imports its own class's member can differ or fail to compile in the pool. self_references lists such references per staged file.

RULE_VERSION module-attribute

RULE_VERSION = 'java-last-declaration-v1'

The rule normalize_shadowed_definitions applies, which its records name.

normalize_shadowed_definitions

normalize_shadowed_definitions(source: str) -> SuiteNormalization

source without the earlier of two declarations a class makes twice. Unchanged, with the error, when tree-sitter cannot parse it. A field declaration of several variables is left to the compiler.

top_class_name

top_class_name(source: str) -> str

The public top-level class's name, else the first's, or "" (none, unparsable).

rename_class

rename_class(source: str, old: str, new: str) -> SourceObservation

source with the type old renamed to new (the module's type rename) as a completed observation, for example to match a copied class to its file name. parse_error when it does not parse, unsupported with the reason when the rename is unsafe.

static_operations

static_operations() -> Any

The source operations that need no JDK and no project: structure check, test metrics, skeletons, fingerprints, optimization metrics, imports, duplicate names, merge collisions, test-file names, pruning and finalization. The others judge or compile a source: a JavaAdapter.