From c1ed1925b8f282b9759a579dce60d497f0140258 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:10:17 +0000 Subject: [PATCH 01/12] test: split processor tests into the modules they cover (#390) Move every test that exercises a shared codegen module into that module so each module proves its behavior with tests in its own tree: - simple-processor: JavaLangAnalyserTest, OptionValueParsersTest, CodegenProcessorConfigurationTest, ProcessorOptionRegistryTest, ElementCollectorTest and MinimalCodegenProcessorTest (now compiling against CodegenTestUtils directly), plus new JavaLangMapperTest and FieldAnnotationExtractorTest driving a probe processor - codegen-core: ActivePerformanceTrackerTest (with a local capturing logger, as codegen-testing would be a dependency cycle), plus new SinkProcessingLoggerTest, CodegenEnumsTest and ImportCollectorTest; jackson-databind added as test-scoped dep for the tracker's JSON assertions - codegen-testing: FormatterProfileTestUtilsTest plus new tests for CapturingProcessingLogger, CodegenTestUtils, ProcessingEnvironmentStub and ProcessorAsserts; a minimal eclipse-java-format.xml test resource stands in for the bundled codegen-roaster profile - codegen-roaster: RoasterCodeGeneratorResilienceTest rebuilt on a GenerationEnvironment stub of codegen-core types, plus new RoasterCodeGeneratorTest asserting whole generated sources against generic DTOs processor no longer depends on codegen-roaster: the only main-code mention was a javadoc reference, now kept as plain text. Each module's metrics profile reports coverage from its own tests alone (e.g. codegen-core 91% lines, processor 98%). --- codegen-core/pom.xml | 8 + .../codegen/enums/CodegenEnumsTest.java | 61 +++++ .../logging/ActivePerformanceTrackerTest.java | 201 +++++++++------ .../logging/SinkProcessingLoggerTest.java | 110 ++++++++ .../codegen/util/ImportCollectorTest.java | 97 ++++++++ .../RoasterCodeGeneratorResilienceTest.java | 67 ++--- .../roaster/RoasterCodeGeneratorTest.java | 190 ++++++++++++++ .../CapturingProcessingLoggerTest.java | 73 ++++++ .../codegen/testing/CodegenTestUtilsTest.java | 140 +++++++++++ .../FormatterProfileTestUtilsTest.java | 3 +- .../ProcessingEnvironmentStubTest.java | 57 +++++ .../codegen/testing/ProcessorAssertsTest.java | 83 +++++++ .../test/resources/eclipse-java-format.xml | 7 + processor/pom.xml | 5 - .../processing/BuilderDefinitionCreator.java | 4 +- .../FieldAnnotationExtractorTest.java | 235 ++++++++++++++++++ .../analysis}/JavaLangAnalyserTest.java | 3 +- .../codegen/analysis/JavaLangMapperTest.java | 207 +++++++++++++++ .../CodegenProcessorConfigurationTest.java | 0 .../processing/ElementCollectorTest.java | 0 .../MinimalCodegenProcessorTest.java | 8 +- .../processing/OptionValueParsersTest.java | 3 +- .../ProcessorOptionRegistryTest.java | 0 23 files changed, 1441 insertions(+), 121 deletions(-) create mode 100644 codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java rename {processor => codegen-core}/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java (74%) create mode 100644 codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java create mode 100644 codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java rename {processor/src/test/java/org/javahelpers/simple/builders/processor => codegen-roaster/src/test/java/org/javahelpers/codegen/roaster}/RoasterCodeGeneratorResilienceTest.java (78%) create mode 100644 codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java create mode 100644 codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java create mode 100644 codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java rename {processor/src/test/java/org/javahelpers/simple/builders/processor => codegen-testing/src/test/java/org/javahelpers/codegen}/testing/FormatterProfileTestUtilsTest.java (95%) create mode 100644 codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java create mode 100644 codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java create mode 100644 codegen-testing/src/test/resources/eclipse-java-format.xml create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java rename {processor/src/test/java/org/javahelpers/simple/builders/processor => simple-processor/src/test/java/org/javahelpers/codegen/analysis}/JavaLangAnalyserTest.java (98%) create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java rename {processor => simple-processor}/src/test/java/org/javahelpers/codegen/processing/CodegenProcessorConfigurationTest.java (100%) rename {processor => simple-processor}/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java (100%) rename {processor => simple-processor}/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java (96%) rename {processor/src/test/java/org/javahelpers/simple/builders/processor => simple-processor/src/test/java/org/javahelpers/codegen}/processing/OptionValueParsersTest.java (97%) rename {processor => simple-processor}/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java (100%) diff --git a/codegen-core/pom.xml b/codegen-core/pom.xml index 0172278c..6c4b5550 100644 --- a/codegen-core/pom.xml +++ b/codegen-core/pom.xml @@ -122,6 +122,14 @@ test + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind.version} + test + + diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java new file mode 100644 index 00000000..3d95d67f --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java @@ -0,0 +1,61 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.enums; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** Unit tests for the codegen enums' value mappings and parsing. */ +class CodegenEnumsTest { + + @Test + void accessModifier_mapsToJavaKeyword() { + assertEquals("public", AccessModifier.DEFAULT.getJavaKeyword()); + assertEquals("public", AccessModifier.PUBLIC.getJavaKeyword()); + assertEquals("protected", AccessModifier.PROTECTED.getJavaKeyword()); + assertEquals("", AccessModifier.PACKAGE_PRIVATE.getJavaKeyword()); + assertEquals("private", AccessModifier.PRIVATE.getJavaKeyword()); + } + + @Test + void formattingMode_optionValuesAndParsing() { + assertEquals("jdt", FormattingMode.JDT.getOptionValue()); + assertEquals("lightweight", FormattingMode.LIGHTWEIGHT.getOptionValue()); + assertEquals("none", FormattingMode.NONE.getOptionValue()); + + assertEquals(FormattingMode.NONE, FormattingMode.fromString("none")); + assertEquals(FormattingMode.LIGHTWEIGHT, FormattingMode.fromString("LightWeight")); + assertEquals(FormattingMode.JDT, FormattingMode.fromString(null)); + assertEquals(FormattingMode.JDT, FormattingMode.fromString("unknown")); + } + + @Test + void optionState_hasTriStateValues() { + assertEquals( + java.util.Set.of(OptionState.UNSET, OptionState.ENABLED, OptionState.DISABLED), + java.util.Set.of(OptionState.values())); + } +} diff --git a/processor/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java similarity index 74% rename from processor/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java rename to codegen-core/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java index 46be9e84..2f08135b 100644 --- a/processor/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java +++ b/codegen-core/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java @@ -24,6 +24,7 @@ package org.javahelpers.codegen.logging; +import static org.javahelpers.codegen.GenerationPhases.*; import static org.junit.jupiter.api.Assertions.*; import com.fasterxml.jackson.databind.JsonNode; @@ -31,11 +32,12 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Set; import org.javahelpers.codegen.GenerationPhases; -import org.javahelpers.codegen.processing.PipelinePhases; -import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -44,18 +46,79 @@ * *

Tests cover phase tracking, generator/enhancer tracking, class metrics, JSON report output * structure and correctness, edge cases, and ThreadLocal cleanup. + * + *

codegen-core cannot depend on codegen-testing (dependency cycle), so the capturing logger and + * the phase vocabulary are defined locally instead of reusing {@code CapturingLogger} and {@code + * PipelinePhases}. */ class ActivePerformanceTrackerTest { @TempDir Path tempDir; + private static final String PHASE_ELEMENT_COLLECTION = "Element Collection"; + private static final String PHASE_CONFIGURATION_RESOLUTION = "Configuration Resolution"; + private static final String PHASE_ANALYSIS = "Analysis"; + private static final String PHASE_TARGET_MAPPING = "Target Mapping"; + private static final String PHASE_CODE_GENERATION = "Code Generation"; + + /** Phase hierarchy rendered in the report, mirroring a typical processing pipeline. */ + private static final PhaseHierarchy TEST_HIERARCHY = + new PhaseHierarchy( + List.of( + PHASE_ELEMENT_COLLECTION, + PHASE_CONFIGURATION_RESOLUTION, + PHASE_ANALYSIS, + PHASE_TARGET_MAPPING, + PHASE_CODE_GENERATION), + Map.of( + PHASE_CODE_GENERATION, + List.of(PHASE_SOURCE_CONSTRUCTION, PHASE_FILE_WRITING), + PHASE_SOURCE_CONSTRUCTION, + List.of(PHASE_ELEMENT_BUILDING, PHASE_STRING_GENERATION, PHASE_FORMATTING), + PHASE_ELEMENT_BUILDING, + List.of( + PHASE_CLASS_CREATION, + PHASE_CLASS_METADATA, + PHASE_FIELDS, + PHASE_CONSTRUCTORS, + PHASE_METHODS, + PHASE_NESTED_TYPES, + PHASE_CLASS_ANNOTATIONS))); + + /** Minimal capturing logger equivalent to codegen-testing's {@code CapturingLogger}. */ + private static final class CapturingLogger { + private final List messages = new ArrayList<>(); + private final ProcessingLogger logger; + + private CapturingLogger(String loggingPrefix) { + logger = + new SinkProcessingLogger( + (severity, message) -> messages.add(severity + ": " + message), false, loggingPrefix); + } + + private static CapturingLogger create() { + return new CapturingLogger(null); + } + + private static CapturingLogger create(String loggingPrefix) { + return new CapturingLogger(loggingPrefix); + } + + private ProcessingLogger logger() { + return logger; + } + + private List messages() { + return messages; + } + } + /** Helper to create a tracker, track some data, and generate report with JSON output. */ private JsonNode generateReportAndParseJson(String outputFile) throws IOException { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(outputFile, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(outputFile, TEST_HIERARCHY); tracker.startClass("TestClassA"); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_ANALYSIS); + tracker.endPhase(PHASE_ANALYSIS); tracker.startGenerator(); tracker.endGenerator("FieldSupplierGenerator"); tracker.startEnhancer(); @@ -64,10 +127,10 @@ private JsonNode generateReportAndParseJson(String outputFile) throws IOExceptio tracker.startClass("TestClassB"); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_TARGET_MAPPING); + tracker.endPhase(PHASE_TARGET_MAPPING); tracker.endClass(3, 1); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -111,18 +174,17 @@ private static JsonNode classMetricByName(JsonNode root, String className) { */ @Test void generateReport_prefixedLogger_producesExpectedTaggedLayout() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_ANALYSIS); + tracker.endPhase(PHASE_ANALYSIS); tracker.startGenerator(); tracker.endGenerator("MyGenerator"); tracker.startEnhancer(); tracker.endEnhancer("MyEnhancer"); tracker.endClass(5, 2); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create("simple-builders"); + CapturingLogger capturing = CapturingLogger.create("simple-builders"); tracker.generateReport(capturing.logger()); // Remove the diagnostic kind marker and the exact measurements (durations, percentages, @@ -179,9 +241,8 @@ void generateReport_prefixedLogger_producesExpectedTaggedLayout() { @Test void generateReport_withNoData_logsBasicReport() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -193,12 +254,11 @@ void generateReport_withNoData_logsBasicReport() { @Test void generateReport_withClassData_logsClassCount() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.endClass(4, 1); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -209,14 +269,13 @@ void generateReport_withClassData_logsClassCount() { @Test void generateReport_withGeneratorData_logsGeneratorStats() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.startGenerator(); tracker.endGenerator("MyGenerator"); tracker.endClass(2, 0); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -226,14 +285,13 @@ void generateReport_withGeneratorData_logsGeneratorStats() { @Test void generateReport_withEnhancerData_logsEnhancerStats() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.startEnhancer(); tracker.endEnhancer("MyEnhancer"); tracker.endClass(2, 0); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -243,61 +301,55 @@ void generateReport_withEnhancerData_logsEnhancerStats() { @Test void generateReport_withPhaseData_logsPhaseBreakdown() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_CONFIGURATION_RESOLUTION); + tracker.endPhase(PHASE_CONFIGURATION_RESOLUTION); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_CODE_GENERATION); + tracker.endPhase(PHASE_CODE_GENERATION); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); assertTrue(capturing.messages().stream().anyMatch(m -> m.contains("Phase breakdown"))); assertTrue( - capturing.messages().stream() - .anyMatch(m -> m.contains(PipelinePhases.PHASE_CONFIGURATION_RESOLUTION))); - assertTrue( - capturing.messages().stream() - .anyMatch(m -> m.contains(PipelinePhases.PHASE_CODE_GENERATION))); + capturing.messages().stream().anyMatch(m -> m.contains(PHASE_CONFIGURATION_RESOLUTION))); + assertTrue(capturing.messages().stream().anyMatch(m -> m.contains(PHASE_CODE_GENERATION))); } @Test void generateReport_withElementCollectionPhase_logsPhaseInReport() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_ELEMENT_COLLECTION); + tracker.endPhase(PHASE_ELEMENT_COLLECTION); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); assertTrue( - capturing.messages().stream() - .anyMatch(m -> m.contains(PipelinePhases.PHASE_ELEMENT_COLLECTION)), - "Text report should contain " + PipelinePhases.PHASE_ELEMENT_COLLECTION); + capturing.messages().stream().anyMatch(m -> m.contains(PHASE_ELEMENT_COLLECTION)), + "Text report should contain " + PHASE_ELEMENT_COLLECTION); } @Test void jsonReport_phaseBreakdown_containsElementCollectionPhase() throws IOException { Path jsonFile = tempDir.resolve("report-element-collection.json"); ActivePerformanceTracker tracker = - new ActivePerformanceTracker(jsonFile.toString(), PipelinePhases.PIPELINE_HIERARCHY); + new ActivePerformanceTracker(jsonFile.toString(), TEST_HIERARCHY); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_ELEMENT_COLLECTION); + tracker.endPhase(PHASE_ELEMENT_COLLECTION); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); JsonNode root = new ObjectMapper().readTree(Files.readString(jsonFile)); JsonNode phases = root.get("phaseBreakdown"); assertTrue( - phases.has(PipelinePhases.PHASE_ELEMENT_COLLECTION), - "JSON phaseBreakdown should contain " + PipelinePhases.PHASE_ELEMENT_COLLECTION); - JsonNode elementCollection = phases.get(PipelinePhases.PHASE_ELEMENT_COLLECTION); + phases.has(PHASE_ELEMENT_COLLECTION), + "JSON phaseBreakdown should contain " + PHASE_ELEMENT_COLLECTION); + JsonNode elementCollection = phases.get(PHASE_ELEMENT_COLLECTION); assertTrue(elementCollection.has("elapsedNanos")); assertTrue(elementCollection.has("elapsedSeconds")); assertTrue(elementCollection.has("percentage")); @@ -305,12 +357,11 @@ void jsonReport_phaseBreakdown_containsElementCollectionPhase() throws IOExcepti @Test void generateReport_withNullOutputFile_doesNotWriteFile() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.endClass(1, 0); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -386,12 +437,12 @@ void jsonReport_phaseBreakdown_containsPhaseHierarchy() throws IOException { JsonNode root = generateReportAndParseJson(jsonFile.toString()); JsonNode phases = root.get("phaseBreakdown"); - assertTrue(phases.has(PipelinePhases.PHASE_CONFIGURATION_RESOLUTION)); - assertTrue(phases.has(PipelinePhases.PHASE_ANALYSIS)); - assertTrue(phases.has(PipelinePhases.PHASE_TARGET_MAPPING)); - assertTrue(phases.has(PipelinePhases.PHASE_CODE_GENERATION)); + assertTrue(phases.has(PHASE_CONFIGURATION_RESOLUTION)); + assertTrue(phases.has(PHASE_ANALYSIS)); + assertTrue(phases.has(PHASE_TARGET_MAPPING)); + assertTrue(phases.has(PHASE_CODE_GENERATION)); - JsonNode codeGen = phases.get(PipelinePhases.PHASE_CODE_GENERATION); + JsonNode codeGen = phases.get(PHASE_CODE_GENERATION); assertTrue(codeGen.has("elapsedNanos")); assertTrue(codeGen.has("elapsedSeconds")); assertTrue(codeGen.has("percentage")); @@ -402,7 +453,7 @@ void jsonReport_phaseBreakdown_codeGenerationHasChildren() throws IOException { Path jsonFile = tempDir.resolve("report.json"); JsonNode root = generateReportAndParseJson(jsonFile.toString()); - JsonNode codeGen = root.get("phaseBreakdown").get(PipelinePhases.PHASE_CODE_GENERATION); + JsonNode codeGen = root.get("phaseBreakdown").get(PHASE_CODE_GENERATION); assertTrue(codeGen.has("children")); JsonNode children = codeGen.get("children"); assertTrue(children.has(GenerationPhases.PHASE_SOURCE_CONSTRUCTION)); @@ -413,9 +464,9 @@ void jsonReport_phaseBreakdown_codeGenerationHasChildren() throws IOException { void jsonReport_withNoData_hasEmptyArrays() throws IOException { Path jsonFile = tempDir.resolve("report-empty.json"); ActivePerformanceTracker tracker = - new ActivePerformanceTracker(jsonFile.toString(), PipelinePhases.PIPELINE_HIERARCHY); + new ActivePerformanceTracker(jsonFile.toString(), TEST_HIERARCHY); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -440,14 +491,13 @@ void jsonReport_createsParentDirectoriesIfMissing() throws IOException { @Test void endMethodsWithoutStart_doesNothing() { - ActivePerformanceTracker tracker = - new ActivePerformanceTracker(null, PipelinePhases.PIPELINE_HIERARCHY); - tracker.endPhase(PipelinePhases.PHASE_CONFIGURATION_RESOLUTION); + ActivePerformanceTracker tracker = new ActivePerformanceTracker(null, TEST_HIERARCHY); + tracker.endPhase(PHASE_CONFIGURATION_RESOLUTION); tracker.endGenerator("NonexistentGenerator"); tracker.endEnhancer("NonexistentEnhancer"); tracker.endClass(5, 2); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -462,7 +512,7 @@ void endMethodsWithoutStart_doesNothing() { void multipleGenerators_accumulateTimeAndCalls() throws IOException { Path jsonFile = tempDir.resolve("report-multi-gen.json"); ActivePerformanceTracker tracker = - new ActivePerformanceTracker(jsonFile.toString(), PipelinePhases.PIPELINE_HIERARCHY); + new ActivePerformanceTracker(jsonFile.toString(), TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.startGenerator(); tracker.endGenerator("GenA"); @@ -472,7 +522,7 @@ void multipleGenerators_accumulateTimeAndCalls() throws IOException { tracker.endGenerator("GenB"); tracker.endClass(2, 0); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -488,7 +538,7 @@ void multipleGenerators_accumulateTimeAndCalls() throws IOException { void jsonReport_escapesSpecialCharactersInNames() throws IOException { Path jsonFile = tempDir.resolve("report-escaping.json"); ActivePerformanceTracker tracker = - new ActivePerformanceTracker(jsonFile.toString(), PipelinePhases.PIPELINE_HIERARCHY); + new ActivePerformanceTracker(jsonFile.toString(), TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.startGenerator(); tracker.endGenerator("Gen\"\\\n\t\r\b\fA\u0001"); @@ -497,7 +547,7 @@ void jsonReport_escapesSpecialCharactersInNames() throws IOException { tracker.endEnhancer("Enh\u0001x"); tracker.endClass(2, 0); - tracker.generateReport(CapturingProcessingLogger.create().logger()); + tracker.generateReport(CapturingLogger.create().logger()); JsonNode root = new ObjectMapper().readTree(Files.readString(jsonFile)); JsonNode genStats = root.get("generatorStats"); @@ -510,30 +560,29 @@ void jsonReport_escapesSpecialCharactersInNames() throws IOException { void multiplePhases_accumulateTime() throws IOException { Path jsonFile = tempDir.resolve("report-multi-phase.json"); ActivePerformanceTracker tracker = - new ActivePerformanceTracker(jsonFile.toString(), PipelinePhases.PIPELINE_HIERARCHY); + new ActivePerformanceTracker(jsonFile.toString(), TEST_HIERARCHY); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_CONFIGURATION_RESOLUTION); + tracker.endPhase(PHASE_CONFIGURATION_RESOLUTION); tracker.startPhase(); - tracker.endPhase(PipelinePhases.PHASE_CONFIGURATION_RESOLUTION); + tracker.endPhase(PHASE_CONFIGURATION_RESOLUTION); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); JsonNode root = new ObjectMapper().readTree(Files.readString(jsonFile)); - JsonNode phase = root.get("phaseBreakdown").get(PipelinePhases.PHASE_CONFIGURATION_RESOLUTION); + JsonNode phase = root.get("phaseBreakdown").get(PHASE_CONFIGURATION_RESOLUTION); assertTrue(phase.get("elapsedNanos").asLong() > 0); } @Test void generateReport_logsWarningOnInvalidPath() { ActivePerformanceTracker tracker = - new ActivePerformanceTracker( - "/nonexistent\0invalid/path.json", PipelinePhases.PIPELINE_HIERARCHY); + new ActivePerformanceTracker("/nonexistent\0invalid/path.json", TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.endClass(1, 0); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); @@ -545,7 +594,7 @@ void generateReport_logsWarningOnInvalidPath() { @Test void noOpPerformanceTracker_allMethodsAreNoOps() { NoOpPerformanceTracker tracker = new NoOpPerformanceTracker(); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.startPhase(); @@ -565,7 +614,7 @@ void noOpPerformanceTracker_allMethodsAreNoOps() { void jsonReport_generatorAndEnhancerStats_sortedByElapsedDesc() throws IOException { Path jsonFile = tempDir.resolve("report-sorted.json"); ActivePerformanceTracker tracker = - new ActivePerformanceTracker(jsonFile.toString(), PipelinePhases.PIPELINE_HIERARCHY); + new ActivePerformanceTracker(jsonFile.toString(), TEST_HIERARCHY); tracker.startClass("MyClass"); tracker.startGenerator(); tracker.endGenerator("SlowGen"); @@ -577,7 +626,7 @@ void jsonReport_generatorAndEnhancerStats_sortedByElapsedDesc() throws IOExcepti tracker.endEnhancer("FastEnh"); tracker.endClass(2, 0); - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingLogger capturing = CapturingLogger.create(); ProcessingLogger logger = capturing.logger(); tracker.generateReport(logger); diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java new file mode 100644 index 00000000..9a766f96 --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java @@ -0,0 +1,110 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.logging; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link SinkProcessingLogger} — flat vs. hierarchical emission to a sink. */ +class SinkProcessingLoggerTest { + + @Test + void nonVerbose_emitsFlatPrefixedMessages() { + List messages = new ArrayList<>(); + SinkProcessingLogger logger = + new SinkProcessingLogger((sev, msg) -> messages.add(sev + ": " + msg), false, "test"); + + logger.info("hello %s", "world"); + logger.warning("careful"); + logger.error("boom"); + logger.debug("hidden"); + + assertEquals( + List.of("NOTE: test: hello world", "WARNING: test: careful", "ERROR: test: boom"), + messages); + } + + @Test + void verbose_debugCarriesDebugPrefixAndTreeMarker() { + List messages = new ArrayList<>(); + SinkProcessingLogger logger = + new SinkProcessingLogger((sev, msg) -> messages.add(sev + ": " + msg), true, "test"); + + logger.debug("flat detail"); + logger.debugStartOperation("outer op"); + logger.debug("nested detail"); + logger.debugEndOperation("outer done"); + logger.debug("flat again"); + + assertEquals( + List.of( + "OTHER: [DEBUG] test: flat detail", + "NOTE: [DEBUG] test: outer op", + "OTHER: [DEBUG] test: ├─ nested detail", + "NOTE: [DEBUG] test: └─ outer done", + "OTHER: [DEBUG] test: flat again"), + messages); + } + + @Test + void verbose_warningAtNestedLevelGetsHierarchicalIndent() { + List messages = new ArrayList<>(); + SinkProcessingLogger logger = + new SinkProcessingLogger((sev, msg) -> messages.add(sev + ": " + msg), true, "test"); + + logger.debugStartOperation("op"); + logger.warning("at level one"); + + assertEquals( + List.of("NOTE: [DEBUG] test: op", "WARNING: test: └─ at level one"), messages); + } + + @Test + void noPrefix_leavesMessageUnchanged() { + List messages = new ArrayList<>(); + SinkProcessingLogger logger = + new SinkProcessingLogger((sev, msg) -> messages.add(msg), false, null); + + logger.info("plain"); + + assertEquals(List.of("plain"), messages); + } + + @Test + void resetIndentation_returnsToLevelZero() { + List messages = new ArrayList<>(); + SinkProcessingLogger logger = + new SinkProcessingLogger((sev, msg) -> messages.add(msg), true, null); + + logger.debugStartOperation("op"); + assertTrue(logger.getCurrentIndentationLevel() > 0); + logger.resetIndentation(); + assertEquals(0, logger.getCurrentIndentationLevel()); + } +} diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java new file mode 100644 index 00000000..56e628fe --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java @@ -0,0 +1,97 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.imports.ImportStatement; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.type.TypeName; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link ImportCollector}: skip rules, generic args and sort order. */ +class ImportCollectorTest { + + private static List fqns(GenerationTargetClassDto classDef) { + return ImportCollector.collectAndSortImports(classDef).stream() + .map(ImportStatement::getFullyQualifiedName) + .toList(); + } + + private static GenerationTargetClassDto classDef(String pkg, String name) { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName(pkg, name)); + return classDef; + } + + private static ClassFieldDto field(String name, String pkg, String type) { + ClassFieldDto field = new ClassFieldDto(); + field.setFieldName(name); + field.setFieldType(new TypeName(pkg, type)); + return field; + } + + @Test + void skipsJavaLangAndSamePackageTypes() { + GenerationTargetClassDto classDef = classDef("com.example", "Dto"); + classDef.addClassField(field("samePackage", "com.example", "Sibling")); + classDef.addClassField(field("langType", "java.lang", "String")); + classDef.addClassField(field("needed", "java.util", "Optional")); + + assertEquals(List.of("java.util.Optional"), fqns(classDef)); + } + + @Test + void importsSortedAlphabetically() { + GenerationTargetClassDto classDef = classDef("com.example", "Dto"); + classDef.addClassField(field("z", "java.util", "TreeSet")); + classDef.addClassField(field("a", "java.util", "ArrayDeque")); + classDef.addClassField(field("m", "java.time", "Instant")); + + assertEquals( + List.of("java.time.Instant", "java.util.ArrayDeque", "java.util.TreeSet"), fqns(classDef)); + } + + @Test + void genericTypeImportsRawTypeAndArguments() { + GenerationTargetClassDto classDef = classDef("com.example", "Dto"); + classDef.addClassField(field("mapping", "com.example", "StringIntegerMap")); + + MethodDto method = new MethodDto("values", new TypeName("java.util", "Collection")); + MethodParameterDto param = new MethodParameterDto(); + param.setParameterName("key"); + param.setParameterTypeName(new TypeName("com.other", "KeyDto")); + method.addParameter(param); + classDef.addMethod(method); + + assertTrue(fqns(classDef).contains("java.util.Collection")); + assertTrue(fqns(classDef).contains("com.other.KeyDto")); + } +} diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/RoasterCodeGeneratorResilienceTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java similarity index 78% rename from processor/src/test/java/org/javahelpers/simple/builders/processor/RoasterCodeGeneratorResilienceTest.java rename to codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java index 7fa0ceb4..e681bbed 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/RoasterCodeGeneratorResilienceTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java @@ -22,16 +22,20 @@ * SOFTWARE. */ -package org.javahelpers.simple.builders.processor; +package org.javahelpers.codegen.roaster; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; -import javax.annotation.processing.ProcessingEnvironment; import org.javahelpers.codegen.CodeGenerationException; +import org.javahelpers.codegen.GeneratedSourceFile; +import org.javahelpers.codegen.GenerationEnvironment; +import org.javahelpers.codegen.GenerationIssueReporter; import org.javahelpers.codegen.SourceFormatter; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.logging.NoOpPerformanceTracker; +import org.javahelpers.codegen.logging.PerformanceTracker; import org.javahelpers.codegen.logging.ProcessingLogger; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; import org.javahelpers.codegen.model.method.ConstructorDto; @@ -40,15 +44,8 @@ import org.javahelpers.codegen.model.method.MethodDto; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.TypeName; -import org.javahelpers.codegen.processing.AnnotationProcessingEnvironment; -import org.javahelpers.codegen.processing.logging.MessagerProcessingLogger; -import org.javahelpers.codegen.roaster.RoasterCodeGenerator; -import org.javahelpers.codegen.roaster.RoasterSourceFormatter; import org.javahelpers.codegen.roaster.exceptions.RoasterMapperException; import org.javahelpers.codegen.testing.CapturingProcessingLogger; -import org.javahelpers.codegen.testing.ProcessingEnvironmentStub; -import org.javahelpers.simple.builders.processor.model.core.BuilderConfiguration; -import org.javahelpers.simple.builders.processor.processing.BuilderProcessingContext; import org.junit.jupiter.api.Test; /** @@ -62,6 +59,35 @@ */ class RoasterCodeGeneratorResilienceTest { + /** + * Minimal {@link GenerationEnvironment} built only from codegen-core types: issues surface on the + * logger as warnings, timing is not tracked, and {@code createSourceFile} returns {@code null} so + * the file-write step fails deterministically on it. + */ + private static GenerationEnvironment stubEnvironment(ProcessingLogger logger) { + return new GenerationEnvironment() { + @Override + public ProcessingLogger getLogger() { + return logger; + } + + @Override + public PerformanceTracker getPerformanceTracker() { + return new NoOpPerformanceTracker(); + } + + @Override + public GenerationIssueReporter getIssueReporter() { + return logger::warning; + } + + @Override + public GeneratedSourceFile createSourceFile(CharSequence qualifiedName) { + return null; + } + }; + } + /** Placeholder subtype the mapper does not know how to render, forcing a mapping failure. */ private static final class UnsupportedPlaceholder extends MethodCodePlaceholder { private UnsupportedPlaceholder(String label, String value) { @@ -84,14 +110,8 @@ void shouldWrapRenderingRuntimeExceptionInCodeGenerationException() { constructor.setMethodCodeDto(code); classDef.addConstructor(constructor); - ProcessingEnvironment env = ProcessingEnvironmentStub.createEmpty(); - ProcessingLogger logger = MessagerProcessingLogger.create(env); - BuilderProcessingContext context = - new BuilderProcessingContext(logger, BuilderConfiguration.DEFAULT, env); - RoasterCodeGenerator generator = - new RoasterCodeGenerator( - new AnnotationProcessingEnvironment( - env, logger, context.getPerformanceTracker(), context::reportBasedOnStrictMode)); + ProcessingLogger logger = CapturingProcessingLogger.create().logger(); + RoasterCodeGenerator generator = new RoasterCodeGenerator(stubEnvironment(logger)); SourceFormatter formatter = new RoasterSourceFormatter(logger, FormattingMode.NONE); CodeGenerationException thrown = @@ -117,19 +137,10 @@ void shouldKeepFirstMethodAndWarnOnDuplicateSignature() { classDef.addMethod(duplicateSignatureMethod("second")); CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); - ProcessingEnvironment env = ProcessingEnvironmentStub.createEmpty(); - BuilderProcessingContext context = - new BuilderProcessingContext(capturing.logger(), BuilderConfiguration.DEFAULT, env); - RoasterCodeGenerator generator = - new RoasterCodeGenerator( - new AnnotationProcessingEnvironment( - env, - capturing.logger(), - context.getPerformanceTracker(), - context::reportBasedOnStrictMode)); + RoasterCodeGenerator generator = new RoasterCodeGenerator(stubEnvironment(capturing.logger())); SourceFormatter formatter = new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE); - // generation itself succeeds; only the file-write step fails on the stub's null filer + // generation itself succeeds; only the file-write step fails on the stub's null source file assertThrows(NullPointerException.class, () -> generator.generateClass(classDef, formatter)); capturing.assertMessage( "WARNING: Unexpected duplicate method signature: 'name(java.lang.String)'" diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java new file mode 100644 index 00000000..aee5a54a --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -0,0 +1,190 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.roaster; + +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; + +import java.io.StringWriter; +import java.io.Writer; +import java.net.URI; +import org.javahelpers.codegen.GeneratedSourceFile; +import org.javahelpers.codegen.GenerationEnvironment; +import org.javahelpers.codegen.GenerationIssueReporter; +import org.javahelpers.codegen.SourceFormatter; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.logging.NoOpPerformanceTracker; +import org.javahelpers.codegen.logging.PerformanceTracker; +import org.javahelpers.codegen.logging.ProcessingLogger; +import org.javahelpers.codegen.model.core.ClassFieldDto; +import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.method.MethodDto; +import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.junit.jupiter.api.Test; + +/** + * Tests for {@link RoasterCodeGenerator} driving {@link GenerationTargetClassDto}s directly — no + * simple-builder types involved, the {@link GenerationEnvironment} is built from codegen-core types + * only and the emitted source is captured in memory and asserted as a whole text block. + */ +class RoasterCodeGeneratorTest { + + private static final class CapturingFile implements GeneratedSourceFile { + private final String name; + private final StringWriter buffer = new StringWriter(); + + private CapturingFile(CharSequence qualifiedName) { + this.name = qualifiedName.toString(); + } + + @Override + public URI toUri() { + return URI.create("mem:///" + name.replace('.', '/') + ".java"); + } + + @Override + public Writer openWriter() { + return buffer; + } + + private String source() { + return buffer.toString(); + } + } + + private static GenerationEnvironment environment( + ProcessingLogger logger, CapturingFile[] written) { + return new GenerationEnvironment() { + @Override + public ProcessingLogger getLogger() { + return logger; + } + + @Override + public PerformanceTracker getPerformanceTracker() { + return new NoOpPerformanceTracker(); + } + + @Override + public GenerationIssueReporter getIssueReporter() { + return logger::warning; + } + + @Override + public GeneratedSourceFile createSourceFile(CharSequence qualifiedName) { + CapturingFile file = new CapturingFile(qualifiedName); + written[0] = file; + return file; + } + }; + } + + /** A builder-style DTO: private target field, one delegating setter, one build method. */ + private static GenerationTargetClassDto personBuilderDefinition() { + TypeName builderType = new TypeName("test", "PersonBuilder"); + TypeName personType = new TypeName("test", "Person"); + + GenerationTargetClassDto target = new GenerationTargetClassDto(); + target.setTypeName(builderType); + target.setClassAccessModifier(AccessModifier.PUBLIC); + target.setFormattingMode(FormattingMode.NONE); + + ClassFieldDto field = new ClassFieldDto(); + field.setFieldName("target"); + field.setFieldType(personType); + field.setVisibility(AccessModifier.PRIVATE); + field.setLiteralInitializer("new Person()"); + target.addClassField(field); + + MethodDto name = new MethodDto("name", builderType); + name.setModifier(AccessModifier.PUBLIC); + MethodParameterDto param = new MethodParameterDto(); + param.setParameterName("name"); + param.setParameterTypeName(new TypeName("java.lang", "String")); + name.addParameter(param); + name.setCode( + """ + target.setName(name); + return this;"""); + target.addMethod(name); + + MethodDto build = new MethodDto("build", personType); + build.setModifier(AccessModifier.PUBLIC); + build.setCode("return target;"); + target.addMethod(build); + return target; + } + + @Test + void generatesDelegatingBuilderFromDto() throws Exception { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingFile[] written = new CapturingFile[1]; + RoasterCodeGenerator generator = + new RoasterCodeGenerator(environment(capturing.logger(), written)); + SourceFormatter formatter = new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE); + + generator.generateClass(personBuilderDefinition(), formatter); + + assertNormalizedEquals( + """ + package test; + public class PersonBuilder { + + private Person target = new Person(); + + public PersonBuilder name(String name) { + target.setName(name); + return this; + } + + public Person build() { + return target; + } + }""", + written[0].source(), + "generated PersonBuilder must match the expected source"); + } + + @Test + void writesFileUnderQualifiedName() throws Exception { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + CapturingFile[] written = new CapturingFile[1]; + RoasterCodeGenerator generator = + new RoasterCodeGenerator(environment(capturing.logger(), written)); + + GenerationTargetClassDto empty = new GenerationTargetClassDto(); + empty.setTypeName(new TypeName("com.example", "EmptyBuilder")); + empty.setClassAccessModifier(AccessModifier.PUBLIC); + empty.setFormattingMode(FormattingMode.NONE); + + generator.generateClass( + empty, new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE)); + + org.junit.jupiter.api.Assertions.assertEquals( + "mem:///com/example/EmptyBuilder.java", written[0].toUri().toString()); + } +} diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java new file mode 100644 index 00000000..d009554e --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java @@ -0,0 +1,73 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link CapturingProcessingLogger}. */ +class CapturingProcessingLoggerTest { + + @Test + void capturesSeverityPrefixedMessages() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create("pfx"); + + capturing.logger().info("hello"); + capturing.logger().warning("careful %s", "now"); + capturing.logger().debug("suppressed"); + + assertEquals( + java.util.List.of("NOTE: pfx: hello", "WARNING: pfx: careful now"), capturing.messages()); + } + + @Test + void debugEnabled_capturesDebugMessages() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.createDebugEnabled(); + + capturing.logger().debug("visible"); + + assertEquals(1, capturing.messages().size()); + assertTrue(capturing.messages().get(0).startsWith("OTHER: [DEBUG]")); + } + + @Test + void assertMessage_passesForCapturedMessage() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + + capturing.logger().info("expected"); + + capturing.assertMessage("NOTE: expected"); + } + + @Test + void assertMessage_failsForMissingMessage() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + + assertThrows(AssertionError.class, () -> capturing.assertMessage("NOTE: never emitted")); + } +} diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java new file mode 100644 index 00000000..41d90c21 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java @@ -0,0 +1,140 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.testing.compile.Compilation; +import java.util.Set; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import javax.tools.JavaFileObject; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link CodegenTestUtils} — the compile-testing helpers themselves. */ +class CodegenTestUtilsTest { + + /** Emits one fixed generated source file so {@code loadGeneratedSource} has something to read. */ + private static class EmittingProcessor extends AbstractProcessor { + private boolean ran; + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latestSupported(); + } + + @Override + public Set getSupportedAnnotationTypes() { + return Set.of("*"); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (!ran && !roundEnv.processingOver()) { + ran = true; + try { + var file = processingEnv.getFiler().createSourceFile("test.Generated"); + try (var writer = file.openWriter()) { + writer.write("package test;\npublic class Generated {}\n"); + } + } catch (java.io.IOException e) { + throw new IllegalStateException(e); + } + } + return false; + } + } + + @Test + void forSource_derivesQualifiedNameFromSource() { + JavaFileObject file = + CodegenTestUtils.forSource( + """ + package test.sub; + public record Item(String value) {} + """); + + // compile-testing names in-memory files after the derived qualified name + assertTrue(file.getName().endsWith("Item.java")); + assertTrue(file.getName().contains("test/sub")); + } + + @Test + void forSource_rejectsSourceWithoutTypeDeclaration() { + assertThrows( + IllegalArgumentException.class, + () -> CodegenTestUtils.forSource("package test;\n// no type here\n")); + } + + @Test + void createMockAnnotation_producesCompilableAnnotation() { + JavaFileObject annotation = + CodegenTestUtils.createMockAnnotation( + "test.anno", "Marker", "ElementType.FIELD", "String value();"); + + Compilation compilation = + CodegenTestUtils.createCompiler() + .compile( + annotation, + CodegenTestUtils.forSource( + """ + package test; + public class Dto { + @test.anno.Marker("x") + private String field; + } + """)); + + assertThat(compilation).succeeded(); + } + + @Test + void loadGeneratedSource_readsEmittedFile() { + Compilation compilation = + CodegenTestUtils.createCompiler(new EmittingProcessor()) + .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + + assertThat(compilation).succeeded(); + assertEquals( + "package test;\npublic class Generated {}\n", + CodegenTestUtils.loadGeneratedSource(compilation, "Generated")); + } + + @Test + void loadGeneratedSource_failsForMissingFile() { + Compilation compilation = + CodegenTestUtils.createCompiler() + .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + + assertThat(compilation).succeeded(); + assertThrows( + AssertionError.class, () -> CodegenTestUtils.loadGeneratedSource(compilation, "Missing")); + } +} diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/testing/FormatterProfileTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/FormatterProfileTestUtilsTest.java similarity index 95% rename from processor/src/test/java/org/javahelpers/simple/builders/processor/testing/FormatterProfileTestUtilsTest.java rename to codegen-testing/src/test/java/org/javahelpers/codegen/testing/FormatterProfileTestUtilsTest.java index f7e15648..a7f08a4e 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/testing/FormatterProfileTestUtilsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/FormatterProfileTestUtilsTest.java @@ -22,7 +22,7 @@ * SOFTWARE. */ -package org.javahelpers.simple.builders.processor.testing; +package org.javahelpers.codegen.testing; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -32,7 +32,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; -import org.javahelpers.codegen.testing.FormatterProfileTestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java new file mode 100644 index 00000000..7f272f3f --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java @@ -0,0 +1,57 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Map; +import javax.annotation.processing.ProcessingEnvironment; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link ProcessingEnvironmentStub}. */ +class ProcessingEnvironmentStubTest { + + @Test + void createEmpty_returnsEmptyOptions() { + ProcessingEnvironment env = ProcessingEnvironmentStub.createEmpty(); + assertTrue(env.getOptions().isEmpty()); + } + + @Test + void create_returnsProvidedOptions() { + ProcessingEnvironment env = + ProcessingEnvironmentStub.create(Map.of("verbose", "true", "strict", "false")); + assertEquals("true", env.getOptions().get("verbose")); + assertEquals("false", env.getOptions().get("strict")); + } + + @Test + void builder_accumulatesOptions() { + ProcessingEnvironment env = + ProcessingEnvironmentStub.builder().put("a", "1").put("b", "2").build(); + assertEquals(Map.of("a", "1", "b", "2"), env.getOptions()); + } +} diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java new file mode 100644 index 00000000..61c00ae0 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java @@ -0,0 +1,83 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNotContaining; +import static org.javahelpers.codegen.testing.ProcessorAsserts.contains; +import static org.javahelpers.codegen.testing.ProcessorAsserts.notContains; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link ProcessorAsserts} — asserting the assertion helpers themselves. */ +class ProcessorAssertsTest { + + private static final String CODE = "public class Foo {\n private String name;\n}"; + + @Test + void assertContaining_passesWhenAllSearchStringsPresent() { + assertContaining(CODE, "class Foo", "String name"); + } + + @Test + void assertContaining_failsOnMissingSearchString() { + assertThrows(AssertionError.class, () -> assertContaining(CODE, "class Bar")); + } + + @Test + void assertNotContaining_passesWhenSearchStringAbsent() { + assertNotContaining(CODE, "class Bar"); + assertThrows(AssertionError.class, () -> assertNotContaining(CODE, "class Foo")); + } + + @Test + void assertingResult_supportsRecordChecks() { + ProcessorAsserts.assertingResult(CODE, contains("class Foo"), notContains("class Bar")); + assertThrows( + AssertionError.class, + () -> ProcessorAsserts.assertingResult(CODE, notContains("class Foo"))); + } + + @Test + void assertNormalizedEquals_ignoresWhitespaceDifferences() { + assertNormalizedEquals( + """ + package test; + public class Foo { + private String name; + }""", + "package test;\n public class Foo {\n private String name; \n}\n", + "whitespace-normalized comparison should pass"); + } + + @Test + void assertNormalizedEquals_failsOnContentDifference() { + assertThrows( + AssertionError.class, + () -> assertNormalizedEquals("public class Foo {}", "public class Bar {}", "mismatch")); + } +} diff --git a/codegen-testing/src/test/resources/eclipse-java-format.xml b/codegen-testing/src/test/resources/eclipse-java-format.xml new file mode 100644 index 00000000..16144891 --- /dev/null +++ b/codegen-testing/src/test/resources/eclipse-java-format.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/processor/pom.xml b/processor/pom.xml index 152827d1..7bcc8de5 100644 --- a/processor/pom.xml +++ b/processor/pom.xml @@ -103,11 +103,6 @@ simple-processor ${project.version} - - io.github.java-helpers.codegen - codegen-roaster - ${project.version} - io.github.java-helpers.codegen codegen-testing diff --git a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java index 19b0dd1a..c1dd899d 100644 --- a/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java +++ b/processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java @@ -315,8 +315,8 @@ private static String buildSetterSourceDescription( * same signature key are resolved by keeping the highest-priority one; losers are removed from * their field/class method lists so they are never mapped to the rendering DTO. * - *

A generic safety net in {@link - * org.javahelpers.codegen.roaster.RoasterCodeGenerator#resolveMethodConflicts} handles any + *

A generic safety net in the code generator's method-conflict resolution (see {@code + * RoasterCodeGenerator#resolveMethodConflicts} in the codegen-roaster backend) handles any * remaining duplicates (e.g., from enhancer methods added after this step) by keeping the first * occurrence. * diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java new file mode 100644 index 00000000..a9c96b37 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java @@ -0,0 +1,235 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.analysis; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.testing.compile.Compilation; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.processing.AnnotationProcessingContext; +import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link FieldAnnotationExtractor} against elements captured from a compilation. */ +class FieldAnnotationExtractorTest { + + private static class ProbeProcessor extends AbstractProcessor { + private final BiConsumer probe; + private boolean ran; + + ProbeProcessor(BiConsumer probe) { + this.probe = probe; + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latestSupported(); + } + + @Override + public Set getSupportedAnnotationTypes() { + return Set.of("*"); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (ran || roundEnv.processingOver()) { + return false; + } + ran = true; + probe.accept( + roundEnv, + new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), processingEnv)); + return false; + } + } + + private static VariableElement field(TypeElement dto, String fieldName) { + return dto.getEnclosedElements().stream() + .filter(VariableElement.class::isInstance) + .map(VariableElement.class::cast) + .filter(e -> e.getSimpleName().toString().equals(fieldName)) + .findFirst() + .orElseThrow(); + } + + private static final String DTO_SOURCE = + """ + package test; + public class Dto { + @Deprecated + private String legacy; + @test.Default("GENERAL") + private String mode; + @test.NonNull + private String required; + private String plain; + } + """; + + private static final String ANNOTATION_SOURCES = + """ + package test; + public @interface Default { String value(); } + """; + + private static final String NONNULL_SOURCE = + """ + package test; + public @interface NonNull {} + """; + + private Compilation compile(BiConsumer probe) { + return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)) + .compile( + CodegenTestUtils.forSource(DTO_SOURCE), + CodegenTestUtils.forSource(ANNOTATION_SOURCES), + CodegenTestUtils.forSource(NONNULL_SOURCE)); + } + + @Test + void extractDeprecatedAnnotation_findsDeprecatedField() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, ctx) -> + result.set( + FieldAnnotationExtractor.extractDeprecatedAnnotation( + field(ctx.getTypeElement("test.Dto"), "legacy"), ctx))); + + assertThat(compilation).succeeded(); + assertTrue(result.get().isPresent()); + assertEquals( + "java.lang.Deprecated", + result.get().get().getAnnotationType().getPackageName() + + "." + + result.get().get().getAnnotationType().getClassName()); + } + + @Test + void extractDeprecatedAnnotation_emptyForPlainField() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, ctx) -> + result.set( + FieldAnnotationExtractor.extractDeprecatedAnnotation( + field(ctx.getTypeElement("test.Dto"), "plain"), ctx))); + + assertThat(compilation).succeeded(); + assertTrue(result.get().isEmpty()); + } + + @Test + void extractAnnotations_returnsMemberValues() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, ctx) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(ctx.getTypeElement("test.Dto"), "mode"), ctx))); + + assertThat(compilation).succeeded(); + assertEquals(1, result.get().size()); + AnnotationDto annotation = result.get().get(0); + assertEquals("Default", annotation.getAnnotationType().getClassName()); + assertEquals("\"GENERAL\"", annotation.getMembers().get("value")); + } + + @Test + void hasNonNullConstraint_detectsNonNullAnnotation() { + AtomicReference nonNull = new AtomicReference<>(); + AtomicReference plain = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, ctx) -> { + TypeElement dto = ctx.getTypeElement("test.Dto"); + nonNull.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "required"))); + plain.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "plain"))); + }); + + assertThat(compilation).succeeded(); + assertTrue(nonNull.get()); + assertFalse(plain.get()); + } + + @Test + void extractAnnotationValue_matchesAnnotationBySimpleName() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, ctx) -> + result.set( + FieldAnnotationExtractor.extractAnnotationValue( + field(ctx.getTypeElement("test.Dto"), "mode"), Set.of("Default")))); + + assertThat(compilation).succeeded(); + assertEquals(Optional.of("GENERAL"), result.get()); + } + + @Test + void formatDefaultExpression_quotesStringValues() { + assertEquals( + "\"GENERAL\"", + FieldAnnotationExtractor.formatDefaultExpression("GENERAL", TypeName.of(String.class))); + } + + @Test + void formatDefaultExpression_qualifiesSimpleEnumConstant() { + TypeName enumType = new TypeName("test", "ItemCondition"); + enumType.setEnumType(true); + assertEquals( + "ItemCondition.GOOD", FieldAnnotationExtractor.formatDefaultExpression("GOOD", enumType)); + } + + @Test + void formatDefaultExpression_keepsComplexExpressions() { + TypeName enumType = new TypeName("test", "ItemCondition"); + enumType.setEnumType(true); + assertEquals( + "ItemCondition.GOOD", + FieldAnnotationExtractor.formatDefaultExpression("ItemCondition.GOOD", enumType)); + assertEquals( + "List.of()", + FieldAnnotationExtractor.formatDefaultExpression("List.of()", TypeName.of(List.class))); + } +} diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/JavaLangAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java similarity index 98% rename from processor/src/test/java/org/javahelpers/simple/builders/processor/JavaLangAnalyserTest.java rename to simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java index 1a211d13..c7ed3033 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/JavaLangAnalyserTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -22,7 +22,7 @@ * SOFTWARE. */ -package org.javahelpers.simple.builders.processor; +package org.javahelpers.codegen.analysis; import static org.junit.jupiter.api.Assertions.*; @@ -38,7 +38,6 @@ import javax.lang.model.element.Name; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; -import org.javahelpers.codegen.analysis.JavaLangAnalyser; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java new file mode 100644 index 00000000..34c2a0fb --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java @@ -0,0 +1,207 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.analysis; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import com.google.testing.compile.Compilation; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.codegen.processing.AnnotationProcessingContext; +import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link JavaLangMapper} against elements captured from a real compilation. */ +class JavaLangMapperTest { + + /** Runs {@code probe} once during the first processing round with a live processing context. */ + private static class ProbeProcessor extends AbstractProcessor { + private final BiConsumer probe; + private boolean ran; + + ProbeProcessor(BiConsumer probe) { + this.probe = probe; + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latestSupported(); + } + + @Override + public Set getSupportedAnnotationTypes() { + return Set.of("*"); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (ran || roundEnv.processingOver()) { + return false; + } + ran = true; + probe.accept( + roundEnv, + new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), processingEnv)); + return false; + } + } + + private static VariableElement setterParameter( + TypeElement dto, String setterName, int paramIndex) { + return dto.getEnclosedElements().stream() + .filter(ExecutableElement.class::isInstance) + .map(ExecutableElement.class::cast) + .filter(m -> m.getSimpleName().toString().equals(setterName)) + .map(m -> m.getParameters().get(paramIndex)) + .findFirst() + .orElseThrow(); + } + + @Test + void map2TypeName_mapsJavaClass() { + TypeName typeName = JavaLangMapper.map2TypeName(String.class); + assertEquals("java.lang", typeName.getPackageName()); + assertEquals("String", typeName.getClassName()); + } + + @Test + void mapToTypeName_mapsTypeElement() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, ctx) -> { + TypeElement dto = ctx.getTypeElement("test.Dto"); + result.set(JavaLangMapper.mapToTypeName(dto, ctx)); + })) + .compile( + CodegenTestUtils.forSource( + """ + package test; + public class Dto { + private String name; + public void setName(String name) { this.name = name; } + } + """)); + + assertThat(compilation).succeeded(); + assertEquals("test", result.get().getPackageName()); + assertEquals("Dto", result.get().getClassName()); + } + + @Test + void map2MethodParameter_mapsNameAndListType() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, ctx) -> { + TypeElement dto = ctx.getTypeElement("test.Dto"); + VariableElement param = setterParameter(dto, "setTags", 0); + result.set(JavaLangMapper.map2MethodParameter(param, ctx)); + })) + .compile( + CodegenTestUtils.forSource( + """ + package test; + import java.util.List; + public class Dto { + private List tags; + public void setTags(List tags) { this.tags = tags; } + } + """)); + + assertThat(compilation).succeeded(); + MethodParameterDto param = result.get(); + assertEquals("tags", param.getParameterName()); + TypeNameList typeName = assertInstanceOf(TypeNameList.class, param.getParameterType()); + assertEquals("java.util.List", typeName.getPackageName() + "." + typeName.getClassName()); + assertEquals("String", typeName.getElementType().getClassName()); + } + + @Test + void createDerivedTypeName_appendsSuffix() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, ctx) -> { + TypeElement dto = ctx.getTypeElement("test.Dto"); + result.set(JavaLangMapper.createDerivedTypeName(dto, ctx, "Builder")); + })) + .compile( + CodegenTestUtils.forSource( + """ + package test; + public class Dto {} + """)); + + assertThat(compilation).succeeded(); + assertEquals("test", result.get().getPackageName()); + assertEquals("DtoBuilder", result.get().getClassName()); + } + + @Test + void extractInterfaceTypeArguments_resolvesInheritedListArgument() { + // CustomList extends ArrayList: the List element type is Y, not the declared X/Y pair + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, ctx) -> { + TypeElement customList = ctx.getTypeElement("test.CustomList"); + TypeElement listInterface = ctx.getTypeElement("java.util.List"); + result.set( + JavaLangMapper.extractInterfaceTypeArguments( + customList.asType(), listInterface, ctx)); + })) + .compile( + CodegenTestUtils.forSource( + """ + package test; + import java.util.ArrayList; + public class CustomList extends ArrayList {} + """)); + + assertThat(compilation).succeeded(); + assertEquals(1, result.get().size()); + assertEquals("Y", result.get().get(0).getClassName()); + } +} diff --git a/processor/src/test/java/org/javahelpers/codegen/processing/CodegenProcessorConfigurationTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/CodegenProcessorConfigurationTest.java similarity index 100% rename from processor/src/test/java/org/javahelpers/codegen/processing/CodegenProcessorConfigurationTest.java rename to simple-processor/src/test/java/org/javahelpers/codegen/processing/CodegenProcessorConfigurationTest.java diff --git a/processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java similarity index 100% rename from processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java rename to simple-processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java diff --git a/processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java similarity index 96% rename from processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java rename to simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java index 3358a2b8..189e1585 100644 --- a/processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java @@ -24,8 +24,8 @@ package org.javahelpers.codegen.processing; import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.CodegenTestUtils.loadGeneratedSource; import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; -import static org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils.loadGeneratedSource; import com.google.testing.compile.Compilation; import java.lang.annotation.ElementType; @@ -48,7 +48,7 @@ import org.javahelpers.codegen.model.core.GenerationTargetClassDto; import org.javahelpers.codegen.model.method.MethodDto; import org.javahelpers.codegen.model.type.TypeName; -import org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils; +import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; /** @@ -173,7 +173,7 @@ private static TypeName builderName(TypeElement target, AnnotationProcessingCont void minimalProcessorGeneratesDelegatingBuilder() { // Given JavaFileObject source = - ProcessorTestUtils.forSource( + CodegenTestUtils.forSource( """ package test; import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; @@ -186,7 +186,7 @@ public class Person { // When Compilation compilation = - ProcessorTestUtils.createCompiler(new MinimalProcessor()).compile(source); + CodegenTestUtils.createCompiler(new MinimalProcessor()).compile(source); // Then assertThat(compilation).succeeded(); diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/processing/OptionValueParsersTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/OptionValueParsersTest.java similarity index 97% rename from processor/src/test/java/org/javahelpers/simple/builders/processor/processing/OptionValueParsersTest.java rename to simple-processor/src/test/java/org/javahelpers/codegen/processing/OptionValueParsersTest.java index fa2f546d..45f4fe0d 100644 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/processing/OptionValueParsersTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/OptionValueParsersTest.java @@ -22,14 +22,13 @@ * SOFTWARE. */ -package org.javahelpers.simple.builders.processor.processing; +package org.javahelpers.codegen.processing; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.OptionState; -import org.javahelpers.codegen.processing.OptionValueParsers; import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.junit.jupiter.api.Test; diff --git a/processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java similarity index 100% rename from processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java rename to simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java From 6e7e0dc17cba1e4f4fa3eb4c8f008f2fe9f7375e Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:26:36 +0000 Subject: [PATCH 02/12] test: lift per-module coverage and share test helpers (#390) - add missing coverage for codegen-testing helpers, codegen-roaster backend/mapper/generator and simple-processor analysers, context, options and logging - move shared test support into codegen-testing (ProbeProcessor, ElementTestUtils, TestingGenerationEnvironment) - delete enum-only test and exclude enums/DTO model packages from JaCoCo coverage scope in all modules - pin surefire 3.6.0 in core so JUnit 5 tests actually run Per-module line coverage now: core 95%, codegen-core 90%, codegen-roaster 91%, codegen-testing 91%, simple-processor 84%, processor 97%. Co-Authored-By: Andreas Igel --- codegen-core/pom.xml | 5 +- .../codegen/enums/CodegenEnumsTest.java | 61 -- codegen-roaster/pom.xml | 5 + .../codegen/roaster/RoasterBackendTest.java | 53 ++ .../RoasterCodeGeneratorResilienceTest.java | 41 +- .../roaster/RoasterCodeGeneratorTest.java | 237 ++++-- .../codegen/roaster/RoasterMapperTest.java | 209 +++++ codegen-testing/pom.xml | 5 +- .../codegen/testing/ElementTestUtils.java | 91 +++ .../codegen/testing/ProbeProcessor.java | 83 ++ .../testing/TestingGenerationEnvironment.java | 124 +++ .../CapturingProcessingLoggerTest.java | 12 + .../codegen/testing/CodegenTestUtilsTest.java | 42 + .../codegen/testing/ElementTestUtilsTest.java | 116 +++ .../codegen/testing/ProbeProcessorTest.java | 67 ++ .../ProcessingEnvironmentStubTest.java | 12 + .../codegen/testing/ProcessorAssertsTest.java | 92 +++ .../TestingGenerationEnvironmentTest.java | 77 ++ core/pom.xml | 21 + processor/pom.xml | 5 +- simple-processor/pom.xml | 5 +- .../FieldAnnotationExtractorTest.java | 109 ++- .../codegen/analysis/GeneratedTypesTest.java | 66 ++ .../analysis/JavaLangAnalyserTest.java | 722 ++++++++++++------ .../codegen/analysis/JavaLangMapperTest.java | 344 ++++++--- .../analysis/TypeNameAnalyserTest.java | 76 ++ .../codegen/analysis/testannotations/Tag.java | 33 + .../analysis/testannotations/Tags.java | 30 + .../AnnotationProcessingContextTest.java | 231 ++++++ .../CompilerArgumentsReaderTest.java | 100 +++ .../processing/PipelinePhasesTest.java | 48 ++ .../ProcessorOptionRegistryTest.java | 70 +- .../logging/MessagerProcessingLoggerTest.java | 236 ++++++ 33 files changed, 2866 insertions(+), 562 deletions(-) delete mode 100644 codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java create mode 100644 codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java create mode 100644 codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java create mode 100644 codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java create mode 100644 codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java create mode 100644 codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java create mode 100644 codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java create mode 100644 codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProbeProcessorTest.java create mode 100644 codegen-testing/src/test/java/org/javahelpers/codegen/testing/TestingGenerationEnvironmentTest.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/analysis/GeneratedTypesTest.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/analysis/TypeNameAnalyserTest.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tag.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tags.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/processing/CompilerArgumentsReaderTest.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/processing/PipelinePhasesTest.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java diff --git a/codegen-core/pom.xml b/codegen-core/pom.xml index 6c4b5550..78efb444 100644 --- a/codegen-core/pom.xml +++ b/codegen-core/pom.xml @@ -348,10 +348,13 @@ - + **/codegen/model/** + **/processor/model/** + **/enums/** **/*Exception.* + **/exceptions/** **/JavadocConstants.* diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java deleted file mode 100644 index 3d95d67f..00000000 --- a/codegen-core/src/test/java/org/javahelpers/codegen/enums/CodegenEnumsTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2025-2026 Andreas Igel - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package org.javahelpers.codegen.enums; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** Unit tests for the codegen enums' value mappings and parsing. */ -class CodegenEnumsTest { - - @Test - void accessModifier_mapsToJavaKeyword() { - assertEquals("public", AccessModifier.DEFAULT.getJavaKeyword()); - assertEquals("public", AccessModifier.PUBLIC.getJavaKeyword()); - assertEquals("protected", AccessModifier.PROTECTED.getJavaKeyword()); - assertEquals("", AccessModifier.PACKAGE_PRIVATE.getJavaKeyword()); - assertEquals("private", AccessModifier.PRIVATE.getJavaKeyword()); - } - - @Test - void formattingMode_optionValuesAndParsing() { - assertEquals("jdt", FormattingMode.JDT.getOptionValue()); - assertEquals("lightweight", FormattingMode.LIGHTWEIGHT.getOptionValue()); - assertEquals("none", FormattingMode.NONE.getOptionValue()); - - assertEquals(FormattingMode.NONE, FormattingMode.fromString("none")); - assertEquals(FormattingMode.LIGHTWEIGHT, FormattingMode.fromString("LightWeight")); - assertEquals(FormattingMode.JDT, FormattingMode.fromString(null)); - assertEquals(FormattingMode.JDT, FormattingMode.fromString("unknown")); - } - - @Test - void optionState_hasTriStateValues() { - assertEquals( - java.util.Set.of(OptionState.UNSET, OptionState.ENABLED, OptionState.DISABLED), - java.util.Set.of(OptionState.values())); - } -} diff --git a/codegen-roaster/pom.xml b/codegen-roaster/pom.xml index 8d876dba..50381048 100644 --- a/codegen-roaster/pom.xml +++ b/codegen-roaster/pom.xml @@ -345,8 +345,13 @@ + + **/codegen/model/** + **/processor/model/** + **/enums/** **/*Exception.* + **/exceptions/** **/JavadocConstants.* diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java new file mode 100644 index 00000000..3cdf124e --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java @@ -0,0 +1,53 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.roaster; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; + +import org.javahelpers.codegen.enums.FormattingMode; +import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.TestingGenerationEnvironment; +import org.junit.jupiter.api.Test; + +/** Tests for {@link RoasterBackend}'s matched generator/formatter pair. */ +class RoasterBackendTest { + + @Test + void exposesGeneratorAndCachesFormatterPerMode() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + RoasterBackend backend = + new RoasterBackend( + TestingGenerationEnvironment.create(capturing.logger()), capturing.logger(), null); + + assertInstanceOf(RoasterCodeGenerator.class, backend.generator()); + assertInstanceOf( + RoasterSourceFormatter.class, backend.formatterFor(FormattingMode.LIGHTWEIGHT)); + // formatters are cached per mode + assertSame( + backend.formatterFor(FormattingMode.LIGHTWEIGHT), + backend.formatterFor(FormattingMode.LIGHTWEIGHT)); + } +} diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java index e681bbed..5d1de85d 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java @@ -28,14 +28,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.javahelpers.codegen.CodeGenerationException; -import org.javahelpers.codegen.GeneratedSourceFile; -import org.javahelpers.codegen.GenerationEnvironment; -import org.javahelpers.codegen.GenerationIssueReporter; import org.javahelpers.codegen.SourceFormatter; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; -import org.javahelpers.codegen.logging.NoOpPerformanceTracker; -import org.javahelpers.codegen.logging.PerformanceTracker; import org.javahelpers.codegen.logging.ProcessingLogger; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; import org.javahelpers.codegen.model.method.ConstructorDto; @@ -46,6 +41,7 @@ import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.roaster.exceptions.RoasterMapperException; import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.TestingGenerationEnvironment; import org.junit.jupiter.api.Test; /** @@ -59,35 +55,6 @@ */ class RoasterCodeGeneratorResilienceTest { - /** - * Minimal {@link GenerationEnvironment} built only from codegen-core types: issues surface on the - * logger as warnings, timing is not tracked, and {@code createSourceFile} returns {@code null} so - * the file-write step fails deterministically on it. - */ - private static GenerationEnvironment stubEnvironment(ProcessingLogger logger) { - return new GenerationEnvironment() { - @Override - public ProcessingLogger getLogger() { - return logger; - } - - @Override - public PerformanceTracker getPerformanceTracker() { - return new NoOpPerformanceTracker(); - } - - @Override - public GenerationIssueReporter getIssueReporter() { - return logger::warning; - } - - @Override - public GeneratedSourceFile createSourceFile(CharSequence qualifiedName) { - return null; - } - }; - } - /** Placeholder subtype the mapper does not know how to render, forcing a mapping failure. */ private static final class UnsupportedPlaceholder extends MethodCodePlaceholder { private UnsupportedPlaceholder(String label, String value) { @@ -111,7 +78,8 @@ void shouldWrapRenderingRuntimeExceptionInCodeGenerationException() { classDef.addConstructor(constructor); ProcessingLogger logger = CapturingProcessingLogger.create().logger(); - RoasterCodeGenerator generator = new RoasterCodeGenerator(stubEnvironment(logger)); + RoasterCodeGenerator generator = + new RoasterCodeGenerator(TestingGenerationEnvironment.createUnwritable(logger)); SourceFormatter formatter = new RoasterSourceFormatter(logger, FormattingMode.NONE); CodeGenerationException thrown = @@ -137,7 +105,8 @@ void shouldKeepFirstMethodAndWarnOnDuplicateSignature() { classDef.addMethod(duplicateSignatureMethod("second")); CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); - RoasterCodeGenerator generator = new RoasterCodeGenerator(stubEnvironment(capturing.logger())); + RoasterCodeGenerator generator = + new RoasterCodeGenerator(TestingGenerationEnvironment.createUnwritable(capturing.logger())); SourceFormatter formatter = new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE); // generation itself succeeds; only the file-write step fails on the stub's null source file diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index aee5a54a..85a6b2ab 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -24,85 +24,38 @@ package org.javahelpers.codegen.roaster; +import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; -import java.io.StringWriter; -import java.io.Writer; -import java.net.URI; -import org.javahelpers.codegen.GeneratedSourceFile; -import org.javahelpers.codegen.GenerationEnvironment; -import org.javahelpers.codegen.GenerationIssueReporter; +import java.util.List; import org.javahelpers.codegen.SourceFormatter; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; -import org.javahelpers.codegen.logging.NoOpPerformanceTracker; -import org.javahelpers.codegen.logging.PerformanceTracker; -import org.javahelpers.codegen.logging.ProcessingLogger; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.InterfaceName; import org.javahelpers.codegen.model.core.ClassFieldDto; import org.javahelpers.codegen.model.core.GenerationTargetClassDto; +import org.javahelpers.codegen.model.javadoc.JavadocDto; +import org.javahelpers.codegen.model.method.ConstructorDto; import org.javahelpers.codegen.model.method.MethodDto; import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.type.GenericParameterDto; +import org.javahelpers.codegen.model.type.NestedTypeDto; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNamePrimitive; +import org.javahelpers.codegen.model.type.TypeNameVariable; import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.TestingGenerationEnvironment; import org.junit.jupiter.api.Test; /** * Tests for {@link RoasterCodeGenerator} driving {@link GenerationTargetClassDto}s directly — no - * simple-builder types involved, the {@link GenerationEnvironment} is built from codegen-core types - * only and the emitted source is captured in memory and asserted as a whole text block. + * simple-builder types involved, the {@code GenerationEnvironment} comes from shared test support + * ({@link TestingGenerationEnvironment}) and the emitted source is asserted as a whole text block. */ class RoasterCodeGeneratorTest { - private static final class CapturingFile implements GeneratedSourceFile { - private final String name; - private final StringWriter buffer = new StringWriter(); - - private CapturingFile(CharSequence qualifiedName) { - this.name = qualifiedName.toString(); - } - - @Override - public URI toUri() { - return URI.create("mem:///" + name.replace('.', '/') + ".java"); - } - - @Override - public Writer openWriter() { - return buffer; - } - - private String source() { - return buffer.toString(); - } - } - - private static GenerationEnvironment environment( - ProcessingLogger logger, CapturingFile[] written) { - return new GenerationEnvironment() { - @Override - public ProcessingLogger getLogger() { - return logger; - } - - @Override - public PerformanceTracker getPerformanceTracker() { - return new NoOpPerformanceTracker(); - } - - @Override - public GenerationIssueReporter getIssueReporter() { - return logger::warning; - } - - @Override - public GeneratedSourceFile createSourceFile(CharSequence qualifiedName) { - CapturingFile file = new CapturingFile(qualifiedName); - written[0] = file; - return file; - } - }; - } - /** A builder-style DTO: private target field, one delegating setter, one build method. */ private static GenerationTargetClassDto personBuilderDefinition() { TypeName builderType = new TypeName("test", "PersonBuilder"); @@ -142,9 +95,8 @@ private static GenerationTargetClassDto personBuilderDefinition() { @Test void generatesDelegatingBuilderFromDto() throws Exception { CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); - CapturingFile[] written = new CapturingFile[1]; - RoasterCodeGenerator generator = - new RoasterCodeGenerator(environment(capturing.logger(), written)); + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); + RoasterCodeGenerator generator = new RoasterCodeGenerator(env); SourceFormatter formatter = new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE); generator.generateClass(personBuilderDefinition(), formatter); @@ -165,16 +117,15 @@ public Person build() { return target; } }""", - written[0].source(), + env.generatedSource(), "generated PersonBuilder must match the expected source"); } @Test void writesFileUnderQualifiedName() throws Exception { CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); - CapturingFile[] written = new CapturingFile[1]; - RoasterCodeGenerator generator = - new RoasterCodeGenerator(environment(capturing.logger(), written)); + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); + RoasterCodeGenerator generator = new RoasterCodeGenerator(env); GenerationTargetClassDto empty = new GenerationTargetClassDto(); empty.setTypeName(new TypeName("com.example", "EmptyBuilder")); @@ -185,6 +136,154 @@ void writesFileUnderQualifiedName() throws Exception { empty, new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE)); org.junit.jupiter.api.Assertions.assertEquals( - "mem:///com/example/EmptyBuilder.java", written[0].toUri().toString()); + "mem:///com/example/EmptyBuilder.java", env.writtenUri().toString()); + } + + @Test + void generatesClassMetadataJavadocAndAnnotations() throws Exception { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName("test", "AnnotatedBuilder")); + classDef.setClassAccessModifier(AccessModifier.PUBLIC); + classDef.setFormattingMode(FormattingMode.NONE); + classDef.setClassJavadoc(new JavadocDto("Builder for {@link Person}.")); + AnnotationDto generated = new AnnotationDto(); + generated.setAnnotationType(new TypeName("javax.annotation", "Generated")); + generated.addMember("value", "\"simple-builders\""); + classDef.addClassAnnotation(generated); + classDef.setSuperType(new TypeName("test", "AbstractBuilder")); + InterfaceName iface = new InterfaceName("java.io", "Serializable"); + classDef.addInterface(iface); + + assertContaining( + generate(classDef), + "extends AbstractBuilder", + "implements Serializable", + "Builder for", + "Generated(\"simple-builders\")"); + } + + @Test + void generatesGenericClassAndMethods() throws Exception { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName("test", "GenericBuilder")); + classDef.setClassAccessModifier(AccessModifier.PUBLIC); + classDef.setFormattingMode(FormattingMode.NONE); + GenericParameterDto generic = new GenericParameterDto(); + generic.setName("T"); + classDef.addGeneric(generic); + + MethodDto genericMethod = new MethodDto("of", new TypeNameVariable("T")); + genericMethod.setModifier(AccessModifier.PUBLIC); + genericMethod.setStatic(true); + GenericParameterDto methodGeneric = new GenericParameterDto(); + methodGeneric.setName("R"); + methodGeneric.addUpperBound(TypeName.of(Number.class)); + genericMethod.addGenericParameter(methodGeneric); + MethodParameterDto param = new MethodParameterDto(); + param.setParameterName("input"); + param.setParameterTypeName(new TypeNameVariable("R")); + genericMethod.addParameter(param); + genericMethod.setCode("return null;"); + classDef.addMethod(genericMethod); + + assertContaining( + generate(classDef), "class GenericBuilder", "static T of(R input)"); + } + + @Test + void generatesConstructorAndFieldVariants() throws Exception { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName("test", "CtorBuilder")); + classDef.setClassAccessModifier(AccessModifier.PUBLIC); + classDef.setFormattingMode(FormattingMode.NONE); + + ClassFieldDto constant = new ClassFieldDto(); + constant.setFieldName("DEFAULT_SIZE"); + constant.setFieldType(TypeNamePrimitive.INT); + constant.setVisibility(AccessModifier.PRIVATE); + constant.setLiteralInitializer("42"); + classDef.addClassField(constant); + + ConstructorDto ctor = new ConstructorDto(); + ctor.setVisibility(AccessModifier.PROTECTED); + MethodParameterDto param = new MethodParameterDto(); + param.setParameterName("capacity"); + param.setParameterTypeName(TypeNamePrimitive.INT); + AnnotationDto paramAnnotation = new AnnotationDto(); + paramAnnotation.setAnnotationType(new TypeName("test.anno", "NonNull")); + param.addAnnotation(paramAnnotation); + ctor.addParameter(param); + classDef.addConstructor(ctor); + + assertContaining( + generate(classDef), "private int DEFAULT_SIZE = 42", "protected CtorBuilder(int capacity)"); + } + + @Test + void generatesNestedTypesWithMembers() throws Exception { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName("test", "OuterBuilder")); + classDef.setClassAccessModifier(AccessModifier.PUBLIC); + classDef.setFormattingMode(FormattingMode.NONE); + + NestedTypeDto nested = new NestedTypeDto(); + nested.setTypeName("Helper"); + nested.setKind(NestedTypeDto.NestedTypeKind.CLASS); + nested.setVisibility(AccessModifier.PUBLIC); + nested.setJavadoc(new JavadocDto("Nested helper.")); + MethodDto nestedMethod = new MethodDto("assist", TypeNamePrimitive.VOID); + nestedMethod.setModifier(AccessModifier.PRIVATE); + nestedMethod.setCode("// nothing"); + nested.addMethod(nestedMethod); + classDef.addNestedType(nested); + + assertContaining(generate(classDef), "class Helper", "Nested helper.", "void assist()"); + } + + @Test + void generatesMethodWithJavadocAnnotationsAndTypedParameters() throws Exception { + GenerationTargetClassDto classDef = new GenerationTargetClassDto(); + classDef.setTypeName(new TypeName("test", "RichBuilder")); + classDef.setClassAccessModifier(AccessModifier.PUBLIC); + classDef.setFormattingMode(FormattingMode.NONE); + + MethodDto method = + new MethodDto( + "items", + new TypeNameGeneric( + new TypeName("java.util", "List"), List.of(TypeName.of(String.class)))); + method.setModifier(AccessModifier.PUBLIC); + JavadocDto javadoc = new JavadocDto("Adds items."); + javadoc.addParam("values", "items to add"); + javadoc.addReturn("this builder"); + method.setJavadoc(javadoc); + AnnotationDto override_ = new AnnotationDto(); + override_.setAnnotationType(new TypeName("java.lang", "Override")); + method.addAnnotation(override_); + MethodParameterDto param = new MethodParameterDto(); + param.setParameterName("values"); + param.setParameterTypeName( + new TypeNameGeneric(new TypeName("java.util", "List"), List.of(TypeName.of(String.class)))); + method.addParameter(param); + method.setCode("return null;"); + classDef.addMethod(method); + + String generated = generate(classDef); + assertContaining( + generated, + "Adds items", + "@param values", + "@return", + "@Override", + "List items(List values)"); + } + + private static String generate(GenerationTargetClassDto classDef) throws Exception { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); + RoasterCodeGenerator generator = new RoasterCodeGenerator(env); + generator.generateClass( + classDef, new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE)); + return env.generatedSource(); } } diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java new file mode 100644 index 00000000..c4cc66d7 --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java @@ -0,0 +1,209 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.roaster; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import org.javahelpers.codegen.model.annotation.AnnotationDto; +import org.javahelpers.codegen.model.annotation.InterfaceName; +import org.javahelpers.codegen.model.method.CodeTemplateDto; +import org.javahelpers.codegen.model.method.MethodCodePlaceholder; +import org.javahelpers.codegen.model.method.MethodCodeStringPlaceholder; +import org.javahelpers.codegen.model.method.MethodCodeTypePlaceholder; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameArray; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.javahelpers.codegen.model.type.TypeNamePrimitive; +import org.javahelpers.codegen.model.type.TypeNameVariable; +import org.javahelpers.codegen.roaster.exceptions.RoasterMapperException; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link RoasterMapper}'s type/annotation/code-template rendering. */ +class RoasterMapperTest { + + @Test + void mapType_rendersPlainClassName() { + assertEquals("String", RoasterMapper.mapType(TypeName.of(String.class))); + } + + @Test + void mapType_rendersVariableName() { + assertEquals("T", RoasterMapper.mapType(new TypeNameVariable("T"))); + } + + @Test + void mapType_rendersPrimitive() { + assertEquals("int", RoasterMapper.mapType(TypeNamePrimitive.INT)); + } + + @Test + void mapType_rendersArrayOfInnerType() { + assertEquals("String[]", RoasterMapper.mapType(new TypeNameArray(TypeName.of(String.class)))); + } + + @Test + void mapType_rendersGenericWithInnerArguments() { + TypeNameGeneric generic = + new TypeNameGeneric(new TypeName("java.util", "List"), List.of(TypeName.of(String.class))); + assertEquals("List", RoasterMapper.mapType(generic)); + } + + @Test + void mapType_rendersRawGenericWithoutArguments() { + TypeNameGeneric generic = new TypeNameGeneric(new TypeName("java.util", "List"), List.of()); + assertEquals("List", RoasterMapper.mapType(generic)); + } + + @Test + void mapType_prependsTypeUseAnnotations() { + TypeName annotated = new TypeName("java.lang", "String"); + AnnotationDto nonNull = new AnnotationDto(); + nonNull.setAnnotationType(new TypeName("test.anno", "NonNull")); + annotated.addAnnotation(nonNull); + assertEquals("@NonNull String", RoasterMapper.mapType(annotated)); + } + + @Test + void mapBoxedType_boxesAllPrimitives() { + assertEquals("Boolean", RoasterMapper.mapBoxedType(TypeNamePrimitive.BOOLEAN)); + assertEquals("Byte", RoasterMapper.mapBoxedType(TypeNamePrimitive.BYTE)); + assertEquals("Character", RoasterMapper.mapBoxedType(TypeNamePrimitive.CHAR)); + assertEquals("Double", RoasterMapper.mapBoxedType(TypeNamePrimitive.DOUBLE)); + assertEquals("Float", RoasterMapper.mapBoxedType(TypeNamePrimitive.FLOAT)); + assertEquals("Integer", RoasterMapper.mapBoxedType(TypeNamePrimitive.INT)); + assertEquals("Long", RoasterMapper.mapBoxedType(TypeNamePrimitive.LONG)); + assertEquals("Short", RoasterMapper.mapBoxedType(TypeNamePrimitive.SHORT)); + assertEquals("Void", RoasterMapper.mapBoxedType(TypeNamePrimitive.VOID)); + } + + @Test + void mapBoxedType_passesThroughNonPrimitives() { + assertEquals("String", RoasterMapper.mapBoxedType(TypeName.of(String.class))); + } + + @Test + void mapAnnotation_rendersMarkerWithoutMembers() { + AnnotationDto annotation = new AnnotationDto(); + annotation.setAnnotationType(new TypeName("test.anno", "Marker")); + assertEquals("@Marker", RoasterMapper.mapAnnotation(annotation)); + } + + @Test + void mapAnnotation_rendersValueMemberBareAndOthersNamed() { + AnnotationDto annotation = new AnnotationDto(); + annotation.setAnnotationType(new TypeName("test.anno", "Meta")); + annotation.addMember("value", "\"x\""); + annotation.addMember("order", "3"); + assertEquals("@Meta(\"x\", order = 3)", RoasterMapper.mapAnnotation(annotation)); + } + + @Test + void mapAnnotation_wrapsFailuresInMapperException() { + AnnotationDto annotation = new AnnotationDto(); + annotation.setAnnotationType( + new TypeName("test.anno", "Broken") { + @Override + public List getAnnotations() { + throw new IllegalStateException("boom"); + } + }); + assertThrows(RoasterMapperException.class, () -> RoasterMapper.mapAnnotation(annotation)); + } + + @Test + void mapInterfaceToTypeName_rendersSimpleAndParameterized() { + InterfaceName plain = new InterfaceName("java.util.function", "Supplier"); + assertEquals("Supplier", RoasterMapper.mapInterfaceToTypeName(plain)); + + InterfaceName generic = new InterfaceName("java.util.function", "Supplier"); + generic.addTypeParameter(TypeName.of(String.class)); + assertEquals("Supplier", RoasterMapper.mapInterfaceToTypeName(generic)); + } + + @Test + void mapInterfaceToTypeName_prependsTypeUseAnnotations() { + InterfaceName iface = new InterfaceName("java.io", "Serializable"); + AnnotationDto marker = new AnnotationDto(); + marker.setAnnotationType(new TypeName("test.anno", "Tag")); + iface.addAnnotation(marker); + assertEquals("@Tag Serializable", RoasterMapper.mapInterfaceToTypeName(iface)); + } + + @Test + void mapInterfaceToTypeName_wrapsFailuresInMapperException() { + InterfaceName iface = + new InterfaceName("java.io", "Serializable") { + @Override + public List getTypeParameters() { + throw new IllegalStateException("boom"); + } + }; + iface.addTypeParameter(TypeName.of(String.class)); + // hasTypeParameters() calls getTypeParameters() -> throws + assertThrows(RoasterMapperException.class, () -> RoasterMapper.mapInterfaceToTypeName(iface)); + } + + @Test + void resolveCodeTemplate_replacesStringAndTypePlaceholders() { + CodeTemplateDto code = new CodeTemplateDto(); + code.setCodeFormat("return $name:S, $type:T, $boxed:B, $raw:N;"); + code.addCodeArgument(new MethodCodeStringPlaceholder("name", "val")); + code.addCodeArgument(new MethodCodeTypePlaceholder("type", TypeNamePrimitive.INT)); + code.addCodeArgument(new MethodCodeTypePlaceholder("boxed", TypeNamePrimitive.INT)); + code.addCodeArgument(new MethodCodeStringPlaceholder("raw", "literal")); + + assertEquals("return \"val\", int, Integer, literal;", RoasterMapper.resolveCodeTemplate(code)); + } + + @Test + void resolveCodeTemplate_rewritesTrackedValueFactoryNames() { + CodeTemplateDto code = new CodeTemplateDto(); + code.setCodeFormat( + "TrackedValue.initialValue(x); TrackedValue.changedValue(y); TrackedValue.unsetValue();"); + assertEquals( + "initialValue(x); changedValue(y); unsetValue();", RoasterMapper.resolveCodeTemplate(code)); + } + + @Test + void resolveCodeTemplate_rejectsUnknownPlaceholderKinds() { + CodeTemplateDto code = new CodeTemplateDto(); + code.setCodeFormat("return $x:X;"); + code.addCodeArgument(new MethodCodePlaceholder("x", "v") {}); + assertThrows(RoasterMapperException.class, () -> RoasterMapper.resolveCodeTemplate(code)); + } + + @Test + void quote_escapesSpecialCharacters() { + assertEquals("\"a\\\"b\\\\c\\n\\t\"", RoasterMapper.quote("a\"b\\c\n\t")); + } + + @Test + void packageNameOf_stripsClassName() { + assertEquals("java.util", RoasterMapper.packageNameOf("java.util.List")); + assertEquals("", RoasterMapper.packageNameOf("List")); + } +} diff --git a/codegen-testing/pom.xml b/codegen-testing/pom.xml index ae4d610c..42c6558f 100644 --- a/codegen-testing/pom.xml +++ b/codegen-testing/pom.xml @@ -351,10 +351,13 @@ - + **/codegen/model/** + **/processor/model/** + **/enums/** **/*Exception.* + **/exceptions/** **/JavadocConstants.* diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java new file mode 100644 index 00000000..6d994ed4 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java @@ -0,0 +1,91 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; + +/** + * Look-ups for {@code javax.lang.model} elements during a live compilation — used inside {@link + * ProbeProcessor} probes to grab compiled test types, their fields, methods and parameters. + */ +public final class ElementTestUtils { + + private ElementTestUtils() {} + + /** + * Resolves a compiled type by qualified name. + * + * @param processingEnv the live processing environment + * @param qualifiedName fully qualified type name (e.g. {@code "test.Dto"}) + */ + public static TypeElement typeElement(ProcessingEnvironment processingEnv, String qualifiedName) { + return processingEnv.getElementUtils().getTypeElement(qualifiedName); + } + + /** Finds a field (or any {@link VariableElement} member) of a type by simple name. */ + public static VariableElement field(TypeElement type, String fieldName) { + return type.getEnclosedElements().stream() + .filter(VariableElement.class::isInstance) + .map(VariableElement.class::cast) + .filter(e -> e.getSimpleName().toString().equals(fieldName)) + .findFirst() + .orElseThrow(); + } + + /** + * Finds a method of a type by simple name; fails when several overloads exist — use {@link + * #method(TypeElement, String, int)} or {@link #parameter(ExecutableElement, int)} then. + */ + public static ExecutableElement method(TypeElement type, String methodName) { + return type.getEnclosedElements().stream() + .filter(ExecutableElement.class::isInstance) + .map(ExecutableElement.class::cast) + .filter(e -> e.getSimpleName().toString().equals(methodName)) + .findFirst() + .orElseThrow(); + } + + /** + * Finds the {@code overloadIndex}-th method of a type with the given simple name, in declaration + * order. + */ + public static ExecutableElement method(TypeElement type, String methodName, int overloadIndex) { + return type.getEnclosedElements().stream() + .filter(ExecutableElement.class::isInstance) + .map(ExecutableElement.class::cast) + .filter(e -> e.getSimpleName().toString().equals(methodName)) + .skip(overloadIndex) + .findFirst() + .orElseThrow(); + } + + /** Returns the {@code index}-th parameter of a method. */ + public static VariableElement parameter(ExecutableElement method, int index) { + return method.getParameters().get(index); + } +} diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java new file mode 100644 index 00000000..f4493d51 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java @@ -0,0 +1,83 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import java.util.Set; +import java.util.function.BiConsumer; +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.TypeElement; + +/** + * Test processor that runs a probe once inside a real compilation. + * + *

During the first processing round the probe receives the {@link RoundEnvironment} and the live + * {@link ProcessingEnvironment}, so it can look up {@code TypeElement}s of compiled test sources + * (see {@link ElementTestUtils}) and inspect them with real {@code javax.lang.model} types. Results + * are captured by the probe (e.g. into {@link java.util.concurrent.atomic.AtomicReference}s) and + * asserted by the test after compilation. + * + *

{@code
+ * AtomicReference found = new AtomicReference<>();
+ * Compilation compilation = CodegenTestUtils.createCompiler(
+ *     new ProbeProcessor((roundEnv, processingEnv) ->
+ *         found.set(ElementTestUtils.typeElement(processingEnv, "test.Dto"))))
+ *     .compile(CodegenTestUtils.forSource("package test; public class Dto {}"));
+ * }
+ */ +public class ProbeProcessor extends AbstractProcessor { + + private final BiConsumer probe; + private boolean ran; + + /** + * @param probe callback invoked exactly once in the first processing round + */ + public ProbeProcessor(BiConsumer probe) { + this.probe = probe; + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latestSupported(); + } + + @Override + public Set getSupportedAnnotationTypes() { + return Set.of("*"); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + if (ran || roundEnv.processingOver()) { + return false; + } + ran = true; + probe.accept(roundEnv, processingEnv); + return false; + } +} diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java new file mode 100644 index 00000000..0f8231f7 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java @@ -0,0 +1,124 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import java.io.StringWriter; +import java.io.Writer; +import java.net.URI; +import org.javahelpers.codegen.GeneratedSourceFile; +import org.javahelpers.codegen.GenerationEnvironment; +import org.javahelpers.codegen.GenerationIssueReporter; +import org.javahelpers.codegen.logging.NoOpPerformanceTracker; +import org.javahelpers.codegen.logging.PerformanceTracker; +import org.javahelpers.codegen.logging.ProcessingLogger; + +/** + * A {@link GenerationEnvironment} built only from codegen-core types for tests of code generators: + * issues surface on the logger as warnings, timing is not tracked, and generated sources are + * captured in memory for assertions. + * + *
{@code
+ * TestingGenerationEnvironment env = TestingGenerationEnvironment.create(logger);
+ * generator.generateClass(classDef, formatter);
+ * String source = env.generatedSource();
+ * }
+ */ +public final class TestingGenerationEnvironment implements GenerationEnvironment { + + private final ProcessingLogger logger; + private final boolean writable; + private InMemorySourceFile writtenFile; + + private TestingGenerationEnvironment(ProcessingLogger logger, boolean writable) { + this.logger = logger; + this.writable = writable; + } + + /** Environment whose {@code createSourceFile} captures the emitted source in memory. */ + public static TestingGenerationEnvironment create(ProcessingLogger logger) { + return new TestingGenerationEnvironment(logger, true); + } + + /** + * Environment whose {@code createSourceFile} returns {@code null} — the file-write step fails + * deterministically on it. + */ + public static TestingGenerationEnvironment createUnwritable(ProcessingLogger logger) { + return new TestingGenerationEnvironment(logger, false); + } + + @Override + public ProcessingLogger getLogger() { + return logger; + } + + @Override + public PerformanceTracker getPerformanceTracker() { + return new NoOpPerformanceTracker(); + } + + @Override + public GenerationIssueReporter getIssueReporter() { + return logger::warning; + } + + @Override + public GeneratedSourceFile createSourceFile(CharSequence qualifiedName) { + if (!writable) { + return null; + } + writtenFile = new InMemorySourceFile(qualifiedName); + return writtenFile; + } + + /** The source text written to the captured file. */ + public String generatedSource() { + return writtenFile.buffer.toString(); + } + + /** The URI the captured file was written to ({@code mem:///pkg/Name.java}). */ + public URI writtenUri() { + return writtenFile.toUri(); + } + + private static final class InMemorySourceFile implements GeneratedSourceFile { + private final String name; + private final StringWriter buffer = new StringWriter(); + + private InMemorySourceFile(CharSequence qualifiedName) { + this.name = qualifiedName.toString(); + } + + @Override + public URI toUri() { + return URI.create("mem:///" + name.replace('.', '/') + ".java"); + } + + @Override + public Writer openWriter() { + return buffer; + } + } +} diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java index d009554e..fe95e53b 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java @@ -70,4 +70,16 @@ void assertMessage_failsForMissingMessage() { assertThrows(AssertionError.class, () -> capturing.assertMessage("NOTE: never emitted")); } + + @Test + void assertMessageMatching_passesForPredicateMatch() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + + capturing.logger().warning("warn %s", "42"); + + capturing.assertMessageMatching(m -> m.contains("42"), "expected a message containing 42"); + assertThrows( + AssertionError.class, + () -> capturing.assertMessageMatching(m -> m.contains("99"), "missing")); + } } diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java index 41d90c21..8421c061 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java @@ -137,4 +137,46 @@ void loadGeneratedSource_failsForMissingFile() { assertThrows( AssertionError.class, () -> CodegenTestUtils.loadGeneratedSource(compilation, "Missing")); } + + @Test + void assertNoWarningContaining_passesWithoutMatchingWarning() { + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> + env.getMessager() + .printMessage(javax.tools.Diagnostic.Kind.WARNING, "a warning"))) + .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + + assertThat(compilation).succeeded(); + CodegenTestUtils.assertNoWarningContaining(compilation, "never emitted"); + assertThrows( + AssertionError.class, + () -> CodegenTestUtils.assertNoWarningContaining(compilation, "warning")); + } + + @Test + void readSource_readsForSourceContent() { + JavaFileObject file = CodegenTestUtils.forSource("package test;\npublic class Dto {}\n"); + assertEquals("package test;\npublic class Dto {}\n", CodegenTestUtils.readSource(file)); + } + + @Test + void printDiagnosticsAndSources_emitToSystemOut() { + Compilation compilation = + CodegenTestUtils.createCompiler(new EmittingProcessor()) + .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + + assertThat(compilation).succeeded(); + var captured = new java.io.ByteArrayOutputStream(); + var original = System.out; + try { + System.setOut(new java.io.PrintStream(captured)); + CodegenTestUtils.printDiagnostics(compilation); + CodegenTestUtils.printGeneratedSources(compilation); + } finally { + System.setOut(original); + } + assertTrue(captured.toString().contains("Generated")); + } } diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java new file mode 100644 index 00000000..d2fb5c56 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java @@ -0,0 +1,116 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ElementTestUtils.field; +import static org.javahelpers.codegen.testing.ElementTestUtils.method; +import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; +import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.google.testing.compile.Compilation; +import java.util.concurrent.atomic.AtomicReference; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import org.junit.jupiter.api.Test; + +/** Tests for {@link ElementTestUtils} against elements captured from a real compilation. */ +class ElementTestUtilsTest { + + private static final String DTO_SOURCE = + """ + package test; + public class Dto { + private String name; + public void setName(String name) { this.name = name; } + public void setName(Object name) {} + } + """; + + private static Compilation compile( + java.util.function.BiConsumer< + javax.annotation.processing.RoundEnvironment, + javax.annotation.processing.ProcessingEnvironment> + probe) { + return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + } + + @Test + void typeElement_findsCompiledType() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = compile((roundEnv, env) -> result.set(typeElement(env, "test.Dto"))); + + assertThat(compilation).succeeded(); + assertEquals("test.Dto", result.get().getQualifiedName().toString()); + } + + @Test + void field_findsDeclaredField() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile((roundEnv, env) -> result.set(field(typeElement(env, "test.Dto"), "name"))); + + assertThat(compilation).succeeded(); + assertEquals("name", result.get().getSimpleName().toString()); + assertEquals("java.lang.String", result.get().asType().toString()); + } + + @Test + void method_returnsFirstOverload() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile((roundEnv, env) -> result.set(method(typeElement(env, "test.Dto"), "setName"))); + + assertThat(compilation).succeeded(); + assertEquals("setName", result.get().getSimpleName().toString()); + } + + @Test + void method_overloadIndexSelectsLaterOverload() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile((roundEnv, env) -> result.set(method(typeElement(env, "test.Dto"), "setName", 1))); + + assertThat(compilation).succeeded(); + assertEquals("java.lang.Object", result.get().getParameters().get(0).asType().toString()); + } + + @Test + void parameter_returnsIndexedParameter() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + ExecutableElement mth = method(typeElement(env, "test.Dto"), "setName"); + result.set(parameter(mth, 0)); + }); + + assertThat(compilation).succeeded(); + assertEquals("name", result.get().getSimpleName().toString()); + } +} diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProbeProcessorTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProbeProcessorTest.java new file mode 100644 index 00000000..6bd197be --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProbeProcessorTest.java @@ -0,0 +1,67 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.google.testing.compile.Compilation; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.lang.model.SourceVersion; +import org.junit.jupiter.api.Test; + +/** Tests for {@link ProbeProcessor}. */ +class ProbeProcessorTest { + + @Test + void probe_runsOnceWithLiveEnvironment() { + AtomicInteger invocations = new AtomicInteger(); + AtomicReference seenEnv = + new AtomicReference<>(); + + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, processingEnv) -> { + invocations.incrementAndGet(); + seenEnv.set(processingEnv); + })) + .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + + assertThat(compilation).succeeded(); + assertEquals(1, invocations.get()); + assertNotNull(seenEnv.get()); + assertNotNull(seenEnv.get().getElementUtils()); + } + + @Test + void supportsAllAnnotationsAndLatestSourceVersion() { + ProbeProcessor processor = new ProbeProcessor((roundEnv, processingEnv) -> {}); + assertEquals(java.util.Set.of("*"), processor.getSupportedAnnotationTypes()); + assertEquals(SourceVersion.latestSupported(), processor.getSupportedSourceVersion()); + } +} diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java index 7f272f3f..bb7ef9a0 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.testing; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; @@ -54,4 +55,15 @@ void builder_accumulatesOptions() { ProcessingEnvironmentStub.builder().put("a", "1").put("b", "2").build(); assertEquals(Map.of("a", "1", "b", "2"), env.getOptions()); } + + @Test + void unsupportedAccessors_returnNull() { + ProcessingEnvironment env = ProcessingEnvironmentStub.createEmpty(); + assertNull(env.getMessager()); + assertNull(env.getFiler()); + assertNull(env.getElementUtils()); + assertNull(env.getTypeUtils()); + assertEquals(javax.lang.model.SourceVersion.latestSupported(), env.getSourceVersion()); + assertEquals(java.util.Locale.getDefault().getLanguage(), env.getLocale().getLanguage()); + } } diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java index 61c00ae0..e5ee1492 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java @@ -31,6 +31,9 @@ import static org.javahelpers.codegen.testing.ProcessorAsserts.notContains; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.google.testing.compile.Compilation; +import javax.lang.model.element.TypeElement; +import javax.tools.Diagnostic; import org.junit.jupiter.api.Test; /** Unit tests for {@link ProcessorAsserts} — asserting the assertion helpers themselves. */ @@ -80,4 +83,93 @@ void assertNormalizedEquals_failsOnContentDifference() { AssertionError.class, () -> assertNormalizedEquals("public class Foo {}", "public class Bar {}", "mismatch")); } + + @Test + void assertNotesInOrder_matchesEmittedNotesExactly() { + Compilation compilation = + compileWithDiagnostics( + (env, dto) -> { + env.getMessager().printMessage(Diagnostic.Kind.NOTE, "first note"); + env.getMessager().printMessage(Diagnostic.Kind.NOTE, "second note"); + }); + + ProcessorAsserts.assertNotesInOrder(compilation, "first note", "second note"); + assertThrows( + AssertionError.class, () -> ProcessorAsserts.assertNotesInOrder(compilation, "first note")); + assertThrows( + AssertionError.class, + () -> ProcessorAsserts.assertNotesInOrder(compilation, "first note", "other")); + } + + @Test + void assertDiagnosticsHaveSourcePosition_passesForElementAttachedWarnings() { + Compilation compilation = + compileWithDiagnostics( + (env, dto) -> + env.getMessager().printMessage(Diagnostic.Kind.WARNING, "warning on element", dto)); + + ProcessorAsserts.assertDiagnosticsHaveSourcePosition( + compilation, Diagnostic.Kind.WARNING, "warning on element"); + } + + @Test + void assertDiagnosticsHaveSourcePosition_failsForElementLessWarnings() { + Compilation compilation = + compileWithDiagnostics( + (env, dto) -> + env.getMessager().printMessage(Diagnostic.Kind.WARNING, "floating warning")); + + assertThrows( + AssertionError.class, + () -> + ProcessorAsserts.assertDiagnosticsHaveSourcePosition( + compilation, Diagnostic.Kind.WARNING, "floating warning")); + assertThrows( + AssertionError.class, + () -> + ProcessorAsserts.assertDiagnosticsHaveSourcePosition( + compilation, Diagnostic.Kind.WARNING, "not emitted")); + } + + @Test + void assertDiagnosticsHaveNoSourcePosition_passesForElementLessWarnings() { + Compilation compilation = + compileWithDiagnostics( + (env, dto) -> + env.getMessager().printMessage(Diagnostic.Kind.WARNING, "floating warning")); + + ProcessorAsserts.assertDiagnosticsHaveNoSourcePosition( + compilation, Diagnostic.Kind.WARNING, "floating warning"); + } + + @Test + void assertNoSourceGenerated_failsWhenFileExists() { + Compilation compilation = + compileWithDiagnostics( + (env, dto) -> { + try { + var file = env.getFiler().createSourceFile("test.Generated"); + try (var writer = file.openWriter()) { + writer.write("package test;\npublic class Generated {}\n"); + } + } catch (java.io.IOException e) { + throw new IllegalStateException(e); + } + }); + + ProcessorAsserts.assertNoSourceGenerated(compilation, "Other", "no other file expected"); + assertThrows( + AssertionError.class, + () -> ProcessorAsserts.assertNoSourceGenerated(compilation, "Generated", "boom")); + } + + private static Compilation compileWithDiagnostics( + java.util.function.BiConsumer + emitter) { + return CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> + emitter.accept(env, ElementTestUtils.typeElement(env, "test.Dto")))) + .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + } } diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/TestingGenerationEnvironmentTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/TestingGenerationEnvironmentTest.java new file mode 100644 index 00000000..9f042ea8 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/TestingGenerationEnvironmentTest.java @@ -0,0 +1,77 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.Writer; +import org.javahelpers.codegen.GeneratedSourceFile; +import org.javahelpers.codegen.logging.NoOpPerformanceTracker; +import org.junit.jupiter.api.Test; + +/** Tests for {@link TestingGenerationEnvironment}. */ +class TestingGenerationEnvironmentTest { + + @Test + void create_capturesWrittenSourceInMemory() throws Exception { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); + + GeneratedSourceFile file = env.createSourceFile("com.example.Generated"); + try (Writer writer = file.openWriter()) { + writer.write("public class Generated {}"); + } + + assertEquals("public class Generated {}", env.generatedSource()); + assertEquals("mem:///com/example/Generated.java", env.writtenUri().toString()); + } + + @Test + void createUnwritable_returnsNullSourceFile() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + TestingGenerationEnvironment env = + TestingGenerationEnvironment.createUnwritable(capturing.logger()); + + assertNull(env.createSourceFile("com.example.Generated")); + } + + @Test + void exposesLoggerNoOpTrackerAndReporter() { + CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); + + assertSame(capturing.logger(), env.getLogger()); + assertInstanceOf(NoOpPerformanceTracker.class, env.getPerformanceTracker()); + + env.getIssueReporter().report("issue %s", "one"); + assertTrue( + capturing.messages().stream().anyMatch(m -> m.contains("issue one")), + "issue reporter routes to the logger as warning"); + } +} diff --git a/core/pom.xml b/core/pom.xml index 13d659ce..3b3cc611 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -82,6 +82,7 @@ 3.2.8 3.2.0 3.22.0 + 3.6.0 0.8.16 @@ -110,6 +111,13 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + ${plugin.maven.surefire.version} + + com.spotify.fmt @@ -301,6 +309,19 @@ report + + + + **/codegen/model/** + **/processor/model/** + **/enums/** + + **/*Exception.* + **/exceptions/** + + **/JavadocConstants.* + + diff --git a/processor/pom.xml b/processor/pom.xml index 7bcc8de5..11be54e5 100644 --- a/processor/pom.xml +++ b/processor/pom.xml @@ -374,9 +374,12 @@ - + + **/codegen/model/** **/processor/model/** + **/enums/** + **/*Exception.* **/exceptions/** **/JavadocConstants.* diff --git a/simple-processor/pom.xml b/simple-processor/pom.xml index e313f9f5..3e9adf07 100644 --- a/simple-processor/pom.xml +++ b/simple-processor/pom.xml @@ -339,10 +339,13 @@ - + **/codegen/model/** + **/processor/model/** + **/enums/** **/*Exception.* + **/exceptions/** **/JavadocConstants.* diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java index a9c96b37..af1499c4 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java @@ -25,6 +25,8 @@ package org.javahelpers.codegen.analysis; import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ElementTestUtils.field; +import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -35,60 +37,32 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; -import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; +import javax.tools.JavaFileObject; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.processing.AnnotationProcessingContext; import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** Unit tests for {@link FieldAnnotationExtractor} against elements captured from a compilation. */ class FieldAnnotationExtractorTest { - private static class ProbeProcessor extends AbstractProcessor { - private final BiConsumer probe; - private boolean ran; - - ProbeProcessor(BiConsumer probe) { - this.probe = probe; - } - - @Override - public SourceVersion getSupportedSourceVersion() { - return SourceVersion.latestSupported(); - } - - @Override - public Set getSupportedAnnotationTypes() { - return Set.of("*"); - } - - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { - if (ran || roundEnv.processingOver()) { - return false; - } - ran = true; - probe.accept( - roundEnv, - new AnnotationProcessingContext( - CapturingProcessingLogger.create().logger(), processingEnv)); - return false; - } + private static TypeMappingContext context(ProcessingEnvironment processingEnv) { + return new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), processingEnv); } - private static VariableElement field(TypeElement dto, String fieldName) { - return dto.getEnclosedElements().stream() - .filter(VariableElement.class::isInstance) - .map(VariableElement.class::cast) - .filter(e -> e.getSimpleName().toString().equals(fieldName)) - .findFirst() - .orElseThrow(); + private static Compilation compile( + BiConsumer probe, String... sources) { + JavaFileObject[] files = + java.util.Arrays.stream(sources) + .map(CodegenTestUtils::forSource) + .toArray(JavaFileObject[]::new); + return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)).compile(files); } private static final String DTO_SOURCE = @@ -105,35 +79,32 @@ public class Dto { } """; - private static final String ANNOTATION_SOURCES = + private static final String DEFAULT_ANNOTATION_SOURCE = """ package test; public @interface Default { String value(); } """; - private static final String NONNULL_SOURCE = + private static final String NONNULL_ANNOTATION_SOURCE = """ package test; public @interface NonNull {} """; - private Compilation compile(BiConsumer probe) { - return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)) - .compile( - CodegenTestUtils.forSource(DTO_SOURCE), - CodegenTestUtils.forSource(ANNOTATION_SOURCES), - CodegenTestUtils.forSource(NONNULL_SOURCE)); + private Compilation compileDto(BiConsumer probe) { + return compile(probe, DTO_SOURCE, DEFAULT_ANNOTATION_SOURCE, NONNULL_ANNOTATION_SOURCE); } @Test void extractDeprecatedAnnotation_findsDeprecatedField() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( - (roundEnv, ctx) -> + compileDto( + (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractDeprecatedAnnotation( - field(ctx.getTypeElement("test.Dto"), "legacy"), ctx))); + field(typeElement(processingEnv, "test.Dto"), "legacy"), + context(processingEnv)))); assertThat(compilation).succeeded(); assertTrue(result.get().isPresent()); @@ -148,11 +119,12 @@ void extractDeprecatedAnnotation_findsDeprecatedField() { void extractDeprecatedAnnotation_emptyForPlainField() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( - (roundEnv, ctx) -> + compileDto( + (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractDeprecatedAnnotation( - field(ctx.getTypeElement("test.Dto"), "plain"), ctx))); + field(typeElement(processingEnv, "test.Dto"), "plain"), + context(processingEnv)))); assertThat(compilation).succeeded(); assertTrue(result.get().isEmpty()); @@ -162,11 +134,12 @@ void extractDeprecatedAnnotation_emptyForPlainField() { void extractAnnotations_returnsMemberValues() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( - (roundEnv, ctx) -> + compileDto( + (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotations( - field(ctx.getTypeElement("test.Dto"), "mode"), ctx))); + field(typeElement(processingEnv, "test.Dto"), "mode"), + context(processingEnv)))); assertThat(compilation).succeeded(); assertEquals(1, result.get().size()); @@ -180,9 +153,9 @@ void hasNonNullConstraint_detectsNonNullAnnotation() { AtomicReference nonNull = new AtomicReference<>(); AtomicReference plain = new AtomicReference<>(); Compilation compilation = - compile( - (roundEnv, ctx) -> { - TypeElement dto = ctx.getTypeElement("test.Dto"); + compileDto( + (roundEnv, processingEnv) -> { + var dto = typeElement(processingEnv, "test.Dto"); nonNull.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "required"))); plain.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "plain"))); }); @@ -196,11 +169,11 @@ void hasNonNullConstraint_detectsNonNullAnnotation() { void extractAnnotationValue_matchesAnnotationBySimpleName() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( - (roundEnv, ctx) -> + compileDto( + (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotationValue( - field(ctx.getTypeElement("test.Dto"), "mode"), Set.of("Default")))); + field(typeElement(processingEnv, "test.Dto"), "mode"), Set.of("Default")))); assertThat(compilation).succeeded(); assertEquals(Optional.of("GENERAL"), result.get()); @@ -213,6 +186,14 @@ void formatDefaultExpression_quotesStringValues() { FieldAnnotationExtractor.formatDefaultExpression("GENERAL", TypeName.of(String.class))); } + @Test + void formatDefaultExpression_quotesCharValues() { + assertEquals( + "'A'", + FieldAnnotationExtractor.formatDefaultExpression( + "A", org.javahelpers.codegen.model.type.TypeNamePrimitive.CHAR)); + } + @Test void formatDefaultExpression_qualifiesSimpleEnumConstant() { TypeName enumType = new TypeName("test", "ItemCondition"); diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/GeneratedTypesTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/GeneratedTypesTest.java new file mode 100644 index 00000000..c678d677 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/GeneratedTypesTest.java @@ -0,0 +1,66 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.analysis; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.javahelpers.codegen.model.type.TypeName; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link GeneratedTypes}. */ +class GeneratedTypesTest { + + @Test + void add_registersGeneratedTypeAndFindsIt() { + GeneratedTypes types = new GeneratedTypes(); + TypeName source = TypeName.of(String.class); + TypeName generated = TypeName.of(StringBuilder.class); + assertTrue(types.add(source, generated)); + assertEquals(generated, types.findGenerated(source).orElseThrow()); + } + + @Test + void add_rejectsDuplicateTarget() { + GeneratedTypes types = new GeneratedTypes(); + TypeName source = TypeName.of(String.class); + assertTrue(types.add(source, TypeName.of(StringBuilder.class))); + assertFalse(types.add(source, TypeName.of(StringBuffer.class))); + } + + @Test + void findGenerated_emptyWhenUnknown() { + assertTrue(new GeneratedTypes().findGenerated(TypeName.of(String.class)).isEmpty()); + } + + @Test + void clear_removesAllMappings() { + GeneratedTypes types = new GeneratedTypes(); + types.add(TypeName.of(String.class), TypeName.of(StringBuilder.class)); + types.clear(); + assertTrue(types.findGenerated(TypeName.of(String.class)).isEmpty()); + } +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java index c7ed3033..e5fc9cb7 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -24,298 +24,590 @@ package org.javahelpers.codegen.analysis; -import static org.junit.jupiter.api.Assertions.*; - -import java.lang.annotation.Annotation; +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ElementTestUtils.field; +import static org.javahelpers.codegen.testing.ElementTestUtils.method; +import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; +import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.testing.compile.Compilation; import java.util.List; -import java.util.Set; -import java.util.stream.Stream; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.Element; -import javax.lang.model.element.ElementKind; -import javax.lang.model.element.ElementVisitor; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; -import javax.lang.model.element.Name; -import javax.lang.model.element.VariableElement; -import javax.lang.model.type.TypeMirror; +import javax.lang.model.element.TypeElement; +import javax.tools.JavaFileObject; +import org.javahelpers.codegen.analysis.JavaLangAnalyser.ReadableProperty; +import org.javahelpers.codegen.analysis.testannotations.Tag; +import org.javahelpers.codegen.analysis.testannotations.Tags; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.processing.AnnotationProcessingContext; +import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -/** Unit tests for {@link JavaLangAnalyser}. */ +/** Unit tests for {@link JavaLangAnalyser} against elements captured from a real compilation. */ class JavaLangAnalyserTest { - private static class TestVariableElement implements VariableElement { - private final String name; - - TestVariableElement(String name) { - this.name = name; - } - - @Override - public Name getSimpleName() { - return new Name() { - @Override - public String toString() { - return name; - } - - @Override - public boolean contentEquals(CharSequence cs) { - return name.contentEquals(cs); - } - - @Override - public int length() { - return name.length(); - } - - @Override - public char charAt(int index) { - return name.charAt(index); - } - - @Override - public CharSequence subSequence(int start, int end) { - return name.subSequence(start, end); - } - }; - } - - // Required methods with default implementations - @Override - public Object getConstantValue() { - return null; - } - - @Override - public R accept(ElementVisitor v, P p) { - return null; - } - - @Override - public Element getEnclosingElement() { - return null; - } - - @Override - public List getEnclosedElements() { - return List.of(); - } - - @Override - public TypeMirror asType() { - return null; - } - - @Override - public ElementKind getKind() { - return ElementKind.PARAMETER; - } - - @Override - public Set getModifiers() { - return Set.of(); - } - - @Override - public List getAnnotationMirrors() { - return List.of(); - } - - @Override - public A getAnnotation(Class annotationType) { - return null; - } - - @Override - public A[] getAnnotationsByType(Class annotationType) { - return null; - } + private static final String DTO_SOURCE = + """ + package test; + import org.javahelpers.codegen.analysis.testannotations.Tag; + public class Dto { + private String name; + private boolean active; + private int count; + public Dto() {} + public Dto(String name) {} + public String getName() { return name; } + public boolean isActive() { return active; } + public void setName(String name) { this.name = name; } + public void setName(Object name) {} + private void hidden() {} + public static String staticUtil(String in) { return in; } + public static void staticVoid(String in) {} + public T generic(T in) { return in; } + public void risky() throws java.io.IOException {} + @Deprecated public void old() {} + @Tag("a") public void singleTag() {} + @Tag("a") @Tag("b") public void tagged() {} + @org.javahelpers.codegen.analysis.testannotations.Tags({@Tag("c"), @Tag("d")}) + public void wrapped() {} + } + """; + + private static final String RECORD_SOURCE = + """ + package test; + public record Point(int x, int y) {} + """; + + private static final String INTERFACES_SOURCE = + """ + package test; + public class Interfaces { + public interface Single { void run(); } + public interface Two { void a(); void b(); } + @FunctionalInterface + public interface Explicit { void apply(); default void extra() {} } + } + """; + + private static final String CTOR_SOURCE = + """ + package test; + public class TwoCtor { + public TwoCtor() {} + public TwoCtor(String a) {} + @Deprecated + public TwoCtor(String a, int b) {} + } + """; + + private static AnnotationProcessingContext context(ProcessingEnvironment processingEnv) { + return new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), processingEnv); } - private final VariableElement parameter = new TestVariableElement("testParam"); - - private static Stream extractParamJavaDocNullCases() { - VariableElement param = new TestVariableElement("testParam"); - return Stream.of( - Arguments.of("JavaDoc is null", null, param), - Arguments.of("Parameter is null", "Some Javadoc", null), - Arguments.of( - "Param tag not found", - "/**\n * Some method description.\n * @param otherParam some other parameter\n * @return something\n */", - param), - Arguments.of( - "Empty param doc", - "/**\n * Some method description.\n * @param testParam\n * @return something\n */", - param), - Arguments.of( - "Whitespace only param doc", - "/**\n * Some method description.\n * @param testParam \n * @return something\n */", - param)); + private static Compilation compile( + BiConsumer probe, String... sources) { + JavaFileObject[] files = + java.util.Arrays.stream(sources) + .map(CodegenTestUtils::forSource) + .toArray(JavaFileObject[]::new); + return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)).compile(files); } - @ParameterizedTest(name = "{0}") - @MethodSource("extractParamJavaDocNullCases") - void extractParamJavaDoc_shouldReturnNull( - String testCase, String javaDoc, VariableElement param) { - assertNull(JavaLangAnalyser.extractParamJavaDoc(javaDoc, param)); + private static Compilation compileDto(BiConsumer probe) { + return compile(probe, DTO_SOURCE); } @Test - void extractParamJavaDoc_shouldExtractSingleLineParamDoc() { - String javaDoc = - "/**\n * Some method description.\n * @param testParam this is a test parameter\n * @return something\n */"; - assertEquals( - "this is a test parameter", JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + void isNoMethodOfObjectClass_filtersObjectMethods() { + AtomicReference onObject = new AtomicReference<>(); + AtomicReference onOwn = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + onObject.set( + JavaLangAnalyser.isNoMethodOfObjectClass( + method(typeElement(env, "java.lang.Object"), "toString"), ctx)); + onOwn.set(JavaLangAnalyser.isNoMethodOfObjectClass(method(dto, "getName"), ctx)); + }); + assertThat(compilation).succeeded(); + assertFalse(onObject.get()); + assertTrue(onOwn.get()); } @Test - void extractParamJavaDoc_shouldExtractMultiLineParamDoc() { - String javaDoc = - "/**\n * Some method description.\n * @param testParam this is a test parameter\n * that spans multiple lines\n * with additional details\n * @return something\n */"; - assertEquals( - "this is a test parameter that spans multiple lines with additional details", - JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + void findSetterMethods_returnsSettersSortedByNameAndParameterType() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set( + JavaLangAnalyser.findSetterMethods(typeElement(env, "test.Dto"), ctx).stream() + .map(m -> m.getSimpleName() + "(" + m.getParameters().get(0).asType() + ")") + .toList()); + }); + assertThat(compilation).succeeded(); + assertEquals(List.of("setName(java.lang.Object)", "setName(java.lang.String)"), result.get()); } @Test - void extractParamJavaDoc_shouldStopAtNextTag() { - String javaDoc = - "/**\n * Some method description.\n * @param testParam this is a test parameter\n * @return something\n * @since 1.0\n */"; - assertEquals( - "this is a test parameter", JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + void hasNotAnnotation_checksForAnnotationPresence() { + AtomicReference deprecated = new AtomicReference<>(); + AtomicReference plain = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + deprecated.set( + JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "old"))); + plain.set( + JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "getName"))); + }); + assertThat(compilation).succeeded(); + assertFalse(deprecated.get()); + assertTrue(plain.get()); } @Test - void extractParamJavaDoc_shouldHandleWindowsLineEndings() { - String javaDoc = - "/**\r\n * Some method description.\r\n * @param testParam this is a test parameter\r\n * @return something\r\n */"; + void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { + AtomicReference> results = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + results.set( + List.of( + JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "getName")), + JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "risky")), + // setName returns void -> no return value; getName returns String + JavaLangAnalyser.hasNoReturnValue(method(dto, "setName")), + JavaLangAnalyser.hasNoReturnValue(method(dto, "getName")), + JavaLangAnalyser.isNotPrivate(method(dto, "getName")), + JavaLangAnalyser.isNotPrivate(method(dto, "hidden")), + JavaLangAnalyser.isNotStatic(method(dto, "getName")), + JavaLangAnalyser.isNotStatic(method(dto, "staticUtil")), + JavaLangAnalyser.hasGenericTypes(method(dto, "generic")), + JavaLangAnalyser.hasGenericTypes(method(dto, "getName")), + JavaLangAnalyser.isSetterForField(method(dto, "setName")), + JavaLangAnalyser.isSetterForField(method(dto, "getName")))); + }); + assertThat(compilation).succeeded(); assertEquals( - "this is a test parameter", JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + List.of(true, false, true, false, true, false, true, false, true, false, true, false), + results.get()); } @Test - void extractParamJavaDoc_shouldStopAtEmptyLine() { - String javaDoc = - "/**\n * @param testParam this is a test parameter\n *\n * Some additional description\n * @return something\n */"; - assertEquals( - "this is a test parameter", JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + void hasEmptyConstructor_detectsAccessibleNoArgConstructor() { + AtomicReference dto = new AtomicReference<>(); + AtomicReference ctor = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + dto.set(JavaLangAnalyser.hasEmptyConstructor(typeElement(env, "test.Dto"), ctx)); + // TwoCtor has public no-arg ctor -> true as well + ctor.set(JavaLangAnalyser.hasEmptyConstructor(typeElement(env, "test.TwoCtor"), ctx)); + }, + DTO_SOURCE, + CTOR_SOURCE); + assertThat(compilation).succeeded(); + assertTrue(dto.get()); + assertTrue(ctor.get()); } @Test - void extractParamJavaDoc_shouldHandleEmptyParamTag() { - String javaDoc = "/**\n * @param testParam\n * @return something\n */"; - assertNull(JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + void findAnnotation_locatesDirectAnnotation() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> + result.set( + JavaLangAnalyser.findAnnotation( + method(typeElement(env, "test.Dto"), "old"), Deprecated.class))); + assertThat(compilation).succeeded(); + assertTrue(result.get().isPresent()); } @Test - void extractParamJavaDoc_shouldHandleWhitespaceOnlyParamTag() { - String javaDoc = - "/**\n * @param testParam \t\n * @return something\n */"; - assertNull(JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + void findAnnotationInstances_unwrapsRepeatableContainerAndDirect() { + AtomicReference directCount = new AtomicReference<>(); + AtomicReference containerCount = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + directCount.set( + JavaLangAnalyser.findAnnotationInstances( + method(dto, "tagged"), Tag.class, Tags.class, ctx) + .size()); + containerCount.set( + JavaLangAnalyser.findAnnotationInstances( + method(dto, "wrapped"), Tag.class, Tags.class, ctx) + .size()); + }, + DTO_SOURCE); + assertThat(compilation).succeeded(); + assertEquals(2, directCount.get()); + assertEquals(2, containerCount.get()); } @Test - void extractParamJavaDoc_shouldAddSpaceBetweenLines() { - String javaDoc = - "/**\n * @param testParam first line\n * second line\n * third line\n * @return something\n */"; - assertEquals( - "first line second line third line", - JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); + void findAnnotationAttributeAndArray_readValues() { + AtomicReference value = new AtomicReference<>(); + AtomicReference arraySize = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + AnnotationMirror tag = + JavaLangAnalyser.findAnnotation(method(dto, "singleTag"), Tag.class) + .orElseThrow(); + value.set( + JavaLangAnalyser.findAnnotationAttribute(tag, "value", ctx) + .map(AnnotationValue::getValue) + .map(Object::toString) + .orElse(null)); + AnnotationMirror tags = + JavaLangAnalyser.findAnnotation(method(dto, "wrapped"), Tags.class).orElse(null); + if (tags != null) { + arraySize.set( + JavaLangAnalyser.findAnnotationAttributeArray(tags, "value", ctx).size()); + } + }); + assertThat(compilation).succeeded(); + assertEquals("a", value.get()); + assertEquals(2, arraySize.get()); } @Test - void findGetterForField_shouldReturnEmpty_whenDtoTypeIsNull() { - assertTrue(JavaLangAnalyser.findGetterForField(null, "fieldName", null, null).isEmpty()); + void resolveTypeElement_resolvesAnnotationValueToTypeElement() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + AnnotationMirror tag = + JavaLangAnalyser.findAnnotation(method(dto, "singleTag"), Tag.class) + .orElseThrow(); + // value is a string, not a TypeMirror -> empty + AnnotationValue val = + JavaLangAnalyser.findAnnotationAttribute(tag, "value", ctx).orElseThrow(); + result.set(JavaLangAnalyser.resolveTypeElement(val, ctx)); + }); + assertThat(compilation).succeeded(); + assertTrue(result.get().isEmpty()); } @Test - void findGetterForField_shouldReturnEmpty_whenFieldNameIsNull() { - assertTrue(JavaLangAnalyser.findGetterForField(null, null, null, null).isEmpty()); + void findMethodsStatic_filtersBySignatureAndStaticModifier() { + AtomicReference> single = new AtomicReference<>(); + AtomicReference> voidReturn = new AtomicReference<>(); + AtomicReference> allStatic = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + single.set( + JavaLangAnalyser.findMethodsStatic( + dto, TypeName.of(String.class), TypeName.of(String.class), ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + voidReturn.set( + JavaLangAnalyser.findMethodsStatic( + dto, List.of(TypeName.of(String.class)), null, ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + allStatic.set( + JavaLangAnalyser.findMethodsStatic(dto, List.of(TypeName.of(String.class)), ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + }); + assertThat(compilation).succeeded(); + assertEquals(List.of("staticUtil"), single.get()); + assertEquals(List.of("staticVoid"), voidReturn.get()); + assertEquals(List.of("staticUtil", "staticVoid"), allStatic.get()); } @Test - void findGetterForField_shouldReturnEmpty_whenFieldTypeMirrorIsNull() { - assertTrue(JavaLangAnalyser.findGetterForField(null, "fieldName", null, null).isEmpty()); + void findMethods_matchesByParametersAndReturnType() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + result.set( + JavaLangAnalyser.findMethods(dto, List.of(), TypeName.of(String.class), ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + }); + assertThat(compilation).succeeded(); + assertEquals(List.of("toString", "getName"), result.get()); } @Test - void extractDeprecatedJavaDoc_shouldReturnNull_whenJavaDocHasNoDeprecatedTag() { - String javaDoc = - """ - /** - * Some method description. - * @param name the name - * @return something - */ - """; - assertNull(JavaLangAnalyser.extractDeprecatedJavaDoc(javaDoc)); + void findMethodWithoutParameters_matchesNameAndModifiers() { + AtomicReference> found = new AtomicReference<>(); + AtomicReference> missing = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + found.set( + JavaLangAnalyser.findMethodWithoutParameters(dto, "getName", Modifier.PUBLIC)); + missing.set( + JavaLangAnalyser.findMethodWithoutParameters(dto, "setName", Modifier.PUBLIC)); + }); + assertThat(compilation).succeeded(); + assertTrue(found.get().isPresent()); + assertTrue(missing.get().isEmpty()); } @Test - void extractDeprecatedJavaDoc_shouldReturnNull_whenJavaDocIsNull() { - assertNull(JavaLangAnalyser.extractDeprecatedJavaDoc(null)); + void findReadableProperties_combinesRecordComponentsGettersAndFields() { + AtomicReference> recordProps = new AtomicReference<>(); + AtomicReference> dtoProps = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + recordProps.set( + JavaLangAnalyser.findReadableProperties(typeElement(env, "test.Point"), ctx) + .stream() + .map(ReadableProperty::name) + .toList()); + dtoProps.set( + JavaLangAnalyser.findReadableProperties(typeElement(env, "test.Dto"), ctx) + .stream() + .map(ReadableProperty::name) + .toList()); + }, + RECORD_SOURCE, + DTO_SOURCE); + assertThat(compilation).succeeded(); + assertEquals(List.of("x", "y"), recordProps.get()); + // getters are readable; private fields without accessors are not + assertTrue(dtoProps.get().containsAll(List.of("name", "active"))); } @Test - void extractDeprecatedJavaDoc_shouldExtractSingleLineDeprecatedText() { - String javaDoc = - """ - /** - * Some method description. - * @deprecated use {@link #newMethod} instead - * @return something - */ - """; - assertEquals( - "use {@link #newMethod} instead", JavaLangAnalyser.extractDeprecatedJavaDoc(javaDoc)); + void findSingleParameterMethods_returnsNonStaticOneParamMethods() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set( + JavaLangAnalyser.findSingleParameterMethods(typeElement(env, "test.Dto"), ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .distinct() + .sorted() + .toList()); + }); + assertThat(compilation).succeeded(); + // setName overloads + generic — staticUtil excluded (static) + assertEquals(List.of("generic", "setName"), result.get()); + } + + @Test + void hasConstructorAccepting_matchesParameterType() { + AtomicReference matching = new AtomicReference<>(); + AtomicReference nonMatching = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement ctor = typeElement(env, "test.TwoCtor"); + matching.set( + JavaLangAnalyser.hasConstructorAccepting(ctor, TypeName.of(String.class), ctx)); + nonMatching.set( + JavaLangAnalyser.hasConstructorAccepting(ctor, TypeName.of(Integer.class), ctx)); + }, + CTOR_SOURCE); + assertThat(compilation).succeeded(); + assertTrue(matching.get()); + assertFalse(nonMatching.get()); } @Test - void extractDeprecatedJavaDoc_shouldExtractMultiLineDeprecatedText() { - String javaDoc = + void isFunctionalInterface_detectsAnnotatedAndSingleAbstractMethod() { + AtomicReference> results = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + results.set( + List.of( + JavaLangAnalyser.isFunctionalInterface( + typeElement(env, "test.Interfaces.Single")), + JavaLangAnalyser.isFunctionalInterface( + typeElement(env, "test.Interfaces.Two")), + JavaLangAnalyser.isFunctionalInterface( + typeElement(env, "test.Interfaces.Explicit")), + JavaLangAnalyser.isFunctionalInterface(typeElement(env, "test.Dto")), + JavaLangAnalyser.isFunctionalInterface(null))); + }, + INTERFACES_SOURCE, + DTO_SOURCE); + assertThat(compilation).succeeded(); + assertEquals(List.of(true, false, true, false, false), results.get()); + } + + @Test + void extractParamJavaDoc_readsParamTextWithContinuation() { + AtomicReference mth = new AtomicReference<>(); + Compilation compilation = + compileDto((roundEnv, env) -> mth.set(method(typeElement(env, "test.Dto"), "setName"))); + assertThat(compilation).succeeded(); + String javadoc = """ - /** - * Some method description. - * @deprecated use {@link #newMethod} instead - * and migrate all callers - * @return something - */ + Sets the name. + @param name the name + continued description + @return nothing """; assertEquals( - "use {@link #newMethod} instead and migrate all callers", - JavaLangAnalyser.extractDeprecatedJavaDoc(javaDoc)); + "the name continued description", + JavaLangAnalyser.extractParamJavaDoc(javadoc, parameter(mth.get(), 0))); + assertNull(JavaLangAnalyser.extractParamJavaDoc(null, parameter(mth.get(), 0))); + assertNull(JavaLangAnalyser.extractParamJavaDoc(javadoc, null)); } @Test - void findFieldElement_shouldReturnEmpty_whenClassElementIsNull() { - assertTrue(JavaLangAnalyser.findFieldElement(null, "fieldName").isEmpty()); + void extractDeprecatedJavaDoc_readsDeprecatedTagText() { + String javadoc = "Old method.\n@deprecated use {@code fresh()} instead\n@return x"; + assertEquals("use {@code fresh()} instead", JavaLangAnalyser.extractDeprecatedJavaDoc(javadoc)); + assertNull(JavaLangAnalyser.extractDeprecatedJavaDoc(null)); + assertNull(JavaLangAnalyser.extractDeprecatedJavaDoc("no tags here")); } @Test - void findFieldElement_shouldReturnEmpty_whenFieldNameIsNull() { - assertTrue(JavaLangAnalyser.findFieldElement(null, null).isEmpty()); + void findGetterForField_matchesRecordBooleanAndStandardAccessors() { + AtomicReference> byGet = new AtomicReference<>(); + AtomicReference> byIs = new AtomicReference<>(); + AtomicReference> absent = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + byGet.set( + JavaLangAnalyser.findGetterForField( + dto, "name", field(dto, "name").asType(), ctx)); + byIs.set( + JavaLangAnalyser.findGetterForField( + dto, "active", field(dto, "active").asType(), ctx)); + absent.set( + JavaLangAnalyser.findGetterForField( + dto, "count", field(dto, "count").asType(), ctx)); + }); + assertThat(compilation).succeeded(); + assertTrue(byGet.get().isPresent()); + assertTrue(byIs.get().isPresent()); + assertTrue(absent.get().isEmpty()); } @Test - void findRecordComponent_shouldReturnEmpty_whenTypeElementIsNull() { - assertTrue(JavaLangAnalyser.findRecordComponent(null, "componentName").isEmpty()); + void findFieldElementAndRecordComponent_locateMembers() { + AtomicReference fieldFound = new AtomicReference<>(); + AtomicReference fieldMissing = new AtomicReference<>(); + AtomicReference compFound = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + fieldFound.set(JavaLangAnalyser.findFieldElement(dto, "name").isPresent()); + fieldMissing.set(JavaLangAnalyser.findFieldElement(dto, "missing").isEmpty()); + compFound.set( + JavaLangAnalyser.findRecordComponent(typeElement(env, "test.Point"), "x") + .isPresent()); + }, + DTO_SOURCE, + RECORD_SOURCE); + assertThat(compilation).succeeded(); + assertTrue(fieldFound.get()); + assertTrue(fieldMissing.get()); + assertTrue(compFound.get()); } @Test - void findRecordComponent_shouldReturnEmpty_whenComponentNameIsNull() { - assertTrue(JavaLangAnalyser.findRecordComponent(null, null).isEmpty()); + void findSetterForField_matchesVoidSingleParamSetter() { + AtomicReference> found = new AtomicReference<>(); + AtomicReference> missing = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + found.set(JavaLangAnalyser.findSetterForField(dto, "name", ctx)); + missing.set(JavaLangAnalyser.findSetterForField(dto, "count", ctx)); + }); + assertThat(compilation).succeeded(); + assertTrue(found.get().isPresent()); + assertTrue(missing.get().isEmpty()); } @Test - void findSetterForField_shouldReturnEmpty_whenDtoTypeIsNull() { - assertTrue(JavaLangAnalyser.findSetterForField(null, "fieldName", null).isEmpty()); + void findPrimaryConstructor_prefersAnnotatedCtorElseWidest() { + AtomicReference annotated = new AtomicReference<>(); + AtomicReference> noAnnotation = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement twoCtor = typeElement(env, "test.TwoCtor"); + annotated.set( + JavaLangAnalyser.findPrimaryConstructor(twoCtor, Deprecated.class, ctx) + .map(c -> c.getParameters().size()) + .orElse(-1)); + TypeElement dto = typeElement(env, "test.Dto"); + noAnnotation.set(JavaLangAnalyser.findPrimaryConstructor(dto, null, ctx)); + }, + CTOR_SOURCE, + DTO_SOURCE); + assertThat(compilation).succeeded(); + assertEquals(2, annotated.get()); + // widest ctor of Dto has 1 param + assertEquals(1, noAnnotation.get().map(c -> c.getParameters().size()).orElse(-1)); } @Test - void findSetterForField_shouldReturnEmpty_whenFieldNameIsNull() { - assertTrue(JavaLangAnalyser.findSetterForField(null, null, null).isEmpty()); + void hasAccessibleConstructor_detectsPublicCtors() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, env) -> + result.set( + JavaLangAnalyser.hasAccessibleConstructor( + typeElement(env, "test.Dto"), context(env)))); + assertThat(compilation).succeeded(); + assertTrue(result.get()); } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java index 34c2a0fb..be597fbc 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java @@ -25,73 +25,54 @@ package org.javahelpers.codegen.analysis; import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ElementTestUtils.method; +import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; +import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import com.google.testing.compile.Compilation; import java.util.List; -import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; -import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; +import javax.tools.JavaFileObject; import org.javahelpers.codegen.model.method.MethodParameterDto; +import org.javahelpers.codegen.model.type.GenericParameterDto; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.model.type.TypeNameList; +import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNamePrimitive; +import org.javahelpers.codegen.model.type.TypeNameSet; import org.javahelpers.codegen.processing.AnnotationProcessingContext; import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** Unit tests for {@link JavaLangMapper} against elements captured from a real compilation. */ class JavaLangMapperTest { - /** Runs {@code probe} once during the first processing round with a live processing context. */ - private static class ProbeProcessor extends AbstractProcessor { - private final BiConsumer probe; - private boolean ran; - - ProbeProcessor(BiConsumer probe) { - this.probe = probe; - } - - @Override - public SourceVersion getSupportedSourceVersion() { - return SourceVersion.latestSupported(); - } - - @Override - public Set getSupportedAnnotationTypes() { - return Set.of("*"); - } - - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { - if (ran || roundEnv.processingOver()) { - return false; - } - ran = true; - probe.accept( - roundEnv, - new AnnotationProcessingContext( - CapturingProcessingLogger.create().logger(), processingEnv)); - return false; - } + private static AnnotationProcessingContext context(ProcessingEnvironment processingEnv) { + return new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), processingEnv); } - private static VariableElement setterParameter( - TypeElement dto, String setterName, int paramIndex) { - return dto.getEnclosedElements().stream() - .filter(ExecutableElement.class::isInstance) - .map(ExecutableElement.class::cast) - .filter(m -> m.getSimpleName().toString().equals(setterName)) - .map(m -> m.getParameters().get(paramIndex)) - .findFirst() - .orElseThrow(); + private static Compilation compile( + BiConsumer probe, String... sources) { + JavaFileObject[] files = + java.util.Arrays.stream(sources) + .map(CodegenTestUtils::forSource) + .toArray(JavaFileObject[]::new); + return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)).compile(files); + } + + private static TypeName paramType( + TypeElement dto, String methodName, int paramIndex, TypeMappingContext ctx) { + return JavaLangMapper.map2MethodParameter(parameter(method(dto, methodName), paramIndex), ctx) + .getParameterType(); } @Test @@ -105,21 +86,15 @@ void map2TypeName_mapsJavaClass() { void mapToTypeName_mapsTypeElement() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, ctx) -> { - TypeElement dto = ctx.getTypeElement("test.Dto"); - result.set(JavaLangMapper.mapToTypeName(dto, ctx)); - })) - .compile( - CodegenTestUtils.forSource( - """ - package test; - public class Dto { - private String name; - public void setName(String name) { this.name = name; } - } - """)); + compile( + (roundEnv, processingEnv) -> + result.set( + JavaLangMapper.mapToTypeName( + typeElement(processingEnv, "test.Dto"), context(processingEnv))), + """ + package test; + public class Dto {} + """); assertThat(compilation).succeeded(); assertEquals("test", result.get().getPackageName()); @@ -130,23 +105,21 @@ public class Dto { void map2MethodParameter_mapsNameAndListType() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, ctx) -> { - TypeElement dto = ctx.getTypeElement("test.Dto"); - VariableElement param = setterParameter(dto, "setTags", 0); - result.set(JavaLangMapper.map2MethodParameter(param, ctx)); - })) - .compile( - CodegenTestUtils.forSource( - """ - package test; - import java.util.List; - public class Dto { - private List tags; - public void setTags(List tags) { this.tags = tags; } - } - """)); + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set( + JavaLangMapper.map2MethodParameter( + parameter(method(dto, "setTags"), 0), context(processingEnv))); + }, + """ + package test; + import java.util.List; + public class Dto { + private List tags; + public void setTags(List tags) { this.tags = tags; } + } + """); assertThat(compilation).succeeded(); MethodParameterDto param = result.get(); @@ -156,22 +129,84 @@ public class Dto { assertEquals("String", typeName.getElementType().getClassName()); } + @Test + void map2MethodParameter_mapsSetToTypeNameSet() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setIds", 0, context(processingEnv))); + }, + """ + package test; + import java.util.Set; + public class Dto { + public void setIds(Set ids) {} + } + """); + + assertThat(compilation).succeeded(); + assertInstanceOf(TypeNameSet.class, result.get()); + assertEquals("Integer", ((TypeNameSet) result.get()).getElementType().getClassName()); + } + + @Test + void map2MethodParameter_mapsMapToTypeNameMap() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setLookup", 0, context(processingEnv))); + }, + """ + package test; + import java.util.Map; + public class Dto { + public void setLookup(Map lookup) {} + } + """); + + assertThat(compilation).succeeded(); + TypeNameMap typeName = assertInstanceOf(TypeNameMap.class, result.get()); + assertEquals("String", typeName.getKeyType().getClassName()); + assertEquals("Integer", typeName.getValueType().getClassName()); + } + + @Test + void map2MethodParameter_mapsPrimitive() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setCount", 0, context(processingEnv))); + }, + """ + package test; + public class Dto { + public void setCount(int count) {} + } + """); + + assertThat(compilation).succeeded(); + assertInstanceOf(TypeNamePrimitive.class, result.get()); + } + @Test void createDerivedTypeName_appendsSuffix() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, ctx) -> { - TypeElement dto = ctx.getTypeElement("test.Dto"); - result.set(JavaLangMapper.createDerivedTypeName(dto, ctx, "Builder")); - })) - .compile( - CodegenTestUtils.forSource( - """ - package test; - public class Dto {} - """)); + compile( + (roundEnv, processingEnv) -> + result.set( + JavaLangMapper.createDerivedTypeName( + typeElement(processingEnv, "test.Dto"), context(processingEnv), "Builder")), + """ + package test; + public class Dto {} + """); assertThat(compilation).succeeded(); assertEquals("test", result.get().getPackageName()); @@ -183,25 +218,124 @@ void extractInterfaceTypeArguments_resolvesInheritedListArgument() { // CustomList extends ArrayList: the List element type is Y, not the declared X/Y pair AtomicReference> result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, ctx) -> { - TypeElement customList = ctx.getTypeElement("test.CustomList"); - TypeElement listInterface = ctx.getTypeElement("java.util.List"); - result.set( - JavaLangMapper.extractInterfaceTypeArguments( - customList.asType(), listInterface, ctx)); - })) - .compile( - CodegenTestUtils.forSource( - """ - package test; - import java.util.ArrayList; - public class CustomList extends ArrayList {} - """)); + compile( + (roundEnv, processingEnv) -> { + AnnotationProcessingContext ctx = context(processingEnv); + TypeElement customList = typeElement(processingEnv, "test.CustomList"); + TypeElement listInterface = typeElement(processingEnv, "java.util.List"); + result.set( + JavaLangMapper.extractInterfaceTypeArguments( + customList.asType(), listInterface, ctx)); + }, + """ + package test; + import java.util.ArrayList; + public class CustomList extends ArrayList {} + """); assertThat(compilation).succeeded(); assertEquals(1, result.get().size()); assertEquals("Y", result.get().get(0).getClassName()); } + + @Test + void map2MethodParameter_wrapsConcreteCollections() { + // ArrayList/HashMap/TreeMap take the hasConstructorWithParameterOfType path and still wrap + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + AnnotationProcessingContext ctx = context(processingEnv); + result.set( + List.of( + paramType(dto, "setTags", 0, ctx), + paramType(dto, "setLookup", 0, ctx), + paramType(dto, "setSorted", 0, ctx))); + }, + """ + package test; + import java.util.ArrayList; + import java.util.HashMap; + import java.util.TreeMap; + public class Dto { + public void setTags(ArrayList tags) {} + public void setLookup(HashMap lookup) {} + public void setSorted(TreeMap sorted) {} + } + """); + + assertThat(compilation).succeeded(); + assertInstanceOf(TypeNameList.class, result.get().get(0)); + assertEquals("String", ((TypeNameList) result.get().get(0)).getElementType().getClassName()); + assertInstanceOf(TypeNameMap.class, result.get().get(1)); + assertEquals("Integer", ((TypeNameMap) result.get().get(1)).getValueType().getClassName()); + assertInstanceOf(TypeNameMap.class, result.get().get(2)); + } + + @Test + void map2MethodParameter_wrapsGenericListToTypeNameList() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setTags", 0, context(processingEnv))); + }, + """ + package test; + import java.util.LinkedList; + public class Dto { + public void setTags(LinkedList tags) {} + } + """); + + assertThat(compilation).succeeded(); + assertInstanceOf(TypeNameList.class, result.get()); + assertEquals("Double", ((TypeNameList) result.get()).getElementType().getClassName()); + } + + @Test + void map2GenericParameterDtos_mapsTypeParametersWithBounds() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(JavaLangMapper.map2GenericParameterDtos(dto, context(processingEnv))); + }, + """ + package test; + public class Dto {} + """); + + assertThat(compilation).succeeded(); + assertEquals(2, result.get().size()); + assertEquals("T", result.get().get(0).getName()); + assertEquals("Number", result.get().get(0).getUpperBounds().get(0).getClassName()); + assertEquals("U", result.get().get(1).getName()); + } + + @Test + void map2MethodParameter_mapsArrayAndTypeVariable() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + AnnotationProcessingContext ctx = context(processingEnv); + result.set(List.of(paramType(dto, "setArr", 0, ctx), paramType(dto, "setT", 0, ctx))); + }, + """ + package test; + public class Dto { + public void setArr(String[] arr) {} + public void setT(T t) {} + } + """); + + assertThat(compilation).succeeded(); + assertEquals("TypeNameArray", result.get().get(0).getClass().getSimpleName()); + assertEquals("T", result.get().get(1).getClassName()); + } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/TypeNameAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/TypeNameAnalyserTest.java new file mode 100644 index 00000000..8b315f8e --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/TypeNameAnalyserTest.java @@ -0,0 +1,76 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.analysis; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Optional; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameGeneric; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link TypeNameAnalyser}. */ +class TypeNameAnalyserTest { + + @Test + void isJavaClass_detectsJavaLangAndUtilTypes() { + assertTrue(TypeNameAnalyser.isJavaClass(TypeName.of(String.class))); + assertTrue(TypeNameAnalyser.isJavaClass(TypeName.of(java.util.ArrayList.class))); + assertFalse(TypeNameAnalyser.isJavaClass(TypeName.of(org.junit.jupiter.api.Test.class))); + } + + @Test + void isOptional_matchesJavaUtilOptional() { + assertTrue(TypeNameAnalyser.isOptional(TypeName.of(Optional.class))); + assertFalse(TypeNameAnalyser.isOptional(TypeName.of(String.class))); + } + + @Test + void isString_matchesJavaLangString() { + assertTrue(TypeNameAnalyser.isString(TypeName.of(String.class))); + assertFalse(TypeNameAnalyser.isString(TypeName.of(StringBuilder.class))); + } + + @Test + void isOptionalString_requiresParameterizedOptionalOfString() { + TypeNameGeneric optionalString = + new TypeNameGeneric("java.util", "Optional", TypeName.of(String.class)); + assertTrue(TypeNameAnalyser.isOptionalString(optionalString)); + TypeNameGeneric optionalInteger = + new TypeNameGeneric("java.util", "Optional", TypeName.of(Integer.class)); + assertFalse(TypeNameAnalyser.isOptionalString(optionalInteger)); + assertFalse(TypeNameAnalyser.isOptionalString(TypeName.of(String.class))); + } + + @Test + void isParameterizedOptional_detectsGenericOptional() { + TypeNameGeneric optional = + new TypeNameGeneric("java.util", "Optional", TypeName.of(String.class)); + assertTrue(TypeNameAnalyser.isParameterizedOptional(optional)); + assertFalse(TypeNameAnalyser.isParameterizedOptional(TypeName.of(Optional.class))); + assertFalse(TypeNameAnalyser.isParameterizedOptional(TypeName.of(String.class))); + } +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tag.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tag.java new file mode 100644 index 00000000..be5529dc --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tag.java @@ -0,0 +1,33 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.analysis.testannotations; + +import java.lang.annotation.Repeatable; + +/** Repeatable fixture annotation for repeatable-annotation lookup tests. */ +@Repeatable(Tags.class) +public @interface Tag { + String value(); +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tags.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tags.java new file mode 100644 index 00000000..5aac86b2 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/testannotations/Tags.java @@ -0,0 +1,30 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.analysis.testannotations; + +/** Container annotation wrapping repeats of {@link Tag}. */ +public @interface Tags { + Tag[] value(); +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java new file mode 100644 index 00000000..61736a4f --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java @@ -0,0 +1,231 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.processing; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ElementTestUtils.field; +import static org.javahelpers.codegen.testing.ElementTestUtils.method; +import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.testing.compile.Compilation; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.TypeMirror; +import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.javahelpers.codegen.testing.ProbeProcessor; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for {@link AnnotationProcessingContext} delegates against a real processing + * environment. + */ +class AnnotationProcessingContextTest { + + private static final String DTO_SOURCE = + """ + package test; + /** Doc comment on the type. */ + public class Dto extends Base { + @SuppressWarnings("unchecked") private String name; + public String getName() { return name; } + } + class Base { + public void inherited() {} + } + """; + + private static AnnotationProcessingContext context( + javax.annotation.processing.ProcessingEnvironment env) { + return new AnnotationProcessingContext(CapturingProcessingLogger.create().logger(), env); + } + + @Test + void delegates_elementAndTypeUtilities() { + AtomicReference> results = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = ctx.getTypeElement("test.Dto"); + TypeMirror nameType = field(dto, "name").asType(); + TypeMirror dtoType = dto.asType(); + results.set( + List.of( + dto != null, + ctx.getTypeElement(TypeName.of(String.class)) != null, + ctx.getPackageOf(dto).getQualifiedName().contentEquals("test"), + ctx.getPackageElement("test") != null, + ctx.getPackageName(dto).equals("test"), + ctx.getAllMembers(dto).stream() + .anyMatch(e -> e.getSimpleName().contentEquals("inherited")), + ctx.getDocComment(dto) != null + && ctx.getDocComment(dto).contains("Doc comment on the type."), + ((TypeElement) ctx.asElement(dtoType)) + .getQualifiedName() + .equals(dto.getQualifiedName()), + ctx.isSameType(nameType, nameType), + !ctx.isSameType(nameType, dtoType), + ctx.erasure(nameType) != null, + ctx.isAssignable(ctx.erasure(dtoType), ctx.erasure(dtoType)), + !ctx.directSupertypes(dtoType).isEmpty())); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + List names = + List.of( + "typeElement", + "typeElementByName", + "packageOf", + "packageElement", + "packageName", + "allMembers", + "docComment", + "asElement", + "isSameType", + "notSameType", + "erasure", + "isAssignable", + "directSupertypes"); + for (int i = 0; i < names.size(); i++) { + assertTrue(results.get().get(i), "check failed: " + names.get(i)); + } + } + + @Test + void generatedTypes_addFindAndClear() { + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = ctx.getTypeElement("test.Dto"); + TypeName elementType = TypeName.of(String.class); + TypeName generated = TypeName.of(Integer.class); + assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); + ctx.addGeneratedType(elementType, generated); + assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); // dto != elementType + assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isPresent()); + ctx.getGeneratedTypes().clear(); + assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isEmpty()); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + } + + @Test + void loggingDelegates_emitToLogger() { + CapturingProcessingLogger capture = CapturingProcessingLogger.create(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = + new AnnotationProcessingContext(capture.logger(), env); + ctx.info("hello %s", "info"); + ctx.debug("hello %s", "debug"); + ctx.warning("hello %s", "warning"); + ctx.error("hello %s", "error"); + ctx.startPerformancePhase(); + ctx.endPerformancePhase("phase"); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello info"))); + assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello warning"))); + assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello error"))); + } + + @Test + void currentTask_nullByDefault() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set(ctx.getCurrentTask()); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertNull(result.get()); + } + + @Test + void getElementValuesWithDefaults_includesDefaultsAndSetValues() { + AtomicReference size = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + javax.lang.model.element.VariableElement nameField = + field(typeElement(env, "test.Dto"), "name"); + javax.lang.model.element.AnnotationMirror suppress = + nameField.getAnnotationMirrors().get(0); + size.set(ctx.getElementValuesWithDefaults(suppress).size()); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + // @SuppressWarnings declares a single 'value' member + assertEquals(1, size.get()); + } + + @Test + void isAccessibleFromGeneratedPackage_publicMembersAccessible() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "getName"))); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertNotNull(result.get()); + } + + @Test + void performanceTracker_defaultsToNoOp() { + AtomicReference tracker = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> tracker.set(context(env).getPerformanceTracker()))) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertNotNull(tracker.get()); + assertEquals("NoOpPerformanceTracker", tracker.get().getClass().getSimpleName()); + } +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/CompilerArgumentsReaderTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/CompilerArgumentsReaderTest.java new file mode 100644 index 00000000..d81e4be8 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/CompilerArgumentsReaderTest.java @@ -0,0 +1,100 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.processing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Map; +import org.javahelpers.codegen.testing.ProcessingEnvironmentStub; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link CompilerArgumentsReader}. */ +class CompilerArgumentsReaderTest { + + private static final CompilerOption OPTION = + new CompilerOption() { + @Override + public String getOptionName() { + return "verbose"; + } + + @Override + public String getCompilerArgument() { + return "mydomain.verbose"; + } + }; + + @Test + void readValue_prefersCompilerArgumentThenBareName() { + assertEquals("a", CompilerArgumentsReader.readValue(OPTION, Map.of("mydomain.verbose", "a"))); + assertEquals("b", CompilerArgumentsReader.readValue(OPTION, Map.of("verbose", "b"))); + assertNull(CompilerArgumentsReader.readValue(OPTION, Map.of())); + } + + @Test + void readValue_usesSystemPropertyFirst() { + System.setProperty("mydomain.verbose", "sysprop"); + try { + assertEquals("sysprop", CompilerArgumentsReader.readValue(OPTION, Map.of("verbose", "b"))); + } finally { + System.clearProperty("mydomain.verbose"); + } + } + + @Test + void readValue_readsFromProcessingEnvironment() { + CompilerArgumentsReader reader = + new CompilerArgumentsReader( + ProcessingEnvironmentStub.create(Map.of("mydomain.verbose", "env"))); + assertEquals("env", reader.readValue(OPTION)); + } + + @Test + void readBooleanValue_parsesAliasesAndDefaults() { + assertTrue(CompilerArgumentsReader.readBooleanValue(OPTION, Map.of("verbose", "true"), false)); + assertTrue( + CompilerArgumentsReader.readBooleanValue(OPTION, Map.of("verbose", "enabled"), false)); + assertFalse(CompilerArgumentsReader.readBooleanValue(OPTION, Map.of("verbose", "false"), true)); + assertFalse( + CompilerArgumentsReader.readBooleanValue(OPTION, Map.of("verbose", "disabled"), true)); + assertTrue(CompilerArgumentsReader.readBooleanValue(OPTION, Map.of(), true)); + assertFalse(CompilerArgumentsReader.readBooleanValue(OPTION, Map.of(), false)); + assertTrue(CompilerArgumentsReader.readBooleanValue(OPTION, Map.of("verbose", ""), true)); + assertFalse(CompilerArgumentsReader.readBooleanValue(OPTION, Map.of("verbose", "junk"), false)); + } + + @Test + void readBooleanValue_readsFromProcessingEnvironment() { + CompilerArgumentsReader reader = + new CompilerArgumentsReader(ProcessingEnvironmentStub.create(Map.of("verbose", "enabled"))); + assertTrue(reader.readBooleanValue(OPTION)); + assertFalse( + new CompilerArgumentsReader(ProcessingEnvironmentStub.create(Map.of())) + .readBooleanValue(OPTION)); + } +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/PipelinePhasesTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/PipelinePhasesTest.java new file mode 100644 index 00000000..4814a262 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/PipelinePhasesTest.java @@ -0,0 +1,48 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.processing; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link PipelinePhases}. */ +class PipelinePhasesTest { + + @Test + void pipelineHierarchy_containsAllDeclaredPhases() { + List topLevel = PipelinePhases.PIPELINE_HIERARCHY.topLevelPhases(); + for (String phase : + List.of( + PipelinePhases.PHASE_ELEMENT_COLLECTION, + PipelinePhases.PHASE_CONFIGURATION_RESOLUTION, + PipelinePhases.PHASE_ANALYSIS, + PipelinePhases.PHASE_TARGET_MAPPING, + PipelinePhases.PHASE_CODE_GENERATION)) { + assertTrue(topLevel.contains(phase), "missing top-level phase " + phase); + } + } +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java index 4f1e2809..ce9ef3f2 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java @@ -24,25 +24,79 @@ package org.javahelpers.codegen.processing; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.Set; +import java.util.List; +import java.util.Map; +import org.javahelpers.codegen.testing.ProcessingEnvironmentStub; import org.junit.jupiter.api.Test; /** Unit tests for {@link ProcessorOptionRegistry}. */ class ProcessorOptionRegistryTest { - private static ProcessorOptionRegistry minimalRegistry() { - return ProcessorOptionRegistry.builder().options(Set.of()).build(); + private static CompilerOption option(String name) { + return new CompilerOption() { + @Override + public String getOptionName() { + return name; + } + + @Override + public String getCompilerArgument() { + return "testdomain." + name; + } + }; + } + + @Test + void supportedOptions_includesOptionAndArgumentNames() { + ProcessorOptionRegistry registry = + new ProcessorOptionRegistry(List.of(option("alpha"), option("beta"))); + assertTrue( + registry + .supportedOptions() + .containsAll(List.of("alpha", "testdomain.alpha", "beta", "testdomain.beta"))); + } + + @Test + void builder_wiresVerboseAndFormatterProfile() { + ProcessorOptionRegistry registry = + ProcessorOptionRegistry.builder() + .options(List.of(option("alpha"))) + .verboseOption(option("verbose")) + .formatterProfileOption(option("formatter")) + .build(); + assertTrue(registry.supportedOptions().containsAll(List.of("verbose", "formatter", "alpha"))); + + assertTrue( + registry.isVerboseRequested( + new CompilerArgumentsReader( + ProcessingEnvironmentStub.create(Map.of("testdomain.verbose", "true"))))); + assertEquals( + "compact", + registry.formatterProfile( + new CompilerArgumentsReader( + ProcessingEnvironmentStub.create(Map.of("formatter", " compact "))))); } @Test - void reader_returnsReaderForEnvironment() { - assertNotNull(minimalRegistry().reader(null)); + void defaults_noVerboseAndNoProfile() { + ProcessorOptionRegistry registry = new ProcessorOptionRegistry(List.of()); + CompilerArgumentsReader reader = + new CompilerArgumentsReader(ProcessingEnvironmentStub.create(Map.of())); + assertFalse(registry.isVerboseRequested(reader)); + assertNull(registry.formatterProfile(reader)); } @Test - void formatterProfile_withoutConfiguredOption_returnsNull() { - assertNull(minimalRegistry().formatterProfile(new CompilerArgumentsReader(null))); + void reader_wrapsProcessingEnvironment() { + ProcessorOptionRegistry registry = new ProcessorOptionRegistry(List.of()); + assertTrue( + registry + .reader(ProcessingEnvironmentStub.create(Map.of("verbose", "true"))) + .readBooleanValue(option("verbose"))); } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java new file mode 100644 index 00000000..355a048d --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java @@ -0,0 +1,236 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.processing.logging; + +import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.testing.ElementTestUtils.method; +import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.testing.compile.Compilation; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import javax.annotation.processing.Filer; +import javax.annotation.processing.Messager; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.Element; +import javax.lang.model.util.Elements; +import javax.lang.model.util.Types; +import javax.tools.Diagnostic; +import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.javahelpers.codegen.testing.ProbeProcessor; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link MessagerProcessingLogger} driven by a real Messager. */ +class MessagerProcessingLoggerTest { + + private static final String DTO_SOURCE = + """ + package test; + public class Dto { + public void setName(String name) {} + } + """; + + /** Recorded diagnostic: kind, message, attached element. */ + private record Diag(Diagnostic.Kind kind, String message, Element element) {} + + @Test + void warning_attachesElementInDefaultMode() { + List diags = new CopyOnWriteArrayList<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.create(recordingEnv(env, diags)); + Element param = + method(typeElement(env, "test.Dto"), "setName").getParameters().get(0); + logger.warning(param, "conflict on %s", "name"); + logger.flushWarningLocations(); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertEquals(1, diags.size()); + Diag diag = diags.get(0); + assertEquals(Diagnostic.Kind.WARNING, diag.kind()); + assertTrue(diag.message().contains("conflict on name")); + assertEquals("name", diag.element().getSimpleName().toString()); + } + + @Test + void error_attachesElement() { + List diags = new CopyOnWriteArrayList<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.create(recordingEnv(env, diags)); + logger.error(typeElement(env, "test.Dto"), "failed on %s", "Dto"); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + // the emitted error fails the compilation on purpose + assertEquals(1, diags.size()); + assertEquals(Diagnostic.Kind.ERROR, diags.get(0).kind()); + assertEquals("Dto", diags.get(0).element().getSimpleName().toString()); + } + + @Test + void verboseWarning_deferLocationAndFlushOncePerType() { + List diags = new CopyOnWriteArrayList<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.createVerbose(recordingEnv(env, diags), "test"); + Element param = + method(typeElement(env, "test.Dto"), "setName").getParameters().get(0); + logger.warning(param, "first %s", "a"); + logger.warning(param, "second %s", "b"); + logger.flushWarningLocations(); + logger.flushWarningLocations(); // cleared -> nothing more + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertEquals(3, diags.size()); + // two flat warnings without element + one location marker on the enclosing type + assertTrue(diags.get(0).message().contains("first a")); + assertNull(diags.get(0).element()); + assertTrue(diags.get(2).message().contains("Location of the warning(s)")); + assertEquals("Dto", diags.get(2).element().getSimpleName().toString()); + } + + @Test + void deferWarningLocation_ignoresNullElement() { + List diags = new CopyOnWriteArrayList<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.createVerbose(recordingEnv(env, diags)); + logger.warning((Element) null, "orphan warning"); + logger.flushWarningLocations(); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertEquals(1, diags.size()); + assertTrue(diags.get(0).message().contains("orphan warning")); + } + + @Test + void loggingPrefix_appliesToMessages() { + List diags = new CopyOnWriteArrayList<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> + MessagerProcessingLogger.create(recordingEnv(env, diags), "myproc") + .info("hello %s", "world"))) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertTrue(diags.get(0).message().contains("myproc")); + } + + /** Returns an environment identical to {@code env} but with a diagnostic-recording Messager. */ + private static ProcessingEnvironment recordingEnv(ProcessingEnvironment env, List diags) { + Messager delegate = env.getMessager(); + Messager recorder = + new Messager() { + @Override + public void printMessage(Diagnostic.Kind kind, CharSequence msg) { + diags.add(new Diag(kind, msg.toString(), null)); + delegate.printMessage(kind, msg); + } + + @Override + public void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e) { + diags.add(new Diag(kind, msg.toString(), e)); + delegate.printMessage(kind, msg, e); + } + + @Override + public void printMessage( + Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a) { + delegate.printMessage(kind, msg, e, a); + } + + @Override + public void printMessage( + Diagnostic.Kind kind, + CharSequence msg, + Element e, + AnnotationMirror a, + AnnotationValue v) { + delegate.printMessage(kind, msg, e, a, v); + } + }; + return new ProcessingEnvironment() { + @Override + public Map getOptions() { + return env.getOptions(); + } + + @Override + public Messager getMessager() { + return recorder; + } + + @Override + public Filer getFiler() { + return env.getFiler(); + } + + @Override + public Elements getElementUtils() { + return env.getElementUtils(); + } + + @Override + public Types getTypeUtils() { + return env.getTypeUtils(); + } + + @Override + public SourceVersion getSourceVersion() { + return env.getSourceVersion(); + } + + @Override + public Locale getLocale() { + return env.getLocale(); + } + }; + } +} From 31fe1a60ca93fd6362a0a6b6390b467b3be9dac8 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:29:39 +0000 Subject: [PATCH 03/12] address review comments: fix ambiguous method lookups, S3516/S2093/S5778, richer Roaster test asserts --- codegen-core/pom.xml | 5 +- .../codegen/model/type/TypeNameGeneric.java | 12 +++ codegen-roaster/pom.xml | 5 +- .../codegen/roaster/RoasterBackendTest.java | 12 +-- .../roaster/RoasterCodeGeneratorTest.java | 69 +++++++++++---- .../codegen/roaster/RoasterMapperTest.java | 3 +- codegen-testing/pom.xml | 5 +- .../codegen/testing/ElementTestUtils.java | 78 +++++++++++------ .../codegen/testing/ProbeProcessor.java | 38 +++++++-- .../codegen/testing/CodegenTestUtilsTest.java | 4 +- .../codegen/testing/ElementTestUtilsTest.java | 83 +++++++++---------- .../codegen/testing/ProcessorAssertsTest.java | 5 +- core/pom.xml | 5 +- processor/pom.xml | 5 +- simple-processor/pom.xml | 5 +- .../analysis/JavaLangAnalyserTest.java | 8 +- 16 files changed, 213 insertions(+), 129 deletions(-) diff --git a/codegen-core/pom.xml b/codegen-core/pom.xml index 78efb444..adcde882 100644 --- a/codegen-core/pom.xml +++ b/codegen-core/pom.xml @@ -349,14 +349,13 @@ - **/codegen/model/** - **/processor/model/** + **/model/** **/enums/** **/*Exception.* **/exceptions/** - **/JavadocConstants.* + **/*Constants.* diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java index 487a6249..7d701daf 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java @@ -95,6 +95,18 @@ public TypeNameGeneric(String packageName, String className, TypeName... innerTy this.innerTypeArguments = List.of(innerTypeArguments); } + /** + * Varargs convenience constructor taking {@link Class} references directly. + * + * @param outerType the outer type + * @param innerTypeArguments variable number of generic type arguments + */ + public TypeNameGeneric(Class outerType, Class... innerTypeArguments) { + this( + TypeName.of(outerType), + java.util.Arrays.stream(innerTypeArguments).map(TypeName::of).toArray(TypeName[]::new)); + } + /** * Returns the raw type (without type parameters). * diff --git a/codegen-roaster/pom.xml b/codegen-roaster/pom.xml index 50381048..6b5e8afa 100644 --- a/codegen-roaster/pom.xml +++ b/codegen-roaster/pom.xml @@ -346,14 +346,13 @@ - **/codegen/model/** - **/processor/model/** + **/model/** **/enums/** **/*Exception.* **/exceptions/** - **/JavadocConstants.* + **/*Constants.* diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java index 3cdf124e..0ca7a06c 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterBackendTest.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.roaster; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import org.javahelpers.codegen.enums.FormattingMode; @@ -43,11 +44,10 @@ void exposesGeneratorAndCachesFormatterPerMode() { TestingGenerationEnvironment.create(capturing.logger()), capturing.logger(), null); assertInstanceOf(RoasterCodeGenerator.class, backend.generator()); - assertInstanceOf( - RoasterSourceFormatter.class, backend.formatterFor(FormattingMode.LIGHTWEIGHT)); - // formatters are cached per mode - assertSame( - backend.formatterFor(FormattingMode.LIGHTWEIGHT), - backend.formatterFor(FormattingMode.LIGHTWEIGHT)); + RoasterSourceFormatter formatter = + (RoasterSourceFormatter) backend.formatterFor(FormattingMode.LIGHTWEIGHT); + // formatters are cached per mode, and distinct across modes + assertSame(formatter, backend.formatterFor(FormattingMode.LIGHTWEIGHT)); + assertNotSame(formatter, backend.formatterFor(FormattingMode.NONE)); } } diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index 85a6b2ab..71934c49 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -26,6 +26,7 @@ import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.javahelpers.codegen.SourceFormatter; @@ -135,8 +136,7 @@ void writesFileUnderQualifiedName() throws Exception { generator.generateClass( empty, new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE)); - org.junit.jupiter.api.Assertions.assertEquals( - "mem:///com/example/EmptyBuilder.java", env.writtenUri().toString()); + assertEquals("mem:///com/example/EmptyBuilder.java", env.writtenUri().toString()); } @Test @@ -156,10 +156,9 @@ void generatesClassMetadataJavadocAndAnnotations() throws Exception { assertContaining( generate(classDef), - "extends AbstractBuilder", - "implements Serializable", - "Builder for", - "Generated(\"simple-builders\")"); + "* Builder for {@link Person}.", + "@Generated(\"simple-builders\")", + "public class AnnotatedBuilder extends AbstractBuilder implements Serializable"); } @Test @@ -187,7 +186,10 @@ void generatesGenericClassAndMethods() throws Exception { classDef.addMethod(genericMethod); assertContaining( - generate(classDef), "class GenericBuilder", "static T of(R input)"); + generate(classDef), + "public class GenericBuilder", + "public static T of(R input) {", + "return null;"); } @Test @@ -215,8 +217,17 @@ void generatesConstructorAndFieldVariants() throws Exception { ctor.addParameter(param); classDef.addConstructor(ctor); - assertContaining( - generate(classDef), "private int DEFAULT_SIZE = 42", "protected CtorBuilder(int capacity)"); + assertNormalizedEquals( + """ + package test; + import test.anno.NonNull; + public class CtorBuilder { + private int DEFAULT_SIZE = 42; + protected CtorBuilder(int capacity) { + } + }""", + generate(classDef), + "generated CtorBuilder must match the expected source"); } @Test @@ -237,7 +248,20 @@ void generatesNestedTypesWithMembers() throws Exception { nested.addMethod(nestedMethod); classDef.addNestedType(nested); - assertContaining(generate(classDef), "class Helper", "Nested helper.", "void assist()"); + assertNormalizedEquals( + """ + package test; + public class OuterBuilder { + /** + * Nested helper. + */ + public class Helper { + public void assist() { + } + } + }""", + generate(classDef), + "generated OuterBuilder must match the expected source"); } @Test @@ -268,14 +292,23 @@ void generatesMethodWithJavadocAnnotationsAndTypedParameters() throws Exception method.setCode("return null;"); classDef.addMethod(method); - String generated = generate(classDef); - assertContaining( - generated, - "Adds items", - "@param values", - "@return", - "@Override", - "List items(List values)"); + assertNormalizedEquals( + """ + package test; + import java.util.List; + public class RichBuilder { + /** + * Adds items. + * @param values items to add + * @return this builder + */ + @Override + public List items(List values) { + return null; + } + }""", + generate(classDef), + "generated RichBuilder must match the expected source"); } private static String generate(GenerationTargetClassDto classDef) throws Exception { diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java index c4cc66d7..1e7b6f15 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java @@ -67,8 +67,7 @@ void mapType_rendersArrayOfInnerType() { @Test void mapType_rendersGenericWithInnerArguments() { - TypeNameGeneric generic = - new TypeNameGeneric(new TypeName("java.util", "List"), List.of(TypeName.of(String.class))); + TypeNameGeneric generic = new TypeNameGeneric(List.class, String.class); assertEquals("List", RoasterMapper.mapType(generic)); } diff --git a/codegen-testing/pom.xml b/codegen-testing/pom.xml index 42c6558f..4c8d4fa1 100644 --- a/codegen-testing/pom.xml +++ b/codegen-testing/pom.xml @@ -352,14 +352,13 @@ - **/codegen/model/** - **/processor/model/** + **/model/** **/enums/** **/*Exception.* **/exceptions/** - **/JavadocConstants.* + **/*Constants.* diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java index 6d994ed4..23c23315 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java @@ -24,6 +24,8 @@ package org.javahelpers.codegen.testing; +import java.util.List; +import java.util.stream.Stream; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; @@ -47,41 +49,67 @@ public static TypeElement typeElement(ProcessingEnvironment processingEnv, Strin return processingEnv.getElementUtils().getTypeElement(qualifiedName); } - /** Finds a field (or any {@link VariableElement} member) of a type by simple name. */ + /** + * Finds the field of a type by simple name. Only fields are considered — parameters belong to + * methods, not to the type. Fails when the field is missing or declared several times. + */ public static VariableElement field(TypeElement type, String fieldName) { - return type.getEnclosedElements().stream() - .filter(VariableElement.class::isInstance) - .map(VariableElement.class::cast) - .filter(e -> e.getSimpleName().toString().equals(fieldName)) - .findFirst() - .orElseThrow(); + return exactlyOne( + type.getEnclosedElements().stream() + .filter(VariableElement.class::isInstance) + .map(VariableElement.class::cast) + .filter(e -> e.getSimpleName().toString().equals(fieldName)), + "field '" + fieldName + "' on " + type.getQualifiedName()); } /** - * Finds a method of a type by simple name; fails when several overloads exist — use {@link - * #method(TypeElement, String, int)} or {@link #parameter(ExecutableElement, int)} then. + * Finds the method of a type by simple name; fails when it is missing or overloaded — use {@link + * #method(TypeElement, String, String...)} to select an overload by its parameter types. */ public static ExecutableElement method(TypeElement type, String methodName) { - return type.getEnclosedElements().stream() - .filter(ExecutableElement.class::isInstance) - .map(ExecutableElement.class::cast) - .filter(e -> e.getSimpleName().toString().equals(methodName)) - .findFirst() - .orElseThrow(); + return exactlyOne( + type.getEnclosedElements().stream() + .filter(ExecutableElement.class::isInstance) + .map(ExecutableElement.class::cast) + .filter(e -> e.getSimpleName().toString().equals(methodName)), + "method '" + methodName + "' on " + type.getQualifiedName()); } /** - * Finds the {@code overloadIndex}-th method of a type with the given simple name, in declaration - * order. + * Finds the method of a type by simple name and parameter types (as qualified names, e.g. {@code + * "java.lang.String"}), matching each parameter's erased type string. */ - public static ExecutableElement method(TypeElement type, String methodName, int overloadIndex) { - return type.getEnclosedElements().stream() - .filter(ExecutableElement.class::isInstance) - .map(ExecutableElement.class::cast) - .filter(e -> e.getSimpleName().toString().equals(methodName)) - .skip(overloadIndex) - .findFirst() - .orElseThrow(); + public static ExecutableElement method( + TypeElement type, String methodName, String... parameterTypes) { + return exactlyOne( + type.getEnclosedElements().stream() + .filter(ExecutableElement.class::isInstance) + .map(ExecutableElement.class::cast) + .filter(e -> e.getSimpleName().toString().equals(methodName)) + .filter( + e -> + e.getParameters().stream() + .map(p -> p.asType().toString()) + .toList() + .equals(List.of(parameterTypes))), + "method '" + + methodName + + "(" + + String.join(", ", parameterTypes) + + "' on " + + type.getQualifiedName()); + } + + private static T exactlyOne(Stream matches, String description) { + List found = matches.toList(); + if (found.isEmpty()) { + throw new IllegalArgumentException("No " + description + " found"); + } + if (found.size() > 1) { + throw new IllegalArgumentException( + "Expected one " + description + " but found " + found.size()); + } + return found.get(0); } /** Returns the {@code index}-th parameter of a method. */ diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java index f4493d51..f4b0649d 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java @@ -25,12 +25,15 @@ package org.javahelpers.codegen.testing; import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; +import java.util.function.BiFunction; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; +import javax.tools.JavaFileObject; /** * Test processor that runs a probe once inside a real compilation. @@ -38,15 +41,16 @@ *

During the first processing round the probe receives the {@link RoundEnvironment} and the live * {@link ProcessingEnvironment}, so it can look up {@code TypeElement}s of compiled test sources * (see {@link ElementTestUtils}) and inspect them with real {@code javax.lang.model} types. Results - * are captured by the probe (e.g. into {@link java.util.concurrent.atomic.AtomicReference}s) and - * asserted by the test after compilation. + * are captured by the probe and asserted by the test after compilation. + * + *

{@link #probe(BiFunction, JavaFileObject...)} wraps the whole ceremony — compiler setup, + * capturing and returning the probe's result — in one call: * *

{@code
- * AtomicReference found = new AtomicReference<>();
- * Compilation compilation = CodegenTestUtils.createCompiler(
- *     new ProbeProcessor((roundEnv, processingEnv) ->
- *         found.set(ElementTestUtils.typeElement(processingEnv, "test.Dto"))))
- *     .compile(CodegenTestUtils.forSource("package test; public class Dto {}"));
+ * TypeElement dto = ProbeProcessor.probe(
+ *     (roundEnv, processingEnv) ->
+ *         ElementTestUtils.typeElement(processingEnv, "test.Dto"),
+ *     CodegenTestUtils.forSource("package test; public class Dto {}"));
  * }
*/ public class ProbeProcessor extends AbstractProcessor { @@ -54,6 +58,23 @@ public class ProbeProcessor extends AbstractProcessor { private final BiConsumer probe; private boolean ran; + /** + * Runs {@code probe} once inside a compilation of {@code sources} and returns its result. + * + * @param probe callback invoked in the first processing round + * @param sources the compilation units to compile + * @return whatever the probe produced + */ + public static T probe( + BiFunction probe, JavaFileObject... sources) { + AtomicReference result = new AtomicReference<>(); + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, processingEnv) -> result.set(probe.apply(roundEnv, processingEnv)))) + .compile(sources); + return result.get(); + } + /** * @param probe callback invoked exactly once in the first processing round */ @@ -78,6 +99,7 @@ public boolean process(Set annotations, RoundEnvironment } ran = true; probe.accept(roundEnv, processingEnv); - return false; + // Claim the annotations of the round the probe consumed. + return true; } } diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java index 8421c061..f4b4bbdd 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java @@ -170,8 +170,8 @@ void printDiagnosticsAndSources_emitToSystemOut() { assertThat(compilation).succeeded(); var captured = new java.io.ByteArrayOutputStream(); var original = System.out; - try { - System.setOut(new java.io.PrintStream(captured)); + try (java.io.PrintStream redirected = new java.io.PrintStream(captured)) { + System.setOut(redirected); CodegenTestUtils.printDiagnostics(compilation); CodegenTestUtils.printGeneratedSources(compilation); } finally { diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java index d2fb5c56..2de50024 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java @@ -24,15 +24,14 @@ package org.javahelpers.codegen.testing; -import static com.google.testing.compile.CompilationSubject.assertThat; import static org.javahelpers.codegen.testing.ElementTestUtils.field; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import com.google.testing.compile.Compilation; -import java.util.concurrent.atomic.AtomicReference; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; @@ -51,66 +50,62 @@ public void setName(Object name) {} } """; - private static Compilation compile( - java.util.function.BiConsumer< + private static T probe( + java.util.function.BiFunction< javax.annotation.processing.RoundEnvironment, - javax.annotation.processing.ProcessingEnvironment> - probe) { - return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + javax.annotation.processing.ProcessingEnvironment, + T> + probeFn) { + return ProbeProcessor.probe(probeFn, CodegenTestUtils.forSource(DTO_SOURCE)); } @Test void typeElement_findsCompiledType() { - AtomicReference result = new AtomicReference<>(); - Compilation compilation = compile((roundEnv, env) -> result.set(typeElement(env, "test.Dto"))); - - assertThat(compilation).succeeded(); - assertEquals("test.Dto", result.get().getQualifiedName().toString()); + TypeElement dto = probe((roundEnv, env) -> typeElement(env, "test.Dto")); + assertEquals("test.Dto", dto.getQualifiedName().toString()); } @Test void field_findsDeclaredField() { - AtomicReference result = new AtomicReference<>(); - Compilation compilation = - compile((roundEnv, env) -> result.set(field(typeElement(env, "test.Dto"), "name"))); - - assertThat(compilation).succeeded(); - assertEquals("name", result.get().getSimpleName().toString()); - assertEquals("java.lang.String", result.get().asType().toString()); + VariableElement name = probe((roundEnv, env) -> field(typeElement(env, "test.Dto"), "name")); + assertEquals("name", name.getSimpleName().toString()); + assertEquals("java.lang.String", name.asType().toString()); } @Test - void method_returnsFirstOverload() { - AtomicReference result = new AtomicReference<>(); - Compilation compilation = - compile((roundEnv, env) -> result.set(method(typeElement(env, "test.Dto"), "setName"))); - - assertThat(compilation).succeeded(); - assertEquals("setName", result.get().getSimpleName().toString()); + void field_failsWhenMissing() { + // javac wraps processor-thrown exceptions in RuntimeException + RuntimeException thrown = + assertThrows( + RuntimeException.class, + () -> probe((roundEnv, env) -> field(typeElement(env, "test.Dto"), "missing"))); + assertTrue(String.valueOf(thrown.getCause()).contains("No field 'missing'")); } @Test - void method_overloadIndexSelectsLaterOverload() { - AtomicReference result = new AtomicReference<>(); - Compilation compilation = - compile((roundEnv, env) -> result.set(method(typeElement(env, "test.Dto"), "setName", 1))); + void method_failsOnOverloadAmbiguity() { + // javac wraps processor-thrown exceptions in RuntimeException + RuntimeException thrown = + assertThrows( + RuntimeException.class, + () -> probe((roundEnv, env) -> method(typeElement(env, "test.Dto"), "setName"))); + assertTrue(String.valueOf(thrown.getCause()).contains("found 2")); + } - assertThat(compilation).succeeded(); - assertEquals("java.lang.Object", result.get().getParameters().get(0).asType().toString()); + @Test + void method_parameterTypesSelectOverload() { + ExecutableElement objectOverload = + probe( + (roundEnv, env) -> method(typeElement(env, "test.Dto"), "setName", "java.lang.Object")); + assertEquals("java.lang.Object", objectOverload.getParameters().get(0).asType().toString()); } @Test void parameter_returnsIndexedParameter() { - AtomicReference result = new AtomicReference<>(); - Compilation compilation = - compile( - (roundEnv, env) -> { - ExecutableElement mth = method(typeElement(env, "test.Dto"), "setName"); - result.set(parameter(mth, 0)); - }); - - assertThat(compilation).succeeded(); - assertEquals("name", result.get().getSimpleName().toString()); + VariableElement param = + probe( + (roundEnv, env) -> + parameter(method(typeElement(env, "test.Dto"), "setName", "java.lang.String"), 0)); + assertEquals("name", param.getSimpleName().toString()); } } diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java index e5ee1492..5c9e5090 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java @@ -60,9 +60,8 @@ void assertNotContaining_passesWhenSearchStringAbsent() { @Test void assertingResult_supportsRecordChecks() { ProcessorAsserts.assertingResult(CODE, contains("class Foo"), notContains("class Bar")); - assertThrows( - AssertionError.class, - () -> ProcessorAsserts.assertingResult(CODE, notContains("class Foo"))); + var failingCheck = notContains("class Foo"); + assertThrows(AssertionError.class, () -> ProcessorAsserts.assertingResult(CODE, failingCheck)); } @Test diff --git a/core/pom.xml b/core/pom.xml index 3b3cc611..2aac0661 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -312,14 +312,13 @@ - **/codegen/model/** - **/processor/model/** + **/model/** **/enums/** **/*Exception.* **/exceptions/** - **/JavadocConstants.* + **/*Constants.* diff --git a/processor/pom.xml b/processor/pom.xml index 11be54e5..d445850f 100644 --- a/processor/pom.xml +++ b/processor/pom.xml @@ -375,14 +375,13 @@ - **/codegen/model/** - **/processor/model/** + **/model/** **/enums/** **/*Exception.* **/exceptions/** - **/JavadocConstants.* + **/*Constants.* diff --git a/simple-processor/pom.xml b/simple-processor/pom.xml index 3e9adf07..19adcf96 100644 --- a/simple-processor/pom.xml +++ b/simple-processor/pom.xml @@ -340,14 +340,13 @@ - **/codegen/model/** - **/processor/model/** + **/model/** **/enums/** **/*Exception.* **/exceptions/** - **/JavadocConstants.* + **/*Constants.* diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java index e5fc9cb7..dec78a9f 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -198,7 +198,7 @@ void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "getName")), JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "risky")), // setName returns void -> no return value; getName returns String - JavaLangAnalyser.hasNoReturnValue(method(dto, "setName")), + JavaLangAnalyser.hasNoReturnValue(method(dto, "setName", "java.lang.String")), JavaLangAnalyser.hasNoReturnValue(method(dto, "getName")), JavaLangAnalyser.isNotPrivate(method(dto, "getName")), JavaLangAnalyser.isNotPrivate(method(dto, "hidden")), @@ -206,7 +206,7 @@ void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { JavaLangAnalyser.isNotStatic(method(dto, "staticUtil")), JavaLangAnalyser.hasGenericTypes(method(dto, "generic")), JavaLangAnalyser.hasGenericTypes(method(dto, "getName")), - JavaLangAnalyser.isSetterForField(method(dto, "setName")), + JavaLangAnalyser.isSetterForField(method(dto, "setName", "java.lang.String")), JavaLangAnalyser.isSetterForField(method(dto, "getName")))); }); assertThat(compilation).succeeded(); @@ -484,7 +484,9 @@ void isFunctionalInterface_detectsAnnotatedAndSingleAbstractMethod() { void extractParamJavaDoc_readsParamTextWithContinuation() { AtomicReference mth = new AtomicReference<>(); Compilation compilation = - compileDto((roundEnv, env) -> mth.set(method(typeElement(env, "test.Dto"), "setName"))); + compileDto( + (roundEnv, env) -> + mth.set(method(typeElement(env, "test.Dto"), "setName", "java.lang.String"))); assertThat(compilation).succeeded(); String javadoc = """ From ca5b4c8f649470055dff9541d75bc5ba77561e95 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:30:03 +0000 Subject: [PATCH 04/12] codeql: assert emitted diagnostics/messages in logger tests --- .../javahelpers/codegen/logging/SinkProcessingLoggerTest.java | 2 ++ .../processing/logging/MessagerProcessingLoggerTest.java | 1 + 2 files changed, 3 insertions(+) diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java index 9a766f96..bacc315e 100644 --- a/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java +++ b/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.logging; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; @@ -104,6 +105,7 @@ void resetIndentation_returnsToLevelZero() { logger.debugStartOperation("op"); assertTrue(logger.getCurrentIndentationLevel() > 0); + assertFalse(messages.isEmpty()); logger.resetIndentation(); assertEquals(0, logger.getCurrentIndentationLevel()); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java index 355a048d..f0db1adc 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java @@ -100,6 +100,7 @@ void error_attachesElement() { })) .compile(CodegenTestUtils.forSource(DTO_SOURCE)); // the emitted error fails the compilation on purpose + assertThat(compilation).failed(); assertEquals(1, diags.size()); assertEquals(Diagnostic.Kind.ERROR, diags.get(0).kind()); assertEquals("Dto", diags.get(0).element().getSimpleName().toString()); From 74881369e47a6fcb4a8a8960a117ecedf5f6e00e Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:35:55 +0000 Subject: [PATCH 05/12] merge main: adapt tests to findAccessibleConstructors/findConstructorsAnnotatedWith, JUL logging capture --- .../codegen/testing/CodegenTestUtilsTest.java | 26 ++++++-- .../analysis/JavaLangAnalyserTest.java | 63 +++++++++++++------ 2 files changed, 63 insertions(+), 26 deletions(-) diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java index f4b4bbdd..6a04e33f 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java @@ -162,20 +162,34 @@ void readSource_readsForSourceContent() { } @Test - void printDiagnosticsAndSources_emitToSystemOut() { + void printDiagnosticsAndSources_emitToLog() { Compilation compilation = CodegenTestUtils.createCompiler(new EmittingProcessor()) .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); assertThat(compilation).succeeded(); - var captured = new java.io.ByteArrayOutputStream(); - var original = System.out; - try (java.io.PrintStream redirected = new java.io.PrintStream(captured)) { - System.setOut(redirected); + var captured = new StringBuilder(); + java.util.logging.Handler captureHandler = + new java.util.logging.Handler() { + @Override + public void publish(java.util.logging.LogRecord record) { + captured.append(record.getMessage()).append('\n'); + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + java.util.logging.Logger log = + java.util.logging.Logger.getLogger(CodegenTestUtils.class.getName()); + log.addHandler(captureHandler); + try { CodegenTestUtils.printDiagnostics(compilation); CodegenTestUtils.printGeneratedSources(compilation); } finally { - System.setOut(original); + log.removeHandler(captureHandler); } assertTrue(captured.toString().contains("Generated")); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java index dec78a9f..cc9efe76 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -115,6 +115,15 @@ public TwoCtor(String a, int b) {} } """; + private static final String PRIVATE_CTOR_SOURCE = + """ + package test; + public class PrivateCtor { + private PrivateCtor() {} + public PrivateCtor(String a) {} + } + """; + private static AnnotationProcessingContext context(ProcessingEnvironment processingEnv) { return new AnnotationProcessingContext( CapturingProcessingLogger.create().logger(), processingEnv); @@ -577,39 +586,53 @@ void findSetterForField_matchesVoidSingleParamSetter() { } @Test - void findPrimaryConstructor_prefersAnnotatedCtorElseWidest() { - AtomicReference annotated = new AtomicReference<>(); - AtomicReference> noAnnotation = new AtomicReference<>(); + void findAccessibleConstructors_excludesPrivate() { + AtomicReference twoCtor = new AtomicReference<>(); + AtomicReference privateCtor = new AtomicReference<>(); Compilation compilation = compile( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); - TypeElement twoCtor = typeElement(env, "test.TwoCtor"); - annotated.set( - JavaLangAnalyser.findPrimaryConstructor(twoCtor, Deprecated.class, ctx) - .map(c -> c.getParameters().size()) - .orElse(-1)); - TypeElement dto = typeElement(env, "test.Dto"); - noAnnotation.set(JavaLangAnalyser.findPrimaryConstructor(dto, null, ctx)); + twoCtor.set( + JavaLangAnalyser.findAccessibleConstructors(typeElement(env, "test.TwoCtor"), ctx) + .size()); + privateCtor.set( + JavaLangAnalyser.findAccessibleConstructors( + typeElement(env, "test.PrivateCtor"), ctx) + .size()); }, CTOR_SOURCE, - DTO_SOURCE); + PRIVATE_CTOR_SOURCE); assertThat(compilation).succeeded(); - assertEquals(2, annotated.get()); - // widest ctor of Dto has 1 param - assertEquals(1, noAnnotation.get().map(c -> c.getParameters().size()).orElse(-1)); + assertEquals(3, twoCtor.get()); + assertEquals(1, privateCtor.get()); } @Test - void hasAccessibleConstructor_detectsPublicCtors() { - AtomicReference result = new AtomicReference<>(); + void findConstructorsAnnotatedWith_findsMarkedCtor() { + AtomicReference> annotated = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> + annotated.set( + JavaLangAnalyser.findConstructorsAnnotatedWith( + typeElement(env, "test.TwoCtor"), Deprecated.class, context(env))), + CTOR_SOURCE); + assertThat(compilation).succeeded(); + assertEquals(1, annotated.get().size()); + assertEquals(2, annotated.get().get(0).getParameters().size()); + } + + @Test + void findConstructorsAnnotatedWith_emptyWhenUnmarked() { + AtomicReference> annotated = new AtomicReference<>(); Compilation compilation = compileDto( (roundEnv, env) -> - result.set( - JavaLangAnalyser.hasAccessibleConstructor( - typeElement(env, "test.Dto"), context(env)))); + annotated.set( + JavaLangAnalyser.findConstructorsAnnotatedWith( + typeElement(env, "test.Dto"), Deprecated.class, context(env)))); assertThat(compilation).succeeded(); - assertTrue(result.get()); + assertTrue(annotated.get().isEmpty()); } } From 9314ab8eae61f73972b9d0bb18a47905ab759c2b Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:37:47 +0000 Subject: [PATCH 06/12] sonar: suppress S3516 on probe helper, try-with-resources for log capture --- .../codegen/testing/ProbeProcessor.java | 3 + .../codegen/testing/CodegenTestUtilsTest.java | 56 ++++++++++++------- 2 files changed, 38 insertions(+), 21 deletions(-) diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java index f4b0649d..aa84ff15 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java @@ -65,6 +65,9 @@ public class ProbeProcessor extends AbstractProcessor { * @param sources the compilation units to compile * @return whatever the probe produced */ + @SuppressWarnings( + "java:S3516") // the result is produced by the probe callback inside the compilation — static + // analysis sees {@code result} as never mutated public static T probe( BiFunction probe, JavaFileObject... sources) { AtomicReference result = new AtomicReference<>(); diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java index 6a04e33f..4979aafc 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java @@ -168,29 +168,43 @@ void printDiagnosticsAndSources_emitToLog() { .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); assertThat(compilation).succeeded(); - var captured = new StringBuilder(); - java.util.logging.Handler captureHandler = - new java.util.logging.Handler() { - @Override - public void publish(java.util.logging.LogRecord record) { - captured.append(record.getMessage()).append('\n'); - } - - @Override - public void flush() {} - - @Override - public void close() {} - }; - java.util.logging.Logger log = - java.util.logging.Logger.getLogger(CodegenTestUtils.class.getName()); - log.addHandler(captureHandler); - try { + String captured; + try (CapturingLogHandler handler = + new CapturingLogHandler( + java.util.logging.Logger.getLogger(CodegenTestUtils.class.getName()))) { CodegenTestUtils.printDiagnostics(compilation); CodegenTestUtils.printGeneratedSources(compilation); - } finally { - log.removeHandler(captureHandler); + captured = handler.output(); + } + assertTrue(captured.contains("Generated")); + } + + /** JUL handler capturing log records; detaches itself from its logger on {@link #close()}. */ + private static final class CapturingLogHandler extends java.util.logging.Handler + implements AutoCloseable { + private final StringBuilder records = new StringBuilder(); + private final java.util.logging.Logger logger; + + private CapturingLogHandler(java.util.logging.Logger logger) { + this.logger = logger; + logger.addHandler(this); + } + + @Override + public void publish(java.util.logging.LogRecord record) { + records.append(record.getMessage()).append('\n'); + } + + @Override + public void flush() {} + + @Override + public void close() { + logger.removeHandler(this); + } + + private String output() { + return records.toString(); } - assertTrue(captured.toString().contains("Generated")); } } From f4426a5a59523e456a69206b915f68eec3b5bd45 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:42:44 +0000 Subject: [PATCH 07/12] test: cover findTopLevelType on nested types --- .../analysis/JavaLangAnalyserTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java index cc9efe76..7e90f517 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -124,6 +124,16 @@ public PrivateCtor(String a) {} } """; + private static final String NESTED_SOURCE = + """ + package test; + public class Outer { + public static class Inner { + public static class Deep {} + } + } + """; + private static AnnotationProcessingContext context(ProcessingEnvironment processingEnv) { return new AnnotationProcessingContext( CapturingProcessingLogger.create().logger(), processingEnv); @@ -635,4 +645,26 @@ void findConstructorsAnnotatedWith_emptyWhenUnmarked() { assertThat(compilation).succeeded(); assertTrue(annotated.get().isEmpty()); } + + @Test + void findTopLevelType_walksToOutermostType() { + AtomicReference deepTop = new AtomicReference<>(); + AtomicReference outerTop = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, env) -> { + deepTop.set( + JavaLangAnalyser.findTopLevelType(typeElement(env, "test.Outer.Inner.Deep")) + .getSimpleName() + .toString()); + outerTop.set( + JavaLangAnalyser.findTopLevelType(typeElement(env, "test.Outer")) + .getSimpleName() + .toString()); + }, + NESTED_SOURCE); + assertThat(compilation).succeeded(); + assertEquals("Outer", deepTop.get()); + assertEquals("Outer", outerTop.get()); + } } From 6a43f788a5c14441a6975e213fda8c22b02e99de Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:51:27 +0000 Subject: [PATCH 08/12] test: cover own-output regeneration, manual-target clash and JDK gate --- .../MinimalCodegenProcessorTest.java | 178 +++++++++++++++++- 1 file changed, 174 insertions(+), 4 deletions(-) diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java index 189e1585..41a95ec8 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java @@ -26,17 +26,26 @@ import static com.google.testing.compile.CompilationSubject.assertThat; import static org.javahelpers.codegen.testing.CodegenTestUtils.loadGeneratedSource; import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.testing.compile.Compilation; +import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings; import org.javahelpers.codegen.analysis.JavaLangAnalyser; @@ -50,6 +59,7 @@ import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * A complete codegen processor in minimal form — only the domain members that have no generic @@ -78,19 +88,26 @@ public TypeName targetTypeName() { } } - /** A processor that generates a builder delegating to the target type's setters. */ - static class MinimalProcessor + /** + * A processor that generates a builder delegating to the target type's setters. Public so javac's + * {@code -processor} mechanism can instantiate it. + */ + public static class MinimalProcessor extends AbstractCodegenProcessor< AnnotationProcessingContext, CodegenConfiguration, MinimalTargetDefinition> { - MinimalProcessor() { - super( + public MinimalProcessor() { + this( CodegenProcessorConfiguration.builder() .elementCollector(ElementCollector.builder().selector(GenerateBuilder.class).build()) .loggerPrefix("minimal") .build()); } + MinimalProcessor(CodegenProcessorConfiguration configuration) { + super(configuration); + } + @Override protected AnnotationProcessingContext createContext( ProcessingEnvironment processingEnv, @@ -169,6 +186,18 @@ private static TypeName builderName(TypeElement target, AnnotationProcessingCont } } + /** MinimalProcessor variant declaring an unreachable minimum source level. */ + static class StrictJdkProcessor extends MinimalProcessor { + StrictJdkProcessor() { + super( + CodegenProcessorConfiguration.builder() + .elementCollector(ElementCollector.builder().selector(GenerateBuilder.class).build()) + .loggerPrefix("minimal") + .requiredSourceVersion("RELEASE_99") + .build()); + } + } + @Test void minimalProcessorGeneratesDelegatingBuilder() { // Given @@ -212,4 +241,145 @@ public Person build() { generatedCode, "generated PersonBuilder must match the expected source"); } + + /** + * A stale builder left in the generated-sources output is this processor's own previous output — + * it must be regenerated silently instead of producing the "already exists" warning. + * + *

Runs through real javac (not compile-testing) because the check compares the element's + * source location against the real {@code -s} output directory — the Filer's virtualized + * locations cannot express that setup. + */ + @Test + void regeneratesOwnPreviousOutput(@TempDir Path workDir) throws IOException { + Path generatedSources = workDir.resolve("generated-sources"); + Path stale = generatedSources.resolve("test").resolve("PersonBuilder.java"); + Files.createDirectories(stale.getParent()); + Files.writeString( + stale, + """ + package test; + public class PersonBuilder { + // leftover of a previous compilation + } + """); + + Path source = writeDto(workDir, "src"); + + List diagnostics = compileWithJavac(source, generatedSources, generatedSources); + assertTrue( + diagnostics.stream().noneMatch(d -> d.contains("already exists")), + () -> "unexpected 'already exists' warning: " + diagnostics); + + String regenerated = Files.readString(stale); + assertTrue( + regenerated.contains("public PersonBuilder name(String name)"), + () -> "stale file was not regenerated: " + regenerated); + } + + /** + * A hand-written class under the target's qualified name is not the processor's own output — the + * clash must still surface the "already exists" warning. + */ + @Test + void warnsOnManualTargetClash(@TempDir Path workDir) throws IOException { + Path generatedSources = workDir.resolve("generated-sources"); + Files.createDirectories(generatedSources); + Path sourceRoot = workDir.resolve("src"); + Path manual = sourceRoot.resolve("test").resolve("PersonBuilder.java"); + Files.createDirectories(manual.getParent()); + Files.writeString( + manual, + """ + package test; + public class PersonBuilder { + // hand-written class clashing with the generation target + } + """); + + Path source = writeDto(workDir, "src"); + + List diagnostics = compileWithJavac(source, generatedSources, sourceRoot); + assertTrue( + diagnostics.stream().anyMatch(d -> d.contains("already exists")), + () -> "expected 'already exists' warning: " + diagnostics); + } + + /** + * A {@code requiredSourceVersion} the running JDK cannot meet must report the graceful error and + * skip processing. + */ + @Test + void reportsErrorOnUnsupportedJdk() { + JavaFileObject source = + CodegenTestUtils.forSource( + """ + package test; + import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; + @GenerateBuilder + public class Person { + public void setName(String name) {} + } + """); + + Compilation compilation = + CodegenTestUtils.createCompiler(new StrictJdkProcessor()).compile(source); + + assertThat(compilation).failed(); + assertTrue( + compilation.errors().stream() + .map(d -> d.getMessage(null)) + .anyMatch(m -> m.contains("requires Java 99 or higher")), + () -> "expected unsupported-JDK error: " + compilation.errors()); + } + + private static Path writeDto(Path workDir, String sourceRootName) throws IOException { + Path source = sourceRootName.isEmpty() ? workDir : workDir.resolve(sourceRootName); + source = source.resolve("test").resolve("Person.java"); + Files.createDirectories(source.getParent()); + Files.writeString( + source, + """ + package test; + import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; + + @GenerateBuilder + public class Person { + private String name; + public void setName(String name) { this.name = name; } + } + """); + return source; + } + + /** + * Runs javac on {@code source} with the {@link MinimalProcessor}, {@code -s} pointing at {@code + * generatedSources} and {@code -sourcepath} at {@code sourcePath}; returns all diagnostics. + */ + private static List compileWithJavac(Path source, Path generatedSources, Path sourcePath) + throws IOException { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + try (StandardJavaFileManager fileManager = + compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) { + JavaCompiler.CompilationTask task = + compiler.getTask( + null, + fileManager, + diagnostics, + List.of( + "-d", + source.getParent().getParent().resolve("classes").toString(), + "-s", + generatedSources.toString(), + "-sourcepath", + sourcePath.toString(), + "-processor", + MinimalProcessor.class.getName()), + null, + fileManager.getJavaFileObjects(source)); + task.call(); + } + return diagnostics.getDiagnostics().stream().map(d -> d.getMessage(null)).toList(); + } } From 9f2433a0fa89e1eeefeae944eeb458d7b3afe4c3 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:09:16 +0000 Subject: [PATCH 09/12] test: extend simple-processor coverage (extractor, mapper, collector, context, options, failure paths) --- .../FieldAnnotationExtractorTest.java | 146 ++++++++++++++- .../codegen/analysis/JavaLangMapperTest.java | 160 +++++++++++++++++ .../AnnotationProcessingContextTest.java | 110 +++++++++++- .../AnnotationProcessingOptionsTest.java | 66 +++++++ .../processing/ElementCollectorTest.java | 110 ++++++++++++ .../MinimalCodegenProcessorTest.java | 166 ++++++++++++++++++ 6 files changed, 756 insertions(+), 2 deletions(-) create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingOptionsTest.java diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java index af1499c4..43f7298c 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java @@ -75,6 +75,11 @@ public class Dto { private String mode; @test.NonNull private String required; + private @test.NonNull String typed; + @test.Rich(tags = {"alpha", "beta"}, type = String.class, cond = test.ItemCondition.BAD) + private String rich; + @test.Rich(tags = {}) + private String richEmpty; private String plain; } """; @@ -88,11 +93,37 @@ public class Dto { private static final String NONNULL_ANNOTATION_SOURCE = """ package test; + @java.lang.annotation.Target({ + java.lang.annotation.ElementType.FIELD, + java.lang.annotation.ElementType.TYPE_USE + }) public @interface NonNull {} """; + private static final String ITEM_CONDITION_SOURCE = + """ + package test; + public enum ItemCondition { GOOD, BAD } + """; + + private static final String RICH_ANNOTATION_SOURCE = + """ + package test; + public @interface Rich { + String[] tags() default {}; + Class type() default Void.class; + ItemCondition cond() default ItemCondition.GOOD; + } + """; + private Compilation compileDto(BiConsumer probe) { - return compile(probe, DTO_SOURCE, DEFAULT_ANNOTATION_SOURCE, NONNULL_ANNOTATION_SOURCE); + return compile( + probe, + DTO_SOURCE, + DEFAULT_ANNOTATION_SOURCE, + NONNULL_ANNOTATION_SOURCE, + ITEM_CONDITION_SOURCE, + RICH_ANNOTATION_SOURCE); } @Test @@ -213,4 +244,117 @@ void formatDefaultExpression_keepsComplexExpressions() { "List.of()", FieldAnnotationExtractor.formatDefaultExpression("List.of()", TypeName.of(List.class))); } + + @Test + void extractDeprecatedAnnotation_nullElement_returnsEmpty() { + assertTrue(FieldAnnotationExtractor.extractDeprecatedAnnotation(null, null).isEmpty()); + } + + @Test + void extractDeprecatedAnnotation_ignoresOtherAnnotations() { + // 'mode' carries @Default but not @Deprecated — the mirror scan must fall through + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractDeprecatedAnnotation( + field(typeElement(processingEnv, "test.Dto"), "mode"), + context(processingEnv)))); + + assertThat(compilation).succeeded(); + assertTrue(result.get().isEmpty()); + } + + /** + * Type-use annotations live on the {@code TypeMirror}, not the element — {@code + * extractAnnotations} on the field's type must find them. + */ + @Test + void extractAnnotations_onTypeMirror_findsTypeUseAnnotation() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(typeElement(processingEnv, "test.Dto"), "typed").asType(), + context(processingEnv)))); + + assertThat(compilation).succeeded(); + assertEquals(1, result.get().size()); + assertEquals("NonNull", result.get().get(0).getAnnotationType().getClassName()); + } + + /** + * Enum constants, class literals and arrays are the non-trivial branches of {@code + * formatAnnotationValue}: enums get fully qualified, classes print as {@code .class}, arrays as + * {@code {...}}. + */ + @Test + void extractAnnotations_formatsEnumClassAndArrayMembers() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(typeElement(processingEnv, "test.Dto"), "rich"), + context(processingEnv)))); + + assertThat(compilation).succeeded(); + assertEquals(1, result.get().size()); + AnnotationDto rich = result.get().get(0); + assertEquals("test.ItemCondition.BAD", rich.getMembers().get("cond")); + assertTrue( + rich.getMembers().get("type").endsWith("String.class"), + () -> "type member: " + rich.getMembers().get("type")); + assertEquals("{\"alpha\", \"beta\"}", rich.getMembers().get("tags")); + } + + @Test + void extractAnnotations_emptyArrayMember_formatsAsEmptyBraces() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(typeElement(processingEnv, "test.Dto"), "richEmpty"), + context(processingEnv)))); + + assertThat(compilation).succeeded(); + assertEquals(1, result.get().size()); + assertEquals("{}", result.get().get(0).getMembers().get("tags")); + } + + @Test + void extractAnnotationValue_emptyWhenAnnotationHasNoValueMember() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotationValue( + field(typeElement(processingEnv, "test.Dto"), "required"), + Set.of("NonNull")))); + + assertThat(compilation).succeeded(); + assertTrue(result.get().isEmpty()); + } + + @Test + void extractAnnotationValue_emptyWhenNoNameMatches() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compileDto( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotationValue( + field(typeElement(processingEnv, "test.Dto"), "required"), + Set.of("Other")))); + + assertThat(compilation).succeeded(); + assertTrue(result.get().isEmpty()); + } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java index be597fbc..44d69fd8 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java @@ -30,6 +30,8 @@ import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.testing.compile.Compilation; import java.util.List; @@ -42,8 +44,10 @@ import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.GenericParameterDto; import org.javahelpers.codegen.model.type.TypeName; +import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNameList; import org.javahelpers.codegen.model.type.TypeNameMap; +import org.javahelpers.codegen.model.type.TypeNameNested; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameSet; import org.javahelpers.codegen.processing.AnnotationProcessingContext; @@ -338,4 +342,160 @@ public void setT(T t) {} assertEquals("TypeNameArray", result.get().get(0).getClass().getSimpleName()); assertEquals("T", result.get().get(1).getClassName()); } + + @Test + void mapToTypeName_nullElement_returnsNull() { + assertNull(JavaLangMapper.mapToTypeName(null, null)); + assertNull(JavaLangMapper.map2TypeName((TypeElement) null, null)); + } + + /** + * Every primitive kind has its own switch branch — map them all in one DTO to cover the whole + * {@code visitPrimitive} dispatch. + */ + @Test + void map2MethodParameter_mapsAllPrimitiveKinds() { + AtomicReference> result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + AnnotationProcessingContext ctx = context(processingEnv); + result.set( + List.of( + paramType(dto, "setB", 0, ctx), + paramType(dto, "setBy", 0, ctx), + paramType(dto, "setS", 0, ctx), + paramType(dto, "setI", 0, ctx), + paramType(dto, "setL", 0, ctx), + paramType(dto, "setC", 0, ctx), + paramType(dto, "setF", 0, ctx), + paramType(dto, "setD", 0, ctx))); + }, + """ + package test; + public class Dto { + public void setB(boolean b) {} + public void setBy(byte b) {} + public void setS(short s) {} + public void setI(int i) {} + public void setL(long l) {} + public void setC(char c) {} + public void setF(float f) {} + public void setD(double d) {} + } + """); + + assertThat(compilation).succeeded(); + List expected = + List.of("BOOLEAN", "BYTE", "SHORT", "INT", "LONG", "CHAR", "FLOAT", "DOUBLE"); + for (int i = 0; i < expected.size(); i++) { + assertInstanceOf(TypeNamePrimitive.class, result.get().get(i)); + assertEquals(expected.get(i), ((TypeNamePrimitive) result.get().get(i)).getType().name()); + } + } + + /** + * A parameter type that is a concrete non-JDK class with a public no-arg constructor is marked + * {@code hasEmptyConstructor} — the builder can instantiate it for nested construction. + */ + @Test + void map2MethodParameter_marksTypeWithEmptyConstructor() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> + result.set( + paramType( + typeElement(processingEnv, "test.Dto"), + "setAddress", + 0, + context(processingEnv))), + """ + package test; + public class Address { + public Address() {} + } + """, + """ + package test; + public class Dto { + public void setAddress(Address a) {} + } + """); + + assertThat(compilation).succeeded(); + assertTrue(result.get().hasEmptyConstructor()); + } + + /** + * A static nested class maps to {@link TypeNameNested} — the qualified class name keeps the + * {@code Outer.Inner} form. + */ + @Test + void map2MethodParameter_nestedType_mapsTypeNameNested() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> + result.set( + paramType( + typeElement(processingEnv, "test.Dto"), + "setInner", + 0, + context(processingEnv))), + """ + package test; + public class Outer { + public static class Inner {} + } + """, + """ + package test; + public class Dto { + public void setInner(Outer.Inner i) {} + } + """); + + assertThat(compilation).succeeded(); + assertInstanceOf(TypeNameNested.class, result.get()); + assertEquals("Outer.Inner", result.get().getClassName()); + } + + /** + * A {@code Map} implementation without a {@code Map}-parameter copy constructor cannot offer the + * generated map helpers — it falls back to a plain generic type name instead of {@code + * TypeNameMap}. + */ + @Test + void map2MethodParameter_fallsBackWhenMapLacksCopyConstructor() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + compile( + (roundEnv, processingEnv) -> + result.set( + paramType( + typeElement(processingEnv, "test.Dto"), + "setLookup", + 0, + context(processingEnv))), + """ + package test; + public class WeirdMap extends java.util.AbstractMap { + @Override + public java.util.Set> entrySet() { + return java.util.Set.of(); + } + } + """, + """ + package test; + public class Dto { + public void setLookup(WeirdMap lookup) {} + } + """); + + assertThat(compilation).succeeded(); + assertInstanceOf(TypeNameGeneric.class, result.get()); + } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java index 61736a4f..7450b987 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java @@ -35,6 +35,7 @@ import com.google.testing.compile.Compilation; import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; @@ -59,7 +60,7 @@ public class Dto extends Base { public String getName() { return name; } } class Base { - public void inherited() {} + void inherited() {} } """; @@ -228,4 +229,111 @@ void performanceTracker_defaultsToNoOp() { assertNotNull(tracker.get()); assertEquals("NoOpPerformanceTracker", tracker.get().getClass().getSimpleName()); } + + /** + * The element-attached and single-argument logging delegates forward to the logger — strict + * reporting promotes to error, lenient stays a warning. + */ + @Test + void loggingDelegates_fullSurface() { + CapturingProcessingLogger capture = CapturingProcessingLogger.createDebugEnabled(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + AnnotationProcessingContext ctx = + new AnnotationProcessingContext(capture.logger(), env); + ctx.info("plain info"); + ctx.debugEndOperation(); + ctx.debugEndOperation("closing %s", "op"); + ctx.warning(dto, "warn %s", "elem"); + ctx.error(dto, "err %s", "elem"); + ctx.reportBasedOnStrictMode(dto, "strict %s", "elem"); + ctx.reportBasedOnStrictMode("strict %s", "flat"); + AnnotationProcessingContext lenient = + new AnnotationProcessingContext( + capture.logger(), + env, + AnnotationProcessingOptions.builder() + .strictModeEnabled(false) + .build()); + lenient.reportBasedOnStrictMode(dto, "lenient %s", "elem"); + lenient.reportBasedOnStrictMode("lenient %s", "flat"); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + for (String expected : + List.of( + "plain info", + "closing op", + "warn elem", + "err elem", + "strict elem", + "strict flat", + "lenient elem", + "lenient flat")) { + assertTrue( + capture.messages().stream().anyMatch(m -> m.contains(expected)), + () -> "missing log line: " + expected); + } + } + + @Test + void getTypeElement_nullTypeName_returnsNull() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> result.set(context(env).getTypeElement((TypeName) null)))) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertNull(result.get()); + } + + /** + * With no current task, a member that is neither public nor private is not reachable from the + * generated package — the task's output package is the only grant. + */ + @Test + void isAccessibleFromGeneratedPackage_packagePrivateWithoutTask_denied() { + AtomicReference result = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Base"); + result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "inherited"))); + })) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertEquals(false, result.get()); + } + + /** + * {@code performanceTrackingEnabled} switches the context to the real tracker writing the report. + */ + @Test + void performanceTracker_activeWhenEnabled() { + AtomicReference tracker = new AtomicReference<>(); + Compilation compilation = + CodegenTestUtils.createCompiler( + new ProbeProcessor( + (roundEnv, env) -> + tracker.set( + new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), + env, + AnnotationProcessingOptions.builder() + .performanceTrackingEnabled(true) + .phaseHierarchy( + new org.javahelpers.codegen.logging.PhaseHierarchy( + List.of(), Map.of())) + .build()) + .getPerformanceTracker()))) + .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + assertThat(compilation).succeeded(); + assertEquals("ActivePerformanceTracker", tracker.get().getClass().getSimpleName()); + } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingOptionsTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingOptionsTest.java new file mode 100644 index 00000000..10da68db --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingOptionsTest.java @@ -0,0 +1,66 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.processing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import org.javahelpers.codegen.logging.PhaseHierarchy; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link AnnotationProcessingOptions}'s builder. */ +class AnnotationProcessingOptionsTest { + + @Test + void builder_setsAllOptions() { + PhaseHierarchy hierarchy = new PhaseHierarchy(List.of(), Map.of()); + AnnotationProcessingOptions options = + AnnotationProcessingOptions.builder() + .strictModeEnabled(false) + .performanceTrackingEnabled(true) + .performanceOutputFile("perf.txt") + .phaseHierarchy(hierarchy) + .build(); + + assertFalse(options.strictModeEnabled()); + assertTrue(options.performanceTrackingEnabled()); + assertEquals("perf.txt", options.performanceOutputFile()); + assertSame(hierarchy, options.phaseHierarchy()); + } + + @Test + void builder_defaults() { + AnnotationProcessingOptions options = AnnotationProcessingOptions.builder().build(); + + assertTrue(options.strictModeEnabled()); + assertFalse(options.performanceTrackingEnabled()); + assertNull(options.performanceOutputFile()); + } +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java index 0000edad..fb228649 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java @@ -27,6 +27,10 @@ import static org.junit.jupiter.api.Assertions.*; import java.lang.annotation.Annotation; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.util.List; import java.util.Set; import javax.lang.model.element.AnnotationMirror; @@ -40,11 +44,117 @@ import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.TypeMirror; import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import org.javahelpers.codegen.testing.CodegenTestUtils; +import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** Unit tests for {@link ElementCollector}. */ class ElementCollectorTest { + /** Direct-selection annotation for the round tests. */ + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.RUNTIME) + public @interface Selected {} + + /** Opt-out annotation for the round tests. */ + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.RUNTIME) + public @interface Skipped {} + + /** Meta-marker annotation for the round tests. */ + @Target(ElementType.ANNOTATION_TYPE) + @Retention(RetentionPolicy.RUNTIME) + public @interface Marker {} + + private static final String DTO_SOURCE = + """ + package test; + import org.javahelpers.codegen.processing.ElementCollectorTest.Selected; + import org.javahelpers.codegen.processing.ElementCollectorTest.Skipped; + import org.javahelpers.codegen.processing.ElementCollectorTest.TemplateHolder; + @Selected + public class Beta {} + @Selected @Skipped + class Alpha {} + @TemplateHolder.Template + class Gamma {} + """; + + /** + * Holds the template annotation so the compiled source can reference it as a nested type of a + * classpath-visible class. + */ + public static class TemplateHolder { + /** Annotation meta-marked with {@link Marker}. */ + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.RUNTIME) + @Marker + public @interface Template {} + } + + /** + * Elements carrying the opt-out annotation are dropped from a direct selection — and a debug line + * explains the drop. + */ + @Test + void collect_optOutAnnotationRemovesSelected() { + ElementCollector collector = + ElementCollector.builder() + .selector( + selector -> + selector + .groupName("selected") + .annotationTypes(Selected.class) + .optOutAnnotation(Skipped.class)) + .build(); + CapturingProcessingLogger capture = CapturingProcessingLogger.createDebugEnabled(); + + ElementGroups groups = + ProbeProcessor.probe( + (roundEnv, env) -> collector.collect(Set.of(), roundEnv, capture.logger()), + CodegenTestUtils.forSource(DTO_SOURCE)); + + List names = + groups.byGroup("selected").stream() + .map(element -> element.getSimpleName().toString()) + .toList(); + assertEquals(List.of("Beta"), names); + assertTrue( + capture.messages().stream() + .anyMatch(message -> message.contains("Skipping element 'Alpha'")), + () -> "expected opt-out debug line: " + capture.messages()); + } + + /** + * An annotation type meta-annotated with the marker selects elements too — the only way + * user-defined annotation types can be discovered. + */ + @Test + void collect_metaMarkerSelectsTemplateAnnotated() { + ElementCollector collector = + ElementCollector.builder() + .selector(selector -> selector.groupName("templated").metaMarker(Marker.class)) + .build(); + + ElementGroups groups = + ProbeProcessor.probe( + (roundEnv, env) -> + collector.collect( + Set.of( + env.getElementUtils() + .getTypeElement( + "org.javahelpers.codegen.processing.ElementCollectorTest.TemplateHolder.Template")), + roundEnv, + CapturingProcessingLogger.create().logger()), + CodegenTestUtils.forSource(DTO_SOURCE)); + + List names = + groups.byGroup("templated").stream() + .map(element -> element.getSimpleName().toString()) + .toList(); + assertEquals(List.of("Gamma"), names); + } + @Test void collect_nonAnnotationTypeElementsAreSkipped() { ElementCollector collector = diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java index 41a95ec8..25bcaa0a 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java @@ -198,6 +198,68 @@ static class StrictJdkProcessor extends MinimalProcessor { } } + /** + * MinimalProcessor whose analysis always fails — and without a configured logger prefix, so the + * simple class name becomes the diagnostic prefix. + */ + static class FailingProcessor extends MinimalProcessor { + FailingProcessor() { + super( + CodegenProcessorConfiguration.builder() + .elementCollector(ElementCollector.builder().selector(GenerateBuilder.class).build()) + .build()); + } + + @Override + protected List analyse( + CodegenTask task, AnnotationProcessingContext ctx) { + throw new IllegalStateException("boom"); + } + } + + /** MinimalProcessor whose analysis produces nothing. */ + static class EmptyProcessor extends MinimalProcessor { + @Override + protected List analyse( + CodegenTask task, AnnotationProcessingContext ctx) { + return List.of(); + } + } + + /** MinimalProcessor whose planning produces no tasks. */ + static class NoTasksProcessor extends MinimalProcessor { + @Override + protected List> planTasks( + ElementGroups collected, AnnotationProcessingContext ctx) { + return List.of(); + } + } + + /** Verbose compiler option understood by {@link VerboseProcessor}. */ + private static final CompilerOption VERBOSE = + new CompilerOption() { + @Override + public String getOptionName() { + return "verbose"; + } + + @Override + public String getCompilerArgument() { + return "verbose"; + } + }; + + /** MinimalProcessor with the verbose option declared — {@code -Averbose=true} switches logger. */ + static class VerboseProcessor extends MinimalProcessor { + VerboseProcessor() { + super( + CodegenProcessorConfiguration.builder() + .elementCollector(ElementCollector.builder().selector(GenerateBuilder.class).build()) + .optionRegistry(ProcessorOptionRegistry.builder().verboseOption(VERBOSE).build()) + .build()); + } + } + @Test void minimalProcessorGeneratesDelegatingBuilder() { // Given @@ -333,6 +395,110 @@ public void setName(String name) {} () -> "expected unsupported-JDK error: " + compilation.errors()); } + /** + * An exception thrown by {@code analyse} is reported per task — strict mode (the default) + * promotes it to an error carrying the processor's class name as prefix. + */ + @Test + void failsWhenAnalysisThrows() { + JavaFileObject source = + CodegenTestUtils.forSource( + """ + package test; + import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; + @GenerateBuilder + public class Person { + public void setName(String name) {} + } + """); + + Compilation compilation = + CodegenTestUtils.createCompiler(new FailingProcessor()).compile(source); + + assertThat(compilation).failed(); + assertTrue( + compilation.errors().stream() + .map(d -> d.getMessage(null)) + .anyMatch( + m -> + m.contains("Failed to generate target - boom") + && m.contains("FailingProcessor")), + () -> "expected per-task failure error: " + compilation.errors()); + } + + /** + * An empty {@code analyse} result is legal — the round produces no targets and the compilation + * still succeeds. + */ + @Test + void succeedsWhenAnalysisIsEmpty() { + JavaFileObject source = + CodegenTestUtils.forSource( + """ + package test; + import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; + @GenerateBuilder + public class Person { + public void setName(String name) {} + } + """); + + Compilation compilation = CodegenTestUtils.createCompiler(new EmptyProcessor()).compile(source); + + assertThat(compilation).succeeded(); + } + + /** + * An empty {@code planTasks} result ends the round without work — the compilation still succeeds. + */ + @Test + void succeedsWhenNoTasksPlanned() { + JavaFileObject source = + CodegenTestUtils.forSource( + """ + package test; + import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; + @GenerateBuilder + public class Person { + public void setName(String name) {} + } + """); + + Compilation compilation = + CodegenTestUtils.createCompiler(new NoTasksProcessor()).compile(source); + + assertThat(compilation).succeeded(); + } + + /** {@code -Averbose=true} switches the logger to verbose output — generation still works. */ + @Test + void generatesInVerboseMode() { + JavaFileObject source = + CodegenTestUtils.forSource( + """ + package test; + import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; + @GenerateBuilder + public class Person { + public void setName(String name) {} + } + """); + + Compilation compilation = + CodegenTestUtils.createCompiler(new VerboseProcessor()) + .withOptions("-Averbose=true") + .compile(source); + + assertThat(compilation).succeeded(); + String generatedCode = + CodegenTestUtils.readSource( + compilation.generatedFiles().stream() + .filter(f -> f.getName().endsWith("PersonBuilder.java")) + .findFirst() + .orElseThrow(() -> new AssertionError("no PersonBuilder.java generated"))); + assertTrue(generatedCode.contains("public PersonBuilder name(String name)")); + } + private static Path writeDto(Path workDir, String sourceRootName) throws IOException { Path source = sourceRootName.isEmpty() ? workDir : workDir.resolve(sourceRootName); source = source.resolve("test").resolve("Person.java"); From 7636adb222a0f614e70d39282d05bffa351d9ee1 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:43:28 +0000 Subject: [PATCH 10/12] test utils: shared probe/compile helpers, review feedback - CodegenTestUtils.probe(...) wraps ProbeProcessor + compile (JavaFileObject/String/List sources) - ProcessingTestUtils.context shared across simple-processor tests - TestingGenerationEnvironment.create() default capturing logger - CapturingLogHandler promoted to codegen-testing util - TypeName.toString() returns qualified name; TypeNameGeneric varargs via Arrays.stream - ElementTestUtils method-ref parameter matching - static helpers moved to end of test classes; per-test compile/context helpers removed --- .../codegen/model/type/TypeName.java | 6 + .../codegen/model/type/TypeNameGeneric.java | 3 +- .../roaster/RoasterCodeGeneratorTest.java | 139 +++++---- .../codegen/testing/CapturingLogHandler.java | 70 +++++ .../codegen/testing/CodegenTestUtils.java | 46 +++ .../codegen/testing/ElementTestUtils.java | 4 +- .../testing/TestingGenerationEnvironment.java | 8 + .../codegen/testing/CodegenTestUtilsTest.java | 101 ++----- .../FieldAnnotationExtractorTest.java | 99 +++---- .../analysis/JavaLangAnalyserTest.java | 118 ++++---- .../codegen/analysis/JavaLangMapperTest.java | 63 ++-- .../AnnotationProcessingContextTest.java | 271 ++++++++---------- .../processing/ProcessingTestUtils.java | 48 ++++ 13 files changed, 520 insertions(+), 456 deletions(-) create mode 100644 codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java create mode 100644 simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessingTestUtils.java diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeName.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeName.java index fc1f23dd..aa7068da 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeName.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeName.java @@ -104,6 +104,12 @@ public String getFullQualifiedName() { return packageName.isEmpty() ? className : packageName + "." + className; } + /** Returns the full qualified name of this type. */ + @Override + public String toString() { + return getFullQualifiedName(); + } + /** * Returns the list of annotations on this type. * diff --git a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java index 03d97e57..a8f6519d 100644 --- a/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java +++ b/codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java @@ -23,6 +23,7 @@ */ package org.javahelpers.codegen.model.type; +import java.util.Arrays; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.builder.EqualsBuilder; @@ -111,7 +112,7 @@ public TypeNameGeneric(String packageName, String className, TypeName... innerTy public TypeNameGeneric(Class outerType, Class... innerTypeArguments) { this( TypeName.of(outerType), - java.util.Arrays.stream(innerTypeArguments).map(TypeName::of).toArray(TypeName[]::new)); + Arrays.stream(innerTypeArguments).map(TypeName::of).toArray(TypeName[]::new)); } /** diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index 71934c49..97508fe5 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -29,7 +29,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; -import org.javahelpers.codegen.SourceFormatter; import org.javahelpers.codegen.enums.AccessModifier; import org.javahelpers.codegen.enums.FormattingMode; import org.javahelpers.codegen.model.annotation.AnnotationDto; @@ -46,7 +45,6 @@ import org.javahelpers.codegen.model.type.TypeNameGeneric; import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameVariable; -import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.javahelpers.codegen.testing.TestingGenerationEnvironment; import org.junit.jupiter.api.Test; @@ -57,52 +55,9 @@ */ class RoasterCodeGeneratorTest { - /** A builder-style DTO: private target field, one delegating setter, one build method. */ - private static GenerationTargetClassDto personBuilderDefinition() { - TypeName builderType = new TypeName("test", "PersonBuilder"); - TypeName personType = new TypeName("test", "Person"); - - GenerationTargetClassDto target = new GenerationTargetClassDto(); - target.setTypeName(builderType); - target.setClassAccessModifier(AccessModifier.PUBLIC); - target.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName("target"); - field.setFieldType(personType); - field.setVisibility(AccessModifier.PRIVATE); - field.setLiteralInitializer("new Person()"); - target.addClassField(field); - - MethodDto name = new MethodDto("name", builderType); - name.setModifier(AccessModifier.PUBLIC); - MethodParameterDto param = new MethodParameterDto(); - param.setParameterName("name"); - param.setParameterTypeName(new TypeName("java.lang", "String")); - name.addParameter(param); - name.setCode( - """ - target.setName(name); - return this;"""); - target.addMethod(name); - - MethodDto build = new MethodDto("build", personType); - build.setModifier(AccessModifier.PUBLIC); - build.setCode("return target;"); - target.addMethod(build); - return target; - } - @Test void generatesDelegatingBuilderFromDto() throws Exception { - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); - TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); - RoasterCodeGenerator generator = new RoasterCodeGenerator(env); - SourceFormatter formatter = new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE); - - generator.generateClass(personBuilderDefinition(), formatter); - - assertNormalizedEquals( + assertGeneratedSource( """ package test; public class PersonBuilder { @@ -118,25 +73,17 @@ public Person build() { return target; } }""", - env.generatedSource(), - "generated PersonBuilder must match the expected source"); + personBuilderDefinition()); } @Test void writesFileUnderQualifiedName() throws Exception { - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); - TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); - RoasterCodeGenerator generator = new RoasterCodeGenerator(env); - GenerationTargetClassDto empty = new GenerationTargetClassDto(); empty.setTypeName(new TypeName("com.example", "EmptyBuilder")); empty.setClassAccessModifier(AccessModifier.PUBLIC); empty.setFormattingMode(FormattingMode.NONE); - generator.generateClass( - empty, new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE)); - - assertEquals("mem:///com/example/EmptyBuilder.java", env.writtenUri().toString()); + assertEquals("mem:///com/example/EmptyBuilder.java", generate(empty).writtenUri().toString()); } @Test @@ -155,7 +102,7 @@ void generatesClassMetadataJavadocAndAnnotations() throws Exception { classDef.addInterface(iface); assertContaining( - generate(classDef), + generate(classDef).generatedSource(), "* Builder for {@link Person}.", "@Generated(\"simple-builders\")", "public class AnnotatedBuilder extends AbstractBuilder implements Serializable"); @@ -186,7 +133,7 @@ void generatesGenericClassAndMethods() throws Exception { classDef.addMethod(genericMethod); assertContaining( - generate(classDef), + generate(classDef).generatedSource(), "public class GenericBuilder", "public static T of(R input) {", "return null;"); @@ -217,7 +164,7 @@ void generatesConstructorAndFieldVariants() throws Exception { ctor.addParameter(param); classDef.addConstructor(ctor); - assertNormalizedEquals( + assertGeneratedSource( """ package test; import test.anno.NonNull; @@ -226,8 +173,7 @@ public class CtorBuilder { protected CtorBuilder(int capacity) { } }""", - generate(classDef), - "generated CtorBuilder must match the expected source"); + classDef); } @Test @@ -248,7 +194,7 @@ void generatesNestedTypesWithMembers() throws Exception { nested.addMethod(nestedMethod); classDef.addNestedType(nested); - assertNormalizedEquals( + assertGeneratedSource( """ package test; public class OuterBuilder { @@ -260,8 +206,7 @@ public void assist() { } } }""", - generate(classDef), - "generated OuterBuilder must match the expected source"); + classDef); } @Test @@ -292,7 +237,7 @@ void generatesMethodWithJavadocAnnotationsAndTypedParameters() throws Exception method.setCode("return null;"); classDef.addMethod(method); - assertNormalizedEquals( + assertGeneratedSource( """ package test; import java.util.List; @@ -307,16 +252,62 @@ public List items(List values) { return null; } }""", - generate(classDef), - "generated RichBuilder must match the expected source"); + classDef); + } + + /** + * Generates {@code classDef} into a fresh {@link TestingGenerationEnvironment} and returns it. + */ + private static TestingGenerationEnvironment generate(GenerationTargetClassDto classDef) + throws Exception { + TestingGenerationEnvironment env = TestingGenerationEnvironment.create(); + new RoasterCodeGenerator(env) + .generateClass(classDef, new RoasterSourceFormatter(env.getLogger(), FormattingMode.NONE)); + return env; } - private static String generate(GenerationTargetClassDto classDef) throws Exception { - CapturingProcessingLogger capturing = CapturingProcessingLogger.create(); - TestingGenerationEnvironment env = TestingGenerationEnvironment.create(capturing.logger()); - RoasterCodeGenerator generator = new RoasterCodeGenerator(env); - generator.generateClass( - classDef, new RoasterSourceFormatter(capturing.logger(), FormattingMode.NONE)); - return env.generatedSource(); + /** Generates {@code classDef} and compares the emitted source against {@code expected}. */ + private static void assertGeneratedSource(String expected, GenerationTargetClassDto classDef) + throws Exception { + assertNormalizedEquals( + expected, + generate(classDef).generatedSource(), + "generated " + classDef.getTypeName().getClassName() + " must match the expected source"); + } + + /** A builder-style DTO: private target field, one delegating setter, one build method. */ + private static GenerationTargetClassDto personBuilderDefinition() { + TypeName builderType = new TypeName("test", "PersonBuilder"); + TypeName personType = new TypeName("test", "Person"); + + GenerationTargetClassDto target = new GenerationTargetClassDto(); + target.setTypeName(builderType); + target.setClassAccessModifier(AccessModifier.PUBLIC); + target.setFormattingMode(FormattingMode.NONE); + + ClassFieldDto field = new ClassFieldDto(); + field.setFieldName("target"); + field.setFieldType(personType); + field.setVisibility(AccessModifier.PRIVATE); + field.setLiteralInitializer("new Person()"); + target.addClassField(field); + + MethodDto name = new MethodDto("name", builderType); + name.setModifier(AccessModifier.PUBLIC); + MethodParameterDto param = new MethodParameterDto(); + param.setParameterName("name"); + param.setParameterTypeName(new TypeName("java.lang", "String")); + name.addParameter(param); + name.setCode( + """ + target.setName(name); + return this;"""); + target.addMethod(name); + + MethodDto build = new MethodDto("build", personType); + build.setModifier(AccessModifier.PUBLIC); + build.setCode("return target;"); + target.addMethod(build); + return target; } } diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java new file mode 100644 index 00000000..0c9846c8 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java @@ -0,0 +1,70 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.testing; + +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +/** + * JUL {@link Handler} capturing the log records of a logger so tests can assert on emitted + * messages. Attach via try-with-resources; the handler detaches itself from the logger on {@link + * #close()}. + * + *
{@code
+ * try (CapturingLogHandler handler = new CapturingLogHandler(Logger.getLogger("my.Logger"))) {
+ *   codeUnderTest.run();
+ *   assertTrue(handler.output().contains("expected message"));
+ * }
+ * }
+ */ +public final class CapturingLogHandler extends Handler implements AutoCloseable { + + private final StringBuilder records = new StringBuilder(); + private final Logger logger; + + public CapturingLogHandler(Logger logger) { + this.logger = logger; + logger.addHandler(this); + } + + @Override + public void publish(LogRecord record) { + records.append(record.getMessage()).append('\n'); + } + + @Override + public void flush() {} + + /** All captured record messages, one per line. */ + public String output() { + return records.toString(); + } + + @Override + public void close() { + logger.removeHandler(this); + } +} diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CodegenTestUtils.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CodegenTestUtils.java index 16a5b24c..84f88b56 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CodegenTestUtils.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CodegenTestUtils.java @@ -29,11 +29,16 @@ import com.google.testing.compile.JavaFileObjects; import java.io.IOException; import java.io.UncheckedIOException; +import java.util.Arrays; +import java.util.List; +import java.util.function.BiConsumer; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; +import javax.annotation.processing.RoundEnvironment; import javax.tools.JavaFileObject; import org.junit.jupiter.api.Assertions; @@ -71,6 +76,47 @@ public static Compiler createCompiler(Processor... processors) { return Compiler.javac().withProcessors(processors); } + /** + * Compiles the given sources with a {@link ProbeProcessor} running {@code probe} in the first + * processing round and returns the compilation. + * + * @param probe callback receiving the {@link RoundEnvironment} and {@link ProcessingEnvironment} + * @param sources the source files to compile + * @return the compilation result + */ + public static Compilation probe( + BiConsumer probe, JavaFileObject... sources) { + return createCompiler(new ProbeProcessor(probe)).compile(sources); + } + + /** + * Compiles the given source texts (via {@link #forSource}) with a {@link ProbeProcessor} running + * {@code probe} in the first processing round and returns the compilation. + * + * @param probe callback receiving the {@link RoundEnvironment} and {@link ProcessingEnvironment} + * @param sources the Java source texts to compile + * @return the compilation result + */ + public static Compilation probe( + BiConsumer probe, String... sources) { + return probe( + probe, + Arrays.stream(sources).map(CodegenTestUtils::forSource).toArray(JavaFileObject[]::new)); + } + + /** + * Compiles the given source texts (via {@link #forSource}) with a {@link ProbeProcessor} running + * {@code probe} in the first processing round and returns the compilation. + * + * @param probe callback receiving the {@link RoundEnvironment} and {@link ProcessingEnvironment} + * @param sources the Java source texts to compile + * @return the compilation result + */ + public static Compilation probe( + BiConsumer probe, List sources) { + return probe(probe, sources.toArray(String[]::new)); + } + /** * Asserts that none of the compilation's warnings contains the given text (case-insensitive). * diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java index 23c23315..a8d95570 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java @@ -30,6 +30,7 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeMirror; /** * Look-ups for {@code javax.lang.model} elements during a live compilation — used inside {@link @@ -89,7 +90,8 @@ public static ExecutableElement method( .filter( e -> e.getParameters().stream() - .map(p -> p.asType().toString()) + .map(VariableElement::asType) + .map(TypeMirror::toString) .toList() .equals(List.of(parameterTypes))), "method '" diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java index 0f8231f7..07cc045f 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java @@ -61,6 +61,14 @@ public static TestingGenerationEnvironment create(ProcessingLogger logger) { return new TestingGenerationEnvironment(logger, true); } + /** + * Environment with a default {@link CapturingProcessingLogger} whose {@code createSourceFile} + * captures the emitted source in memory. + */ + public static TestingGenerationEnvironment create() { + return new TestingGenerationEnvironment(CapturingProcessingLogger.create().logger(), true); + } + /** * Environment whose {@code createSourceFile} returns {@code null} — the file-write step fails * deterministically on it. diff --git a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java index 4979aafc..d8241a35 100644 --- a/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java @@ -30,48 +30,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.testing.compile.Compilation; -import java.util.Set; -import javax.annotation.processing.AbstractProcessor; -import javax.annotation.processing.RoundEnvironment; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.TypeElement; import javax.tools.JavaFileObject; import org.junit.jupiter.api.Test; /** Unit tests for {@link CodegenTestUtils} — the compile-testing helpers themselves. */ class CodegenTestUtilsTest { - /** Emits one fixed generated source file so {@code loadGeneratedSource} has something to read. */ - private static class EmittingProcessor extends AbstractProcessor { - private boolean ran; - - @Override - public SourceVersion getSupportedSourceVersion() { - return SourceVersion.latestSupported(); - } - - @Override - public Set getSupportedAnnotationTypes() { - return Set.of("*"); - } - - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { - if (!ran && !roundEnv.processingOver()) { - ran = true; - try { - var file = processingEnv.getFiler().createSourceFile("test.Generated"); - try (var writer = file.openWriter()) { - writer.write("package test;\npublic class Generated {}\n"); - } - } catch (java.io.IOException e) { - throw new IllegalStateException(e); - } - } - return false; - } - } - @Test void forSource_derivesQualifiedNameFromSource() { JavaFileObject file = @@ -118,8 +82,9 @@ public class Dto { @Test void loadGeneratedSource_readsEmittedFile() { Compilation compilation = - CodegenTestUtils.createCompiler(new EmittingProcessor()) - .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + CodegenTestUtils.probe( + (roundEnv, env) -> emitGeneratedSource(env), + CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); assertThat(compilation).succeeded(); assertEquals( @@ -140,19 +105,18 @@ void loadGeneratedSource_failsForMissingFile() { @Test void assertNoWarningContaining_passesWithoutMatchingWarning() { + final String warningMessage = "a warning"; Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> - env.getMessager() - .printMessage(javax.tools.Diagnostic.Kind.WARNING, "a warning"))) - .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + CodegenTestUtils.probe( + (roundEnv, env) -> + env.getMessager().printMessage(javax.tools.Diagnostic.Kind.WARNING, warningMessage), + CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); assertThat(compilation).succeeded(); CodegenTestUtils.assertNoWarningContaining(compilation, "never emitted"); assertThrows( AssertionError.class, - () -> CodegenTestUtils.assertNoWarningContaining(compilation, "warning")); + () -> CodegenTestUtils.assertNoWarningContaining(compilation, warningMessage)); } @Test @@ -164,8 +128,9 @@ void readSource_readsForSourceContent() { @Test void printDiagnosticsAndSources_emitToLog() { Compilation compilation = - CodegenTestUtils.createCompiler(new EmittingProcessor()) - .compile(CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + CodegenTestUtils.probe( + (roundEnv, env) -> emitGeneratedSource(env), + CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); assertThat(compilation).succeeded(); String captured; @@ -176,35 +141,23 @@ void printDiagnosticsAndSources_emitToLog() { CodegenTestUtils.printGeneratedSources(compilation); captured = handler.output(); } - assertTrue(captured.contains("Generated")); + assertTrue(captured.contains("Compilation Diagnostics")); + assertTrue(captured.contains("Generated Source Files")); + assertTrue(captured.contains("Generated.java")); + assertTrue(captured.contains("public class Generated")); } - /** JUL handler capturing log records; detaches itself from its logger on {@link #close()}. */ - private static final class CapturingLogHandler extends java.util.logging.Handler - implements AutoCloseable { - private final StringBuilder records = new StringBuilder(); - private final java.util.logging.Logger logger; - - private CapturingLogHandler(java.util.logging.Logger logger) { - this.logger = logger; - logger.addHandler(this); - } - - @Override - public void publish(java.util.logging.LogRecord record) { - records.append(record.getMessage()).append('\n'); - } - - @Override - public void flush() {} - - @Override - public void close() { - logger.removeHandler(this); - } - - private String output() { - return records.toString(); + /** + * Writes one fixed generated source file so {@code loadGeneratedSource} has something to read. + */ + private static void emitGeneratedSource(javax.annotation.processing.ProcessingEnvironment env) { + try { + var file = env.getFiler().createSourceFile("test.Generated"); + try (var writer = file.openWriter()) { + writer.write("package test;\npublic class Generated {}\n"); + } + } catch (java.io.IOException e) { + throw new IllegalStateException(e); } } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java index 43f7298c..3a9be519 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.analysis; import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.field; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -36,35 +37,14 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiConsumer; -import javax.annotation.processing.ProcessingEnvironment; -import javax.annotation.processing.RoundEnvironment; -import javax.tools.JavaFileObject; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.type.TypeName; -import org.javahelpers.codegen.processing.AnnotationProcessingContext; -import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.javahelpers.codegen.testing.CodegenTestUtils; -import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** Unit tests for {@link FieldAnnotationExtractor} against elements captured from a compilation. */ class FieldAnnotationExtractorTest { - private static TypeMappingContext context(ProcessingEnvironment processingEnv) { - return new AnnotationProcessingContext( - CapturingProcessingLogger.create().logger(), processingEnv); - } - - private static Compilation compile( - BiConsumer probe, String... sources) { - JavaFileObject[] files = - java.util.Arrays.stream(sources) - .map(CodegenTestUtils::forSource) - .toArray(JavaFileObject[]::new); - return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)).compile(files); - } - private static final String DTO_SOURCE = """ package test; @@ -116,46 +96,42 @@ public enum ItemCondition { GOOD, BAD } } """; - private Compilation compileDto(BiConsumer probe) { - return compile( - probe, - DTO_SOURCE, - DEFAULT_ANNOTATION_SOURCE, - NONNULL_ANNOTATION_SOURCE, - ITEM_CONDITION_SOURCE, - RICH_ANNOTATION_SOURCE); - } + private static final List DTO_SOURCES = + List.of( + DTO_SOURCE, + DEFAULT_ANNOTATION_SOURCE, + NONNULL_ANNOTATION_SOURCE, + ITEM_CONDITION_SOURCE, + RICH_ANNOTATION_SOURCE); @Test void extractDeprecatedAnnotation_findsDeprecatedField() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractDeprecatedAnnotation( field(typeElement(processingEnv, "test.Dto"), "legacy"), - context(processingEnv)))); + context(processingEnv))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertTrue(result.get().isPresent()); - assertEquals( - "java.lang.Deprecated", - result.get().get().getAnnotationType().getPackageName() - + "." - + result.get().get().getAnnotationType().getClassName()); + assertEquals("java.lang.Deprecated", result.get().get().getAnnotationType().toString()); } @Test void extractDeprecatedAnnotation_emptyForPlainField() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractDeprecatedAnnotation( field(typeElement(processingEnv, "test.Dto"), "plain"), - context(processingEnv)))); + context(processingEnv))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertTrue(result.get().isEmpty()); @@ -165,12 +141,13 @@ void extractDeprecatedAnnotation_emptyForPlainField() { void extractAnnotations_returnsMemberValues() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotations( field(typeElement(processingEnv, "test.Dto"), "mode"), - context(processingEnv)))); + context(processingEnv))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertEquals(1, result.get().size()); @@ -184,12 +161,13 @@ void hasNonNullConstraint_detectsNonNullAnnotation() { AtomicReference nonNull = new AtomicReference<>(); AtomicReference plain = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { var dto = typeElement(processingEnv, "test.Dto"); nonNull.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "required"))); plain.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "plain"))); - }); + }, + DTO_SOURCES); assertThat(compilation).succeeded(); assertTrue(nonNull.get()); @@ -200,11 +178,12 @@ void hasNonNullConstraint_detectsNonNullAnnotation() { void extractAnnotationValue_matchesAnnotationBySimpleName() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotationValue( - field(typeElement(processingEnv, "test.Dto"), "mode"), Set.of("Default")))); + field(typeElement(processingEnv, "test.Dto"), "mode"), Set.of("Default"))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertEquals(Optional.of("GENERAL"), result.get()); @@ -255,12 +234,13 @@ void extractDeprecatedAnnotation_ignoresOtherAnnotations() { // 'mode' carries @Default but not @Deprecated — the mirror scan must fall through AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractDeprecatedAnnotation( field(typeElement(processingEnv, "test.Dto"), "mode"), - context(processingEnv)))); + context(processingEnv))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertTrue(result.get().isEmpty()); @@ -274,12 +254,13 @@ void extractDeprecatedAnnotation_ignoresOtherAnnotations() { void extractAnnotations_onTypeMirror_findsTypeUseAnnotation() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotations( field(typeElement(processingEnv, "test.Dto"), "typed").asType(), - context(processingEnv)))); + context(processingEnv))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertEquals(1, result.get().size()); @@ -295,12 +276,13 @@ void extractAnnotations_onTypeMirror_findsTypeUseAnnotation() { void extractAnnotations_formatsEnumClassAndArrayMembers() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotations( field(typeElement(processingEnv, "test.Dto"), "rich"), - context(processingEnv)))); + context(processingEnv))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertEquals(1, result.get().size()); @@ -316,12 +298,13 @@ void extractAnnotations_formatsEnumClassAndArrayMembers() { void extractAnnotations_emptyArrayMember_formatsAsEmptyBraces() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotations( field(typeElement(processingEnv, "test.Dto"), "richEmpty"), - context(processingEnv)))); + context(processingEnv))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertEquals(1, result.get().size()); @@ -332,12 +315,13 @@ void extractAnnotations_emptyArrayMember_formatsAsEmptyBraces() { void extractAnnotationValue_emptyWhenAnnotationHasNoValueMember() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotationValue( field(typeElement(processingEnv, "test.Dto"), "required"), - Set.of("NonNull")))); + Set.of("NonNull"))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertTrue(result.get().isEmpty()); @@ -347,12 +331,13 @@ void extractAnnotationValue_emptyWhenAnnotationHasNoValueMember() { void extractAnnotationValue_emptyWhenNoNameMatches() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( FieldAnnotationExtractor.extractAnnotationValue( field(typeElement(processingEnv, "test.Dto"), "required"), - Set.of("Other")))); + Set.of("Other"))), + DTO_SOURCES); assertThat(compilation).succeeded(); assertTrue(result.get().isEmpty()); diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java index 7e90f517..0bf46e85 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.analysis; import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.field; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; @@ -38,23 +39,17 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiConsumer; -import javax.annotation.processing.ProcessingEnvironment; -import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; -import javax.tools.JavaFileObject; import org.javahelpers.codegen.analysis.JavaLangAnalyser.ReadableProperty; import org.javahelpers.codegen.analysis.testannotations.Tag; import org.javahelpers.codegen.analysis.testannotations.Tags; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.processing.AnnotationProcessingContext; -import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.javahelpers.codegen.testing.CodegenTestUtils; -import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** Unit tests for {@link JavaLangAnalyser} against elements captured from a real compilation. */ @@ -134,30 +129,12 @@ public static class Deep {} } """; - private static AnnotationProcessingContext context(ProcessingEnvironment processingEnv) { - return new AnnotationProcessingContext( - CapturingProcessingLogger.create().logger(), processingEnv); - } - - private static Compilation compile( - BiConsumer probe, String... sources) { - JavaFileObject[] files = - java.util.Arrays.stream(sources) - .map(CodegenTestUtils::forSource) - .toArray(JavaFileObject[]::new); - return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)).compile(files); - } - - private static Compilation compileDto(BiConsumer probe) { - return compile(probe, DTO_SOURCE); - } - @Test void isNoMethodOfObjectClass_filtersObjectMethods() { AtomicReference onObject = new AtomicReference<>(); AtomicReference onOwn = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); @@ -165,7 +142,8 @@ void isNoMethodOfObjectClass_filtersObjectMethods() { JavaLangAnalyser.isNoMethodOfObjectClass( method(typeElement(env, "java.lang.Object"), "toString"), ctx)); onOwn.set(JavaLangAnalyser.isNoMethodOfObjectClass(method(dto, "getName"), ctx)); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertFalse(onObject.get()); assertTrue(onOwn.get()); @@ -175,14 +153,15 @@ void isNoMethodOfObjectClass_filtersObjectMethods() { void findSetterMethods_returnsSettersSortedByNameAndParameterType() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); result.set( JavaLangAnalyser.findSetterMethods(typeElement(env, "test.Dto"), ctx).stream() .map(m -> m.getSimpleName() + "(" + m.getParameters().get(0).asType() + ")") .toList()); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertEquals(List.of("setName(java.lang.Object)", "setName(java.lang.String)"), result.get()); } @@ -192,14 +171,15 @@ void hasNotAnnotation_checksForAnnotationPresence() { AtomicReference deprecated = new AtomicReference<>(); AtomicReference plain = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { TypeElement dto = typeElement(env, "test.Dto"); deprecated.set( JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "old"))); plain.set( JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "getName"))); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertFalse(deprecated.get()); assertTrue(plain.get()); @@ -209,7 +189,7 @@ void hasNotAnnotation_checksForAnnotationPresence() { void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { AtomicReference> results = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { TypeElement dto = typeElement(env, "test.Dto"); results.set( @@ -227,7 +207,8 @@ void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { JavaLangAnalyser.hasGenericTypes(method(dto, "getName")), JavaLangAnalyser.isSetterForField(method(dto, "setName", "java.lang.String")), JavaLangAnalyser.isSetterForField(method(dto, "getName")))); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertEquals( List.of(true, false, true, false, true, false, true, false, true, false, true, false), @@ -239,7 +220,7 @@ void hasEmptyConstructor_detectsAccessibleNoArgConstructor() { AtomicReference dto = new AtomicReference<>(); AtomicReference ctor = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); dto.set(JavaLangAnalyser.hasEmptyConstructor(typeElement(env, "test.Dto"), ctx)); @@ -257,11 +238,12 @@ void hasEmptyConstructor_detectsAccessibleNoArgConstructor() { void findAnnotation_locatesDirectAnnotation() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> result.set( JavaLangAnalyser.findAnnotation( - method(typeElement(env, "test.Dto"), "old"), Deprecated.class))); + method(typeElement(env, "test.Dto"), "old"), Deprecated.class)), + DTO_SOURCE); assertThat(compilation).succeeded(); assertTrue(result.get().isPresent()); } @@ -271,7 +253,7 @@ void findAnnotationInstances_unwrapsRepeatableContainerAndDirect() { AtomicReference directCount = new AtomicReference<>(); AtomicReference containerCount = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); @@ -295,7 +277,7 @@ void findAnnotationAttributeAndArray_readValues() { AtomicReference value = new AtomicReference<>(); AtomicReference arraySize = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); @@ -313,7 +295,8 @@ void findAnnotationAttributeAndArray_readValues() { arraySize.set( JavaLangAnalyser.findAnnotationAttributeArray(tags, "value", ctx).size()); } - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertEquals("a", value.get()); assertEquals(2, arraySize.get()); @@ -323,7 +306,7 @@ void findAnnotationAttributeAndArray_readValues() { void resolveTypeElement_resolvesAnnotationValueToTypeElement() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); @@ -334,7 +317,8 @@ void resolveTypeElement_resolvesAnnotationValueToTypeElement() { AnnotationValue val = JavaLangAnalyser.findAnnotationAttribute(tag, "value", ctx).orElseThrow(); result.set(JavaLangAnalyser.resolveTypeElement(val, ctx)); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertTrue(result.get().isEmpty()); } @@ -345,7 +329,7 @@ void findMethodsStatic_filtersBySignatureAndStaticModifier() { AtomicReference> voidReturn = new AtomicReference<>(); AtomicReference> allStatic = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); @@ -366,7 +350,8 @@ void findMethodsStatic_filtersBySignatureAndStaticModifier() { .stream() .map(m -> m.getSimpleName().toString()) .toList()); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertEquals(List.of("staticUtil"), single.get()); assertEquals(List.of("staticVoid"), voidReturn.get()); @@ -377,7 +362,7 @@ void findMethodsStatic_filtersBySignatureAndStaticModifier() { void findMethods_matchesByParametersAndReturnType() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); @@ -386,7 +371,8 @@ void findMethods_matchesByParametersAndReturnType() { .stream() .map(m -> m.getSimpleName().toString()) .toList()); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertEquals(List.of("toString", "getName"), result.get()); } @@ -396,14 +382,15 @@ void findMethodWithoutParameters_matchesNameAndModifiers() { AtomicReference> found = new AtomicReference<>(); AtomicReference> missing = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { TypeElement dto = typeElement(env, "test.Dto"); found.set( JavaLangAnalyser.findMethodWithoutParameters(dto, "getName", Modifier.PUBLIC)); missing.set( JavaLangAnalyser.findMethodWithoutParameters(dto, "setName", Modifier.PUBLIC)); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertTrue(found.get().isPresent()); assertTrue(missing.get().isEmpty()); @@ -414,7 +401,7 @@ void findReadableProperties_combinesRecordComponentsGettersAndFields() { AtomicReference> recordProps = new AtomicReference<>(); AtomicReference> dtoProps = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); recordProps.set( @@ -440,7 +427,7 @@ void findReadableProperties_combinesRecordComponentsGettersAndFields() { void findSingleParameterMethods_returnsNonStaticOneParamMethods() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); result.set( @@ -450,7 +437,8 @@ void findSingleParameterMethods_returnsNonStaticOneParamMethods() { .distinct() .sorted() .toList()); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); // setName overloads + generic — staticUtil excluded (static) assertEquals(List.of("generic", "setName"), result.get()); @@ -461,7 +449,7 @@ void hasConstructorAccepting_matchesParameterType() { AtomicReference matching = new AtomicReference<>(); AtomicReference nonMatching = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement ctor = typeElement(env, "test.TwoCtor"); @@ -480,7 +468,7 @@ void hasConstructorAccepting_matchesParameterType() { void isFunctionalInterface_detectsAnnotatedAndSingleAbstractMethod() { AtomicReference> results = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { results.set( List.of( @@ -503,9 +491,10 @@ void isFunctionalInterface_detectsAnnotatedAndSingleAbstractMethod() { void extractParamJavaDoc_readsParamTextWithContinuation() { AtomicReference mth = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> - mth.set(method(typeElement(env, "test.Dto"), "setName", "java.lang.String"))); + mth.set(method(typeElement(env, "test.Dto"), "setName", "java.lang.String")), + DTO_SOURCE); assertThat(compilation).succeeded(); String javadoc = """ @@ -535,7 +524,7 @@ void findGetterForField_matchesRecordBooleanAndStandardAccessors() { AtomicReference> byIs = new AtomicReference<>(); AtomicReference> absent = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); @@ -548,7 +537,8 @@ void findGetterForField_matchesRecordBooleanAndStandardAccessors() { absent.set( JavaLangAnalyser.findGetterForField( dto, "count", field(dto, "count").asType(), ctx)); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertTrue(byGet.get().isPresent()); assertTrue(byIs.get().isPresent()); @@ -561,7 +551,7 @@ void findFieldElementAndRecordComponent_locateMembers() { AtomicReference fieldMissing = new AtomicReference<>(); AtomicReference compFound = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { TypeElement dto = typeElement(env, "test.Dto"); fieldFound.set(JavaLangAnalyser.findFieldElement(dto, "name").isPresent()); @@ -583,13 +573,14 @@ void findSetterForField_matchesVoidSingleParamSetter() { AtomicReference> found = new AtomicReference<>(); AtomicReference> missing = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); TypeElement dto = typeElement(env, "test.Dto"); found.set(JavaLangAnalyser.findSetterForField(dto, "name", ctx)); missing.set(JavaLangAnalyser.findSetterForField(dto, "count", ctx)); - }); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertTrue(found.get().isPresent()); assertTrue(missing.get().isEmpty()); @@ -600,7 +591,7 @@ void findAccessibleConstructors_excludesPrivate() { AtomicReference twoCtor = new AtomicReference<>(); AtomicReference privateCtor = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { AnnotationProcessingContext ctx = context(env); twoCtor.set( @@ -622,7 +613,7 @@ void findAccessibleConstructors_excludesPrivate() { void findConstructorsAnnotatedWith_findsMarkedCtor() { AtomicReference> annotated = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> annotated.set( JavaLangAnalyser.findConstructorsAnnotatedWith( @@ -637,11 +628,12 @@ void findConstructorsAnnotatedWith_findsMarkedCtor() { void findConstructorsAnnotatedWith_emptyWhenUnmarked() { AtomicReference> annotated = new AtomicReference<>(); Compilation compilation = - compileDto( + CodegenTestUtils.probe( (roundEnv, env) -> annotated.set( JavaLangAnalyser.findConstructorsAnnotatedWith( - typeElement(env, "test.Dto"), Deprecated.class, context(env)))); + typeElement(env, "test.Dto"), Deprecated.class, context(env))), + DTO_SOURCE); assertThat(compilation).succeeded(); assertTrue(annotated.get().isEmpty()); } @@ -651,7 +643,7 @@ void findTopLevelType_walksToOutermostType() { AtomicReference deepTop = new AtomicReference<>(); AtomicReference outerTop = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, env) -> { deepTop.set( JavaLangAnalyser.findTopLevelType(typeElement(env, "test.Outer.Inner.Deep")) diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java index 44d69fd8..598e7498 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.analysis; import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; @@ -36,11 +37,7 @@ import com.google.testing.compile.Compilation; import java.util.List; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiConsumer; -import javax.annotation.processing.ProcessingEnvironment; -import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.TypeElement; -import javax.tools.JavaFileObject; import org.javahelpers.codegen.model.method.MethodParameterDto; import org.javahelpers.codegen.model.type.GenericParameterDto; import org.javahelpers.codegen.model.type.TypeName; @@ -51,34 +48,12 @@ import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameSet; import org.javahelpers.codegen.processing.AnnotationProcessingContext; -import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.javahelpers.codegen.testing.CodegenTestUtils; -import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** Unit tests for {@link JavaLangMapper} against elements captured from a real compilation. */ class JavaLangMapperTest { - private static AnnotationProcessingContext context(ProcessingEnvironment processingEnv) { - return new AnnotationProcessingContext( - CapturingProcessingLogger.create().logger(), processingEnv); - } - - private static Compilation compile( - BiConsumer probe, String... sources) { - JavaFileObject[] files = - java.util.Arrays.stream(sources) - .map(CodegenTestUtils::forSource) - .toArray(JavaFileObject[]::new); - return CodegenTestUtils.createCompiler(new ProbeProcessor(probe)).compile(files); - } - - private static TypeName paramType( - TypeElement dto, String methodName, int paramIndex, TypeMappingContext ctx) { - return JavaLangMapper.map2MethodParameter(parameter(method(dto, methodName), paramIndex), ctx) - .getParameterType(); - } - @Test void map2TypeName_mapsJavaClass() { TypeName typeName = JavaLangMapper.map2TypeName(String.class); @@ -90,7 +65,7 @@ void map2TypeName_mapsJavaClass() { void mapToTypeName_mapsTypeElement() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( JavaLangMapper.mapToTypeName( @@ -109,7 +84,7 @@ public class Dto {} void map2MethodParameter_mapsNameAndListType() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); result.set( @@ -137,7 +112,7 @@ public class Dto { void map2MethodParameter_mapsSetToTypeNameSet() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); result.set(paramType(dto, "setIds", 0, context(processingEnv))); @@ -159,7 +134,7 @@ public void setIds(Set ids) {} void map2MethodParameter_mapsMapToTypeNameMap() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); result.set(paramType(dto, "setLookup", 0, context(processingEnv))); @@ -182,7 +157,7 @@ public void setLookup(Map lookup) {} void map2MethodParameter_mapsPrimitive() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); result.set(paramType(dto, "setCount", 0, context(processingEnv))); @@ -202,7 +177,7 @@ public void setCount(int count) {} void createDerivedTypeName_appendsSuffix() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( JavaLangMapper.createDerivedTypeName( @@ -222,7 +197,7 @@ void extractInterfaceTypeArguments_resolvesInheritedListArgument() { // CustomList extends ArrayList: the List element type is Y, not the declared X/Y pair AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { AnnotationProcessingContext ctx = context(processingEnv); TypeElement customList = typeElement(processingEnv, "test.CustomList"); @@ -247,7 +222,7 @@ void map2MethodParameter_wrapsConcreteCollections() { // ArrayList/HashMap/TreeMap take the hasConstructorWithParameterOfType path and still wrap AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); AnnotationProcessingContext ctx = context(processingEnv); @@ -281,7 +256,7 @@ public void setSorted(TreeMap sorted) {} void map2MethodParameter_wrapsGenericListToTypeNameList() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); result.set(paramType(dto, "setTags", 0, context(processingEnv))); @@ -303,7 +278,7 @@ public void setTags(LinkedList tags) {} void map2GenericParameterDtos_mapsTypeParametersWithBounds() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); result.set(JavaLangMapper.map2GenericParameterDtos(dto, context(processingEnv))); @@ -324,7 +299,7 @@ public class Dto {} void map2MethodParameter_mapsArrayAndTypeVariable() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); AnnotationProcessingContext ctx = context(processingEnv); @@ -357,7 +332,7 @@ void mapToTypeName_nullElement_returnsNull() { void map2MethodParameter_mapsAllPrimitiveKinds() { AtomicReference> result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> { TypeElement dto = typeElement(processingEnv, "test.Dto"); AnnotationProcessingContext ctx = context(processingEnv); @@ -403,7 +378,7 @@ public void setD(double d) {} void map2MethodParameter_marksTypeWithEmptyConstructor() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( paramType( @@ -436,7 +411,7 @@ public void setAddress(Address a) {} void map2MethodParameter_nestedType_mapsTypeNameNested() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( paramType( @@ -471,7 +446,7 @@ public void setInner(Outer.Inner i) {} void map2MethodParameter_fallsBackWhenMapLacksCopyConstructor() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - compile( + CodegenTestUtils.probe( (roundEnv, processingEnv) -> result.set( paramType( @@ -498,4 +473,10 @@ public void setLookup(WeirdMap lookup) {} assertThat(compilation).succeeded(); assertInstanceOf(TypeNameGeneric.class, result.get()); } + + private static TypeName paramType( + TypeElement dto, String methodName, int paramIndex, TypeMappingContext ctx) { + return JavaLangMapper.map2MethodParameter(parameter(method(dto, methodName), paramIndex), ctx) + .getParameterType(); + } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java index 7450b987..b43ae3c7 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java @@ -25,6 +25,7 @@ package org.javahelpers.codegen.processing; import static com.google.testing.compile.CompilationSubject.assertThat; +import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.field; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; @@ -37,12 +38,13 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.testing.CapturingProcessingLogger; import org.javahelpers.codegen.testing.CodegenTestUtils; -import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** @@ -64,43 +66,37 @@ void inherited() {} } """; - private static AnnotationProcessingContext context( - javax.annotation.processing.ProcessingEnvironment env) { - return new AnnotationProcessingContext(CapturingProcessingLogger.create().logger(), env); - } - @Test void delegates_elementAndTypeUtilities() { AtomicReference> results = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = ctx.getTypeElement("test.Dto"); - TypeMirror nameType = field(dto, "name").asType(); - TypeMirror dtoType = dto.asType(); - results.set( - List.of( - dto != null, - ctx.getTypeElement(TypeName.of(String.class)) != null, - ctx.getPackageOf(dto).getQualifiedName().contentEquals("test"), - ctx.getPackageElement("test") != null, - ctx.getPackageName(dto).equals("test"), - ctx.getAllMembers(dto).stream() - .anyMatch(e -> e.getSimpleName().contentEquals("inherited")), - ctx.getDocComment(dto) != null - && ctx.getDocComment(dto).contains("Doc comment on the type."), - ((TypeElement) ctx.asElement(dtoType)) - .getQualifiedName() - .equals(dto.getQualifiedName()), - ctx.isSameType(nameType, nameType), - !ctx.isSameType(nameType, dtoType), - ctx.erasure(nameType) != null, - ctx.isAssignable(ctx.erasure(dtoType), ctx.erasure(dtoType)), - !ctx.directSupertypes(dtoType).isEmpty())); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = ctx.getTypeElement("test.Dto"); + TypeMirror nameType = field(dto, "name").asType(); + TypeMirror dtoType = dto.asType(); + results.set( + List.of( + dto != null, + ctx.getTypeElement(TypeName.of(String.class)) != null, + ctx.getPackageOf(dto).getQualifiedName().contentEquals("test"), + ctx.getPackageElement("test") != null, + ctx.getPackageName(dto).equals("test"), + ctx.getAllMembers(dto).stream() + .anyMatch(e -> e.getSimpleName().contentEquals("inherited")), + ctx.getDocComment(dto) != null + && ctx.getDocComment(dto).contains("Doc comment on the type."), + ((TypeElement) ctx.asElement(dtoType)) + .getQualifiedName() + .equals(dto.getQualifiedName()), + ctx.isSameType(nameType, nameType), + !ctx.isSameType(nameType, dtoType), + ctx.erasure(nameType) != null, + ctx.isAssignable(ctx.erasure(dtoType), ctx.erasure(dtoType)), + !ctx.directSupertypes(dtoType).isEmpty())); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); List names = List.of( @@ -125,21 +121,20 @@ void delegates_elementAndTypeUtilities() { @Test void generatedTypes_addFindAndClear() { Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = ctx.getTypeElement("test.Dto"); - TypeName elementType = TypeName.of(String.class); - TypeName generated = TypeName.of(Integer.class); - assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); - ctx.addGeneratedType(elementType, generated); - assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); // dto != elementType - assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isPresent()); - ctx.getGeneratedTypes().clear(); - assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isEmpty()); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = ctx.getTypeElement("test.Dto"); + TypeName elementType = TypeName.of(String.class); + TypeName generated = TypeName.of(Integer.class); + assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); + ctx.addGeneratedType(elementType, generated); + assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); // dto != elementType + assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isPresent()); + ctx.getGeneratedTypes().clear(); + assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isEmpty()); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); } @@ -147,19 +142,18 @@ void generatedTypes_addFindAndClear() { void loggingDelegates_emitToLogger() { CapturingProcessingLogger capture = CapturingProcessingLogger.create(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = - new AnnotationProcessingContext(capture.logger(), env); - ctx.info("hello %s", "info"); - ctx.debug("hello %s", "debug"); - ctx.warning("hello %s", "warning"); - ctx.error("hello %s", "error"); - ctx.startPerformancePhase(); - ctx.endPerformancePhase("phase"); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = + new AnnotationProcessingContext(capture.logger(), env); + ctx.info("hello %s", "info"); + ctx.debug("hello %s", "debug"); + ctx.warning("hello %s", "warning"); + ctx.error("hello %s", "error"); + ctx.startPerformancePhase(); + ctx.endPerformancePhase("phase"); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello info"))); assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello warning"))); @@ -170,49 +164,44 @@ void loggingDelegates_emitToLogger() { void currentTask_nullByDefault() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - result.set(ctx.getCurrentTask()); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set(ctx.getCurrentTask()); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertNull(result.get()); } @Test void getElementValuesWithDefaults_includesDefaultsAndSetValues() { - AtomicReference size = new AtomicReference<>(); + AtomicReference elementsWithDefaults = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - javax.lang.model.element.VariableElement nameField = - field(typeElement(env, "test.Dto"), "name"); - javax.lang.model.element.AnnotationMirror suppress = - nameField.getAnnotationMirrors().get(0); - size.set(ctx.getElementValuesWithDefaults(suppress).size()); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + VariableElement nameField = field(typeElement(env, "test.Dto"), "name"); + AnnotationMirror suppress = nameField.getAnnotationMirrors().get(0); + elementsWithDefaults.set(ctx.getElementValuesWithDefaults(suppress).size()); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); // @SuppressWarnings declares a single 'value' member - assertEquals(1, size.get()); + assertEquals(1, elementsWithDefaults.get()); } @Test void isAccessibleFromGeneratedPackage_publicMembersAccessible() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "getName"))); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "getName"))); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertNotNull(result.get()); } @@ -221,10 +210,8 @@ void isAccessibleFromGeneratedPackage_publicMembersAccessible() { void performanceTracker_defaultsToNoOp() { AtomicReference tracker = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> tracker.set(context(env).getPerformanceTracker()))) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> tracker.set(context(env).getPerformanceTracker()), DTO_SOURCE); assertThat(compilation).succeeded(); assertNotNull(tracker.get()); assertEquals("NoOpPerformanceTracker", tracker.get().getClass().getSimpleName()); @@ -238,30 +225,27 @@ void performanceTracker_defaultsToNoOp() { void loggingDelegates_fullSurface() { CapturingProcessingLogger capture = CapturingProcessingLogger.createDebugEnabled(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - TypeElement dto = typeElement(env, "test.Dto"); - AnnotationProcessingContext ctx = - new AnnotationProcessingContext(capture.logger(), env); - ctx.info("plain info"); - ctx.debugEndOperation(); - ctx.debugEndOperation("closing %s", "op"); - ctx.warning(dto, "warn %s", "elem"); - ctx.error(dto, "err %s", "elem"); - ctx.reportBasedOnStrictMode(dto, "strict %s", "elem"); - ctx.reportBasedOnStrictMode("strict %s", "flat"); - AnnotationProcessingContext lenient = - new AnnotationProcessingContext( - capture.logger(), - env, - AnnotationProcessingOptions.builder() - .strictModeEnabled(false) - .build()); - lenient.reportBasedOnStrictMode(dto, "lenient %s", "elem"); - lenient.reportBasedOnStrictMode("lenient %s", "flat"); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + AnnotationProcessingContext ctx = + new AnnotationProcessingContext(capture.logger(), env); + ctx.info("plain info"); + ctx.debugEndOperation(); + ctx.debugEndOperation("closing %s", "op"); + ctx.warning(dto, "warn %s", "elem"); + ctx.error(dto, "err %s", "elem"); + ctx.reportBasedOnStrictMode(dto, "strict %s", "elem"); + ctx.reportBasedOnStrictMode("strict %s", "flat"); + AnnotationProcessingContext lenient = + new AnnotationProcessingContext( + capture.logger(), + env, + AnnotationProcessingOptions.builder().strictModeEnabled(false).build()); + lenient.reportBasedOnStrictMode(dto, "lenient %s", "elem"); + lenient.reportBasedOnStrictMode("lenient %s", "flat"); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); for (String expected : List.of( @@ -283,10 +267,9 @@ void loggingDelegates_fullSurface() { void getTypeElement_nullTypeName_returnsNull() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> result.set(context(env).getTypeElement((TypeName) null)))) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> result.set(context(env).getTypeElement((TypeName) null)), + DTO_SOURCE); assertThat(compilation).succeeded(); assertNull(result.get()); } @@ -299,14 +282,13 @@ void getTypeElement_nullTypeName_returnsNull() { void isAccessibleFromGeneratedPackage_packagePrivateWithoutTask_denied() { AtomicReference result = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Base"); - result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "inherited"))); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Base"); + result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "inherited"))); + }, + DTO_SOURCE); assertThat(compilation).succeeded(); assertEquals(false, result.get()); } @@ -318,21 +300,20 @@ void isAccessibleFromGeneratedPackage_packagePrivateWithoutTask_denied() { void performanceTracker_activeWhenEnabled() { AtomicReference tracker = new AtomicReference<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> - tracker.set( - new AnnotationProcessingContext( - CapturingProcessingLogger.create().logger(), - env, - AnnotationProcessingOptions.builder() - .performanceTrackingEnabled(true) - .phaseHierarchy( - new org.javahelpers.codegen.logging.PhaseHierarchy( - List.of(), Map.of())) - .build()) - .getPerformanceTracker()))) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> + tracker.set( + new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), + env, + AnnotationProcessingOptions.builder() + .performanceTrackingEnabled(true) + .phaseHierarchy( + new org.javahelpers.codegen.logging.PhaseHierarchy( + List.of(), Map.of())) + .build()) + .getPerformanceTracker()), + DTO_SOURCE); assertThat(compilation).succeeded(); assertEquals("ActivePerformanceTracker", tracker.get().getClass().getSimpleName()); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessingTestUtils.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessingTestUtils.java new file mode 100644 index 00000000..dcac4484 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessingTestUtils.java @@ -0,0 +1,48 @@ +/* + * MIT License + * + * Copyright (c) 2025-2026 Andreas Igel + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package org.javahelpers.codegen.processing; + +import javax.annotation.processing.ProcessingEnvironment; +import org.javahelpers.codegen.testing.CapturingProcessingLogger; + +/** Shared helpers for simple-processor tests running against a live compilation. */ +public final class ProcessingTestUtils { + + private ProcessingTestUtils() { + // Private constructor to prevent instantiation + } + + /** + * Creates an {@link AnnotationProcessingContext} backed by a {@link CapturingProcessingLogger} + * for the given live processing environment. + * + * @param processingEnv the processing environment captured inside a probe + * @return a context ready for analyser/mapper calls + */ + public static AnnotationProcessingContext context(ProcessingEnvironment processingEnv) { + return new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), processingEnv); + } +} From cbeb6efcde25605e6160f0b1076f48e4e9d92fff Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:31:58 +0000 Subject: [PATCH 11/12] test: shared probe helper, testutils package, sonar findings - ProcessingTestUtils moved to codegen.testing package and gained a probe() overload asserting compilation success; all simple-processor test classes reuse it instead of their own probe+assert pattern - generatesClassMetadataJavadocAndAnnotations now pins the full generated source textblock - simplified TypeName/TypeNameGeneric constructions to the Class-based factory/ctor where applicable - neutral 'codegen' logger prefix in codegen-core tests - sonar: rename LogRecord param (restricted identifier), document empty flush(), extract duplicated literal to constant --- .../logging/ActivePerformanceTrackerTest.java | 70 +- .../RoasterCodeGeneratorResilienceTest.java | 2 +- .../roaster/RoasterCodeGeneratorTest.java | 30 +- .../codegen/roaster/RoasterMapperTest.java | 4 +- .../codegen/testing/CapturingLogHandler.java | 8 +- .../codegen/testing/ElementTestUtils.java | 8 +- .../FieldAnnotationExtractorTest.java | 186 +++--- .../analysis/JavaLangAnalyserTest.java | 602 ++++++++---------- .../codegen/analysis/JavaLangMapperTest.java | 296 ++++----- .../AnnotationProcessingContextTest.java | 265 ++++---- .../MinimalCodegenProcessorTest.java | 3 - .../logging/MessagerProcessingLoggerTest.java | 97 ++- .../ProcessingTestUtils.java | 45 +- 13 files changed, 730 insertions(+), 886 deletions(-) rename simple-processor/src/test/java/org/javahelpers/codegen/{processing => testing}/ProcessingTestUtils.java (50%) diff --git a/codegen-core/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java b/codegen-core/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java index 2f08135b..65b5507d 100644 --- a/codegen-core/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java +++ b/codegen-core/src/test/java/org/javahelpers/codegen/logging/ActivePerformanceTrackerTest.java @@ -184,7 +184,7 @@ void generateReport_prefixedLogger_producesExpectedTaggedLayout() { tracker.endEnhancer("MyEnhancer"); tracker.endClass(5, 2); - CapturingLogger capturing = CapturingLogger.create("simple-builders"); + CapturingLogger capturing = CapturingLogger.create("codegen"); tracker.generateReport(capturing.logger()); // Remove the diagnostic kind marker and the exact measurements (durations, percentages, @@ -201,40 +201,40 @@ void generateReport_prefixedLogger_producesExpectedTaggedLayout() { assertEquals( """ - simple-builders: PERFORMANCE REPORT - simple-builders: ================================ - simple-builders: Total classes processed: - simple-builders: Total processing time: s - simple-builders: - simple-builders: Phase breakdown: - simple-builders: ├─ Element Collection: s (%) - simple-builders: ├─ Configuration Resolution: s (%) - simple-builders: ├─ Analysis: s (%) - simple-builders: ├─ Target Mapping: s (%) - simple-builders: └─ Code Generation: s (%) - simple-builders: ├─ Source Construction: s (%) - simple-builders: │ ├─ Element Building: s (%) - simple-builders: │ │ ├─ Class Creation: s (%) - simple-builders: │ │ ├─ Class Metadata: s (%) - simple-builders: │ │ ├─ Fields: s (%) - simple-builders: │ │ ├─ Constructors: s (%) - simple-builders: │ │ ├─ Methods: s (%) - simple-builders: │ │ ├─ Nested Types: s (%) - simple-builders: │ │ └─ Class Annotations: s (%) - simple-builders: │ ├─ String Generation: s (%) - simple-builders: │ └─ Formatting: s (%) - simple-builders: └─ File Writing: s (%) - simple-builders: - simple-builders: Average per class: ms - simple-builders: - simple-builders: Top slowest classes: - simple-builders: . MyClass - ms ( fields, collections) - simple-builders: - simple-builders: Top slowest MethodGenerators: - simple-builders: . MyGenerator - s ( calls, ms/call) - simple-builders: - simple-builders: Top slowest enhancers: - simple-builders: . MyEnhancer - s ( calls, ms/call)\ + codegen: PERFORMANCE REPORT + codegen: ================================ + codegen: Total classes processed: + codegen: Total processing time: s + codegen: + codegen: Phase breakdown: + codegen: ├─ Element Collection: s (%) + codegen: ├─ Configuration Resolution: s (%) + codegen: ├─ Analysis: s (%) + codegen: ├─ Target Mapping: s (%) + codegen: └─ Code Generation: s (%) + codegen: ├─ Source Construction: s (%) + codegen: │ ├─ Element Building: s (%) + codegen: │ │ ├─ Class Creation: s (%) + codegen: │ │ ├─ Class Metadata: s (%) + codegen: │ │ ├─ Fields: s (%) + codegen: │ │ ├─ Constructors: s (%) + codegen: │ │ ├─ Methods: s (%) + codegen: │ │ ├─ Nested Types: s (%) + codegen: │ │ └─ Class Annotations: s (%) + codegen: │ ├─ String Generation: s (%) + codegen: │ └─ Formatting: s (%) + codegen: └─ File Writing: s (%) + codegen: + codegen: Average per class: ms + codegen: + codegen: Top slowest classes: + codegen: . MyClass - ms ( fields, collections) + codegen: + codegen: Top slowest MethodGenerators: + codegen: . MyGenerator - s ( calls, ms/call) + codegen: + codegen: Top slowest enhancers: + codegen: . MyEnhancer - s ( calls, ms/call)\ """, actual); } diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java index 5d1de85d..10d42bb7 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorResilienceTest.java @@ -122,7 +122,7 @@ private static MethodDto duplicateSignatureMethod(String marker) { method.setModifier(AccessModifier.PUBLIC); MethodParameterDto parameter = new MethodParameterDto(); parameter.setParameterName("value"); - parameter.setParameterTypeName(new TypeName("java.lang", "String")); + parameter.setParameterTypeName(TypeName.of(String.class)); method.addParameter(parameter); method.setCode("return this; // " + marker); return method; diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index 97508fe5..77b26082 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -101,11 +101,18 @@ void generatesClassMetadataJavadocAndAnnotations() throws Exception { InterfaceName iface = new InterfaceName("java.io", "Serializable"); classDef.addInterface(iface); - assertContaining( - generate(classDef).generatedSource(), - "* Builder for {@link Person}.", - "@Generated(\"simple-builders\")", - "public class AnnotatedBuilder extends AbstractBuilder implements Serializable"); + assertGeneratedSource( + """ + package test; + import java.io.Serializable; + import javax.annotation.Generated; + /** + * Builder for {@link Person}. + */ + @Generated("simple-builders") + public class AnnotatedBuilder extends AbstractBuilder implements Serializable { + }""", + classDef); } @Test @@ -216,23 +223,18 @@ void generatesMethodWithJavadocAnnotationsAndTypedParameters() throws Exception classDef.setClassAccessModifier(AccessModifier.PUBLIC); classDef.setFormattingMode(FormattingMode.NONE); - MethodDto method = - new MethodDto( - "items", - new TypeNameGeneric( - new TypeName("java.util", "List"), List.of(TypeName.of(String.class)))); + MethodDto method = new MethodDto("items", new TypeNameGeneric(List.class, String.class)); method.setModifier(AccessModifier.PUBLIC); JavadocDto javadoc = new JavadocDto("Adds items."); javadoc.addParam("values", "items to add"); javadoc.addReturn("this builder"); method.setJavadoc(javadoc); AnnotationDto override_ = new AnnotationDto(); - override_.setAnnotationType(new TypeName("java.lang", "Override")); + override_.setAnnotationType(TypeName.of(Override.class)); method.addAnnotation(override_); MethodParameterDto param = new MethodParameterDto(); param.setParameterName("values"); - param.setParameterTypeName( - new TypeNameGeneric(new TypeName("java.util", "List"), List.of(TypeName.of(String.class)))); + param.setParameterTypeName(new TypeNameGeneric(List.class, String.class)); method.addParameter(param); method.setCode("return null;"); classDef.addMethod(method); @@ -296,7 +298,7 @@ private static GenerationTargetClassDto personBuilderDefinition() { name.setModifier(AccessModifier.PUBLIC); MethodParameterDto param = new MethodParameterDto(); param.setParameterName("name"); - param.setParameterTypeName(new TypeName("java.lang", "String")); + param.setParameterTypeName(TypeName.of(String.class)); name.addParameter(param); name.setCode( """ diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java index 1e7b6f15..bee5f6e9 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java @@ -73,13 +73,13 @@ void mapType_rendersGenericWithInnerArguments() { @Test void mapType_rendersRawGenericWithoutArguments() { - TypeNameGeneric generic = new TypeNameGeneric(new TypeName("java.util", "List"), List.of()); + TypeNameGeneric generic = new TypeNameGeneric(List.class); assertEquals("List", RoasterMapper.mapType(generic)); } @Test void mapType_prependsTypeUseAnnotations() { - TypeName annotated = new TypeName("java.lang", "String"); + TypeName annotated = TypeName.of(String.class); AnnotationDto nonNull = new AnnotationDto(); nonNull.setAnnotationType(new TypeName("test.anno", "NonNull")); annotated.addAnnotation(nonNull); diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java index 0c9846c8..0fea720c 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java @@ -51,12 +51,14 @@ public CapturingLogHandler(Logger logger) { } @Override - public void publish(LogRecord record) { - records.append(record.getMessage()).append('\n'); + public void publish(LogRecord logRecord) { + records.append(logRecord.getMessage()).append('\n'); } @Override - public void flush() {} + public void flush() { + // records accumulate in memory only — nothing to flush + } /** All captured record messages, one per line. */ public String output() { diff --git a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java index a8d95570..1403c6a8 100644 --- a/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java @@ -38,6 +38,8 @@ */ public final class ElementTestUtils { + private static final String ON = "' on "; + private ElementTestUtils() {} /** @@ -60,7 +62,7 @@ public static VariableElement field(TypeElement type, String fieldName) { .filter(VariableElement.class::isInstance) .map(VariableElement.class::cast) .filter(e -> e.getSimpleName().toString().equals(fieldName)), - "field '" + fieldName + "' on " + type.getQualifiedName()); + "field '" + fieldName + ON + type.getQualifiedName()); } /** @@ -73,7 +75,7 @@ public static ExecutableElement method(TypeElement type, String methodName) { .filter(ExecutableElement.class::isInstance) .map(ExecutableElement.class::cast) .filter(e -> e.getSimpleName().toString().equals(methodName)), - "method '" + methodName + "' on " + type.getQualifiedName()); + "method '" + methodName + ON + type.getQualifiedName()); } /** @@ -98,7 +100,7 @@ public static ExecutableElement method( + methodName + "(" + String.join(", ", parameterTypes) - + "' on " + + ON + type.getQualifiedName()); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java index 3a9be519..c991eb8c 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java @@ -24,22 +24,20 @@ package org.javahelpers.codegen.analysis; -import static com.google.testing.compile.CompilationSubject.assertThat; -import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.field; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.context; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.probe; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.google.testing.compile.Compilation; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import org.javahelpers.codegen.model.annotation.AnnotationDto; import org.javahelpers.codegen.model.type.TypeName; -import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; /** Unit tests for {@link FieldAnnotationExtractor} against elements captured from a compilation. */ @@ -107,16 +105,13 @@ public enum ItemCondition { GOOD, BAD } @Test void extractDeprecatedAnnotation_findsDeprecatedField() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractDeprecatedAnnotation( - field(typeElement(processingEnv, "test.Dto"), "legacy"), - context(processingEnv))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractDeprecatedAnnotation( + field(typeElement(processingEnv, "test.Dto"), "legacy"), + context(processingEnv))), + DTO_SOURCES); assertTrue(result.get().isPresent()); assertEquals("java.lang.Deprecated", result.get().get().getAnnotationType().toString()); } @@ -124,32 +119,25 @@ void extractDeprecatedAnnotation_findsDeprecatedField() { @Test void extractDeprecatedAnnotation_emptyForPlainField() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractDeprecatedAnnotation( - field(typeElement(processingEnv, "test.Dto"), "plain"), - context(processingEnv))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractDeprecatedAnnotation( + field(typeElement(processingEnv, "test.Dto"), "plain"), + context(processingEnv))), + DTO_SOURCES); assertTrue(result.get().isEmpty()); } @Test void extractAnnotations_returnsMemberValues() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractAnnotations( - field(typeElement(processingEnv, "test.Dto"), "mode"), - context(processingEnv))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(typeElement(processingEnv, "test.Dto"), "mode"), context(processingEnv))), + DTO_SOURCES); assertEquals(1, result.get().size()); AnnotationDto annotation = result.get().get(0); assertEquals("Default", annotation.getAnnotationType().getClassName()); @@ -160,16 +148,13 @@ void extractAnnotations_returnsMemberValues() { void hasNonNullConstraint_detectsNonNullAnnotation() { AtomicReference nonNull = new AtomicReference<>(); AtomicReference plain = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - var dto = typeElement(processingEnv, "test.Dto"); - nonNull.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "required"))); - plain.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "plain"))); - }, - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> { + var dto = typeElement(processingEnv, "test.Dto"); + nonNull.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "required"))); + plain.set(FieldAnnotationExtractor.hasNonNullConstraint(field(dto, "plain"))); + }, + DTO_SOURCES); assertTrue(nonNull.get()); assertFalse(plain.get()); } @@ -177,15 +162,12 @@ void hasNonNullConstraint_detectsNonNullAnnotation() { @Test void extractAnnotationValue_matchesAnnotationBySimpleName() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractAnnotationValue( - field(typeElement(processingEnv, "test.Dto"), "mode"), Set.of("Default"))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotationValue( + field(typeElement(processingEnv, "test.Dto"), "mode"), Set.of("Default"))), + DTO_SOURCES); assertEquals(Optional.of("GENERAL"), result.get()); } @@ -233,16 +215,12 @@ void extractDeprecatedAnnotation_nullElement_returnsEmpty() { void extractDeprecatedAnnotation_ignoresOtherAnnotations() { // 'mode' carries @Default but not @Deprecated — the mirror scan must fall through AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractDeprecatedAnnotation( - field(typeElement(processingEnv, "test.Dto"), "mode"), - context(processingEnv))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractDeprecatedAnnotation( + field(typeElement(processingEnv, "test.Dto"), "mode"), context(processingEnv))), + DTO_SOURCES); assertTrue(result.get().isEmpty()); } @@ -253,16 +231,13 @@ void extractDeprecatedAnnotation_ignoresOtherAnnotations() { @Test void extractAnnotations_onTypeMirror_findsTypeUseAnnotation() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractAnnotations( - field(typeElement(processingEnv, "test.Dto"), "typed").asType(), - context(processingEnv))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(typeElement(processingEnv, "test.Dto"), "typed").asType(), + context(processingEnv))), + DTO_SOURCES); assertEquals(1, result.get().size()); assertEquals("NonNull", result.get().get(0).getAnnotationType().getClassName()); } @@ -275,16 +250,12 @@ void extractAnnotations_onTypeMirror_findsTypeUseAnnotation() { @Test void extractAnnotations_formatsEnumClassAndArrayMembers() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractAnnotations( - field(typeElement(processingEnv, "test.Dto"), "rich"), - context(processingEnv))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(typeElement(processingEnv, "test.Dto"), "rich"), context(processingEnv))), + DTO_SOURCES); assertEquals(1, result.get().size()); AnnotationDto rich = result.get().get(0); assertEquals("test.ItemCondition.BAD", rich.getMembers().get("cond")); @@ -297,16 +268,13 @@ void extractAnnotations_formatsEnumClassAndArrayMembers() { @Test void extractAnnotations_emptyArrayMember_formatsAsEmptyBraces() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractAnnotations( - field(typeElement(processingEnv, "test.Dto"), "richEmpty"), - context(processingEnv))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotations( + field(typeElement(processingEnv, "test.Dto"), "richEmpty"), + context(processingEnv))), + DTO_SOURCES); assertEquals(1, result.get().size()); assertEquals("{}", result.get().get(0).getMembers().get("tags")); } @@ -314,32 +282,24 @@ void extractAnnotations_emptyArrayMember_formatsAsEmptyBraces() { @Test void extractAnnotationValue_emptyWhenAnnotationHasNoValueMember() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractAnnotationValue( - field(typeElement(processingEnv, "test.Dto"), "required"), - Set.of("NonNull"))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotationValue( + field(typeElement(processingEnv, "test.Dto"), "required"), Set.of("NonNull"))), + DTO_SOURCES); assertTrue(result.get().isEmpty()); } @Test void extractAnnotationValue_emptyWhenNoNameMatches() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - FieldAnnotationExtractor.extractAnnotationValue( - field(typeElement(processingEnv, "test.Dto"), "required"), - Set.of("Other"))), - DTO_SOURCES); - - assertThat(compilation).succeeded(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotationValue( + field(typeElement(processingEnv, "test.Dto"), "required"), Set.of("Other"))), + DTO_SOURCES); assertTrue(result.get().isEmpty()); } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java index 0bf46e85..1968505b 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -24,18 +24,17 @@ package org.javahelpers.codegen.analysis; -import static com.google.testing.compile.CompilationSubject.assertThat; -import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.field; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.context; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.probe; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.google.testing.compile.Compilation; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; @@ -49,7 +48,6 @@ import org.javahelpers.codegen.analysis.testannotations.Tags; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.processing.AnnotationProcessingContext; -import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; /** Unit tests for {@link JavaLangAnalyser} against elements captured from a real compilation. */ @@ -133,18 +131,16 @@ public static class Deep {} void isNoMethodOfObjectClass_filtersObjectMethods() { AtomicReference onObject = new AtomicReference<>(); AtomicReference onOwn = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - onObject.set( - JavaLangAnalyser.isNoMethodOfObjectClass( - method(typeElement(env, "java.lang.Object"), "toString"), ctx)); - onOwn.set(JavaLangAnalyser.isNoMethodOfObjectClass(method(dto, "getName"), ctx)); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + onObject.set( + JavaLangAnalyser.isNoMethodOfObjectClass( + method(typeElement(env, "java.lang.Object"), "toString"), ctx)); + onOwn.set(JavaLangAnalyser.isNoMethodOfObjectClass(method(dto, "getName"), ctx)); + }, + DTO_SOURCE); assertFalse(onObject.get()); assertTrue(onOwn.get()); } @@ -152,17 +148,15 @@ void isNoMethodOfObjectClass_filtersObjectMethods() { @Test void findSetterMethods_returnsSettersSortedByNameAndParameterType() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - result.set( - JavaLangAnalyser.findSetterMethods(typeElement(env, "test.Dto"), ctx).stream() - .map(m -> m.getSimpleName() + "(" + m.getParameters().get(0).asType() + ")") - .toList()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set( + JavaLangAnalyser.findSetterMethods(typeElement(env, "test.Dto"), ctx).stream() + .map(m -> m.getSimpleName() + "(" + m.getParameters().get(0).asType() + ")") + .toList()); + }, + DTO_SOURCE); assertEquals(List.of("setName(java.lang.Object)", "setName(java.lang.String)"), result.get()); } @@ -170,17 +164,13 @@ void findSetterMethods_returnsSettersSortedByNameAndParameterType() { void hasNotAnnotation_checksForAnnotationPresence() { AtomicReference deprecated = new AtomicReference<>(); AtomicReference plain = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - TypeElement dto = typeElement(env, "test.Dto"); - deprecated.set( - JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "old"))); - plain.set( - JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "getName"))); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + deprecated.set(JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "old"))); + plain.set(JavaLangAnalyser.hasNotAnnotation(Deprecated.class, method(dto, "getName"))); + }, + DTO_SOURCE); assertFalse(deprecated.get()); assertTrue(plain.get()); } @@ -188,28 +178,26 @@ void hasNotAnnotation_checksForAnnotationPresence() { @Test void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { AtomicReference> results = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - TypeElement dto = typeElement(env, "test.Dto"); - results.set( - List.of( - JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "getName")), - JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "risky")), - // setName returns void -> no return value; getName returns String - JavaLangAnalyser.hasNoReturnValue(method(dto, "setName", "java.lang.String")), - JavaLangAnalyser.hasNoReturnValue(method(dto, "getName")), - JavaLangAnalyser.isNotPrivate(method(dto, "getName")), - JavaLangAnalyser.isNotPrivate(method(dto, "hidden")), - JavaLangAnalyser.isNotStatic(method(dto, "getName")), - JavaLangAnalyser.isNotStatic(method(dto, "staticUtil")), - JavaLangAnalyser.hasGenericTypes(method(dto, "generic")), - JavaLangAnalyser.hasGenericTypes(method(dto, "getName")), - JavaLangAnalyser.isSetterForField(method(dto, "setName", "java.lang.String")), - JavaLangAnalyser.isSetterForField(method(dto, "getName")))); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + results.set( + List.of( + JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "getName")), + JavaLangAnalyser.hasNoThrowablesDeclared(method(dto, "risky")), + // setName returns void -> no return value; getName returns String + JavaLangAnalyser.hasNoReturnValue(method(dto, "setName", "java.lang.String")), + JavaLangAnalyser.hasNoReturnValue(method(dto, "getName")), + JavaLangAnalyser.isNotPrivate(method(dto, "getName")), + JavaLangAnalyser.isNotPrivate(method(dto, "hidden")), + JavaLangAnalyser.isNotStatic(method(dto, "getName")), + JavaLangAnalyser.isNotStatic(method(dto, "staticUtil")), + JavaLangAnalyser.hasGenericTypes(method(dto, "generic")), + JavaLangAnalyser.hasGenericTypes(method(dto, "getName")), + JavaLangAnalyser.isSetterForField(method(dto, "setName", "java.lang.String")), + JavaLangAnalyser.isSetterForField(method(dto, "getName")))); + }, + DTO_SOURCE); assertEquals( List.of(true, false, true, false, true, false, true, false, true, false, true, false), results.get()); @@ -219,17 +207,15 @@ void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { void hasEmptyConstructor_detectsAccessibleNoArgConstructor() { AtomicReference dto = new AtomicReference<>(); AtomicReference ctor = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - dto.set(JavaLangAnalyser.hasEmptyConstructor(typeElement(env, "test.Dto"), ctx)); - // TwoCtor has public no-arg ctor -> true as well - ctor.set(JavaLangAnalyser.hasEmptyConstructor(typeElement(env, "test.TwoCtor"), ctx)); - }, - DTO_SOURCE, - CTOR_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + dto.set(JavaLangAnalyser.hasEmptyConstructor(typeElement(env, "test.Dto"), ctx)); + // TwoCtor has public no-arg ctor -> true as well + ctor.set(JavaLangAnalyser.hasEmptyConstructor(typeElement(env, "test.TwoCtor"), ctx)); + }, + DTO_SOURCE, + CTOR_SOURCE); assertTrue(dto.get()); assertTrue(ctor.get()); } @@ -237,14 +223,12 @@ void hasEmptyConstructor_detectsAccessibleNoArgConstructor() { @Test void findAnnotation_locatesDirectAnnotation() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> - result.set( - JavaLangAnalyser.findAnnotation( - method(typeElement(env, "test.Dto"), "old"), Deprecated.class)), - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> + result.set( + JavaLangAnalyser.findAnnotation( + method(typeElement(env, "test.Dto"), "old"), Deprecated.class)), + DTO_SOURCE); assertTrue(result.get().isPresent()); } @@ -252,22 +236,20 @@ void findAnnotation_locatesDirectAnnotation() { void findAnnotationInstances_unwrapsRepeatableContainerAndDirect() { AtomicReference directCount = new AtomicReference<>(); AtomicReference containerCount = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - directCount.set( - JavaLangAnalyser.findAnnotationInstances( - method(dto, "tagged"), Tag.class, Tags.class, ctx) - .size()); - containerCount.set( - JavaLangAnalyser.findAnnotationInstances( - method(dto, "wrapped"), Tag.class, Tags.class, ctx) - .size()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + directCount.set( + JavaLangAnalyser.findAnnotationInstances( + method(dto, "tagged"), Tag.class, Tags.class, ctx) + .size()); + containerCount.set( + JavaLangAnalyser.findAnnotationInstances( + method(dto, "wrapped"), Tag.class, Tags.class, ctx) + .size()); + }, + DTO_SOURCE); assertEquals(2, directCount.get()); assertEquals(2, containerCount.get()); } @@ -276,28 +258,24 @@ void findAnnotationInstances_unwrapsRepeatableContainerAndDirect() { void findAnnotationAttributeAndArray_readValues() { AtomicReference value = new AtomicReference<>(); AtomicReference arraySize = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - AnnotationMirror tag = - JavaLangAnalyser.findAnnotation(method(dto, "singleTag"), Tag.class) - .orElseThrow(); - value.set( - JavaLangAnalyser.findAnnotationAttribute(tag, "value", ctx) - .map(AnnotationValue::getValue) - .map(Object::toString) - .orElse(null)); - AnnotationMirror tags = - JavaLangAnalyser.findAnnotation(method(dto, "wrapped"), Tags.class).orElse(null); - if (tags != null) { - arraySize.set( - JavaLangAnalyser.findAnnotationAttributeArray(tags, "value", ctx).size()); - } - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + AnnotationMirror tag = + JavaLangAnalyser.findAnnotation(method(dto, "singleTag"), Tag.class).orElseThrow(); + value.set( + JavaLangAnalyser.findAnnotationAttribute(tag, "value", ctx) + .map(AnnotationValue::getValue) + .map(Object::toString) + .orElse(null)); + AnnotationMirror tags = + JavaLangAnalyser.findAnnotation(method(dto, "wrapped"), Tags.class).orElse(null); + if (tags != null) { + arraySize.set(JavaLangAnalyser.findAnnotationAttributeArray(tags, "value", ctx).size()); + } + }, + DTO_SOURCE); assertEquals("a", value.get()); assertEquals(2, arraySize.get()); } @@ -305,21 +283,18 @@ void findAnnotationAttributeAndArray_readValues() { @Test void resolveTypeElement_resolvesAnnotationValueToTypeElement() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - AnnotationMirror tag = - JavaLangAnalyser.findAnnotation(method(dto, "singleTag"), Tag.class) - .orElseThrow(); - // value is a string, not a TypeMirror -> empty - AnnotationValue val = - JavaLangAnalyser.findAnnotationAttribute(tag, "value", ctx).orElseThrow(); - result.set(JavaLangAnalyser.resolveTypeElement(val, ctx)); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + AnnotationMirror tag = + JavaLangAnalyser.findAnnotation(method(dto, "singleTag"), Tag.class).orElseThrow(); + // value is a string, not a TypeMirror -> empty + AnnotationValue val = + JavaLangAnalyser.findAnnotationAttribute(tag, "value", ctx).orElseThrow(); + result.set(JavaLangAnalyser.resolveTypeElement(val, ctx)); + }, + DTO_SOURCE); assertTrue(result.get().isEmpty()); } @@ -328,31 +303,28 @@ void findMethodsStatic_filtersBySignatureAndStaticModifier() { AtomicReference> single = new AtomicReference<>(); AtomicReference> voidReturn = new AtomicReference<>(); AtomicReference> allStatic = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - single.set( - JavaLangAnalyser.findMethodsStatic( - dto, TypeName.of(String.class), TypeName.of(String.class), ctx) - .stream() - .map(m -> m.getSimpleName().toString()) - .toList()); - voidReturn.set( - JavaLangAnalyser.findMethodsStatic( - dto, List.of(TypeName.of(String.class)), null, ctx) - .stream() - .map(m -> m.getSimpleName().toString()) - .toList()); - allStatic.set( - JavaLangAnalyser.findMethodsStatic(dto, List.of(TypeName.of(String.class)), ctx) - .stream() - .map(m -> m.getSimpleName().toString()) - .toList()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + single.set( + JavaLangAnalyser.findMethodsStatic( + dto, TypeName.of(String.class), TypeName.of(String.class), ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + voidReturn.set( + JavaLangAnalyser.findMethodsStatic(dto, List.of(TypeName.of(String.class)), null, ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + allStatic.set( + JavaLangAnalyser.findMethodsStatic(dto, List.of(TypeName.of(String.class)), ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + }, + DTO_SOURCE); assertEquals(List.of("staticUtil"), single.get()); assertEquals(List.of("staticVoid"), voidReturn.get()); assertEquals(List.of("staticUtil", "staticVoid"), allStatic.get()); @@ -361,19 +333,16 @@ void findMethodsStatic_filtersBySignatureAndStaticModifier() { @Test void findMethods_matchesByParametersAndReturnType() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - result.set( - JavaLangAnalyser.findMethods(dto, List.of(), TypeName.of(String.class), ctx) - .stream() - .map(m -> m.getSimpleName().toString()) - .toList()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + result.set( + JavaLangAnalyser.findMethods(dto, List.of(), TypeName.of(String.class), ctx).stream() + .map(m -> m.getSimpleName().toString()) + .toList()); + }, + DTO_SOURCE); assertEquals(List.of("toString", "getName"), result.get()); } @@ -381,17 +350,14 @@ void findMethods_matchesByParametersAndReturnType() { void findMethodWithoutParameters_matchesNameAndModifiers() { AtomicReference> found = new AtomicReference<>(); AtomicReference> missing = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - TypeElement dto = typeElement(env, "test.Dto"); - found.set( - JavaLangAnalyser.findMethodWithoutParameters(dto, "getName", Modifier.PUBLIC)); - missing.set( - JavaLangAnalyser.findMethodWithoutParameters(dto, "setName", Modifier.PUBLIC)); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + found.set(JavaLangAnalyser.findMethodWithoutParameters(dto, "getName", Modifier.PUBLIC)); + missing.set( + JavaLangAnalyser.findMethodWithoutParameters(dto, "setName", Modifier.PUBLIC)); + }, + DTO_SOURCE); assertTrue(found.get().isPresent()); assertTrue(missing.get().isEmpty()); } @@ -400,24 +366,20 @@ void findMethodWithoutParameters_matchesNameAndModifiers() { void findReadableProperties_combinesRecordComponentsGettersAndFields() { AtomicReference> recordProps = new AtomicReference<>(); AtomicReference> dtoProps = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - recordProps.set( - JavaLangAnalyser.findReadableProperties(typeElement(env, "test.Point"), ctx) - .stream() - .map(ReadableProperty::name) - .toList()); - dtoProps.set( - JavaLangAnalyser.findReadableProperties(typeElement(env, "test.Dto"), ctx) - .stream() - .map(ReadableProperty::name) - .toList()); - }, - RECORD_SOURCE, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + recordProps.set( + JavaLangAnalyser.findReadableProperties(typeElement(env, "test.Point"), ctx).stream() + .map(ReadableProperty::name) + .toList()); + dtoProps.set( + JavaLangAnalyser.findReadableProperties(typeElement(env, "test.Dto"), ctx).stream() + .map(ReadableProperty::name) + .toList()); + }, + RECORD_SOURCE, + DTO_SOURCE); assertEquals(List.of("x", "y"), recordProps.get()); // getters are readable; private fields without accessors are not assertTrue(dtoProps.get().containsAll(List.of("name", "active"))); @@ -426,20 +388,18 @@ void findReadableProperties_combinesRecordComponentsGettersAndFields() { @Test void findSingleParameterMethods_returnsNonStaticOneParamMethods() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - result.set( - JavaLangAnalyser.findSingleParameterMethods(typeElement(env, "test.Dto"), ctx) - .stream() - .map(m -> m.getSimpleName().toString()) - .distinct() - .sorted() - .toList()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set( + JavaLangAnalyser.findSingleParameterMethods(typeElement(env, "test.Dto"), ctx) + .stream() + .map(m -> m.getSimpleName().toString()) + .distinct() + .sorted() + .toList()); + }, + DTO_SOURCE); // setName overloads + generic — staticUtil excluded (static) assertEquals(List.of("generic", "setName"), result.get()); } @@ -448,18 +408,16 @@ void findSingleParameterMethods_returnsNonStaticOneParamMethods() { void hasConstructorAccepting_matchesParameterType() { AtomicReference matching = new AtomicReference<>(); AtomicReference nonMatching = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement ctor = typeElement(env, "test.TwoCtor"); - matching.set( - JavaLangAnalyser.hasConstructorAccepting(ctor, TypeName.of(String.class), ctx)); - nonMatching.set( - JavaLangAnalyser.hasConstructorAccepting(ctor, TypeName.of(Integer.class), ctx)); - }, - CTOR_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement ctor = typeElement(env, "test.TwoCtor"); + matching.set( + JavaLangAnalyser.hasConstructorAccepting(ctor, TypeName.of(String.class), ctx)); + nonMatching.set( + JavaLangAnalyser.hasConstructorAccepting(ctor, TypeName.of(Integer.class), ctx)); + }, + CTOR_SOURCE); assertTrue(matching.get()); assertFalse(nonMatching.get()); } @@ -467,35 +425,30 @@ void hasConstructorAccepting_matchesParameterType() { @Test void isFunctionalInterface_detectsAnnotatedAndSingleAbstractMethod() { AtomicReference> results = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - results.set( - List.of( - JavaLangAnalyser.isFunctionalInterface( - typeElement(env, "test.Interfaces.Single")), - JavaLangAnalyser.isFunctionalInterface( - typeElement(env, "test.Interfaces.Two")), - JavaLangAnalyser.isFunctionalInterface( - typeElement(env, "test.Interfaces.Explicit")), - JavaLangAnalyser.isFunctionalInterface(typeElement(env, "test.Dto")), - JavaLangAnalyser.isFunctionalInterface(null))); - }, - INTERFACES_SOURCE, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + results.set( + List.of( + JavaLangAnalyser.isFunctionalInterface( + typeElement(env, "test.Interfaces.Single")), + JavaLangAnalyser.isFunctionalInterface(typeElement(env, "test.Interfaces.Two")), + JavaLangAnalyser.isFunctionalInterface( + typeElement(env, "test.Interfaces.Explicit")), + JavaLangAnalyser.isFunctionalInterface(typeElement(env, "test.Dto")), + JavaLangAnalyser.isFunctionalInterface(null))); + }, + INTERFACES_SOURCE, + DTO_SOURCE); assertEquals(List.of(true, false, true, false, false), results.get()); } @Test void extractParamJavaDoc_readsParamTextWithContinuation() { AtomicReference mth = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> - mth.set(method(typeElement(env, "test.Dto"), "setName", "java.lang.String")), - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> + mth.set(method(typeElement(env, "test.Dto"), "setName", "java.lang.String")), + DTO_SOURCE); String javadoc = """ Sets the name. @@ -523,23 +476,19 @@ void findGetterForField_matchesRecordBooleanAndStandardAccessors() { AtomicReference> byGet = new AtomicReference<>(); AtomicReference> byIs = new AtomicReference<>(); AtomicReference> absent = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - byGet.set( - JavaLangAnalyser.findGetterForField( - dto, "name", field(dto, "name").asType(), ctx)); - byIs.set( - JavaLangAnalyser.findGetterForField( - dto, "active", field(dto, "active").asType(), ctx)); - absent.set( - JavaLangAnalyser.findGetterForField( - dto, "count", field(dto, "count").asType(), ctx)); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + byGet.set( + JavaLangAnalyser.findGetterForField(dto, "name", field(dto, "name").asType(), ctx)); + byIs.set( + JavaLangAnalyser.findGetterForField( + dto, "active", field(dto, "active").asType(), ctx)); + absent.set( + JavaLangAnalyser.findGetterForField(dto, "count", field(dto, "count").asType(), ctx)); + }, + DTO_SOURCE); assertTrue(byGet.get().isPresent()); assertTrue(byIs.get().isPresent()); assertTrue(absent.get().isEmpty()); @@ -550,19 +499,17 @@ void findFieldElementAndRecordComponent_locateMembers() { AtomicReference fieldFound = new AtomicReference<>(); AtomicReference fieldMissing = new AtomicReference<>(); AtomicReference compFound = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - TypeElement dto = typeElement(env, "test.Dto"); - fieldFound.set(JavaLangAnalyser.findFieldElement(dto, "name").isPresent()); - fieldMissing.set(JavaLangAnalyser.findFieldElement(dto, "missing").isEmpty()); - compFound.set( - JavaLangAnalyser.findRecordComponent(typeElement(env, "test.Point"), "x") - .isPresent()); - }, - DTO_SOURCE, - RECORD_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + fieldFound.set(JavaLangAnalyser.findFieldElement(dto, "name").isPresent()); + fieldMissing.set(JavaLangAnalyser.findFieldElement(dto, "missing").isEmpty()); + compFound.set( + JavaLangAnalyser.findRecordComponent(typeElement(env, "test.Point"), "x") + .isPresent()); + }, + DTO_SOURCE, + RECORD_SOURCE); assertTrue(fieldFound.get()); assertTrue(fieldMissing.get()); assertTrue(compFound.get()); @@ -572,16 +519,14 @@ void findFieldElementAndRecordComponent_locateMembers() { void findSetterForField_matchesVoidSingleParamSetter() { AtomicReference> found = new AtomicReference<>(); AtomicReference> missing = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - found.set(JavaLangAnalyser.findSetterForField(dto, "name", ctx)); - missing.set(JavaLangAnalyser.findSetterForField(dto, "count", ctx)); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + found.set(JavaLangAnalyser.findSetterForField(dto, "name", ctx)); + missing.set(JavaLangAnalyser.findSetterForField(dto, "count", ctx)); + }, + DTO_SOURCE); assertTrue(found.get().isPresent()); assertTrue(missing.get().isEmpty()); } @@ -590,21 +535,18 @@ void findSetterForField_matchesVoidSingleParamSetter() { void findAccessibleConstructors_excludesPrivate() { AtomicReference twoCtor = new AtomicReference<>(); AtomicReference privateCtor = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - twoCtor.set( - JavaLangAnalyser.findAccessibleConstructors(typeElement(env, "test.TwoCtor"), ctx) - .size()); - privateCtor.set( - JavaLangAnalyser.findAccessibleConstructors( - typeElement(env, "test.PrivateCtor"), ctx) - .size()); - }, - CTOR_SOURCE, - PRIVATE_CTOR_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + twoCtor.set( + JavaLangAnalyser.findAccessibleConstructors(typeElement(env, "test.TwoCtor"), ctx) + .size()); + privateCtor.set( + JavaLangAnalyser.findAccessibleConstructors(typeElement(env, "test.PrivateCtor"), ctx) + .size()); + }, + CTOR_SOURCE, + PRIVATE_CTOR_SOURCE); assertEquals(3, twoCtor.get()); assertEquals(1, privateCtor.get()); } @@ -612,14 +554,12 @@ void findAccessibleConstructors_excludesPrivate() { @Test void findConstructorsAnnotatedWith_findsMarkedCtor() { AtomicReference> annotated = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> - annotated.set( - JavaLangAnalyser.findConstructorsAnnotatedWith( - typeElement(env, "test.TwoCtor"), Deprecated.class, context(env))), - CTOR_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> + annotated.set( + JavaLangAnalyser.findConstructorsAnnotatedWith( + typeElement(env, "test.TwoCtor"), Deprecated.class, context(env))), + CTOR_SOURCE); assertEquals(1, annotated.get().size()); assertEquals(2, annotated.get().get(0).getParameters().size()); } @@ -627,14 +567,12 @@ void findConstructorsAnnotatedWith_findsMarkedCtor() { @Test void findConstructorsAnnotatedWith_emptyWhenUnmarked() { AtomicReference> annotated = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> - annotated.set( - JavaLangAnalyser.findConstructorsAnnotatedWith( - typeElement(env, "test.Dto"), Deprecated.class, context(env))), - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> + annotated.set( + JavaLangAnalyser.findConstructorsAnnotatedWith( + typeElement(env, "test.Dto"), Deprecated.class, context(env))), + DTO_SOURCE); assertTrue(annotated.get().isEmpty()); } @@ -642,20 +580,18 @@ void findConstructorsAnnotatedWith_emptyWhenUnmarked() { void findTopLevelType_walksToOutermostType() { AtomicReference deepTop = new AtomicReference<>(); AtomicReference outerTop = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - deepTop.set( - JavaLangAnalyser.findTopLevelType(typeElement(env, "test.Outer.Inner.Deep")) - .getSimpleName() - .toString()); - outerTop.set( - JavaLangAnalyser.findTopLevelType(typeElement(env, "test.Outer")) - .getSimpleName() - .toString()); - }, - NESTED_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + deepTop.set( + JavaLangAnalyser.findTopLevelType(typeElement(env, "test.Outer.Inner.Deep")) + .getSimpleName() + .toString()); + outerTop.set( + JavaLangAnalyser.findTopLevelType(typeElement(env, "test.Outer")) + .getSimpleName() + .toString()); + }, + NESTED_SOURCE); assertEquals("Outer", deepTop.get()); assertEquals("Outer", outerTop.get()); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java index 598e7498..0f1b9e76 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java @@ -24,17 +24,16 @@ package org.javahelpers.codegen.analysis; -import static com.google.testing.compile.CompilationSubject.assertThat; -import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.parameter; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.context; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.probe; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.google.testing.compile.Compilation; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import javax.lang.model.element.TypeElement; @@ -48,7 +47,6 @@ import org.javahelpers.codegen.model.type.TypeNamePrimitive; import org.javahelpers.codegen.model.type.TypeNameSet; import org.javahelpers.codegen.processing.AnnotationProcessingContext; -import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; /** Unit tests for {@link JavaLangMapper} against elements captured from a real compilation. */ @@ -64,18 +62,15 @@ void map2TypeName_mapsJavaClass() { @Test void mapToTypeName_mapsTypeElement() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - JavaLangMapper.mapToTypeName( - typeElement(processingEnv, "test.Dto"), context(processingEnv))), - """ + probe( + (roundEnv, processingEnv) -> + result.set( + JavaLangMapper.mapToTypeName( + typeElement(processingEnv, "test.Dto"), context(processingEnv))), + """ package test; public class Dto {} """); - - assertThat(compilation).succeeded(); assertEquals("test", result.get().getPackageName()); assertEquals("Dto", result.get().getClassName()); } @@ -83,15 +78,14 @@ public class Dto {} @Test void map2MethodParameter_mapsNameAndListType() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - result.set( - JavaLangMapper.map2MethodParameter( - parameter(method(dto, "setTags"), 0), context(processingEnv))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set( + JavaLangMapper.map2MethodParameter( + parameter(method(dto, "setTags"), 0), context(processingEnv))); + }, + """ package test; import java.util.List; public class Dto { @@ -99,8 +93,6 @@ public class Dto { public void setTags(List tags) { this.tags = tags; } } """); - - assertThat(compilation).succeeded(); MethodParameterDto param = result.get(); assertEquals("tags", param.getParameterName()); TypeNameList typeName = assertInstanceOf(TypeNameList.class, param.getParameterType()); @@ -111,21 +103,18 @@ public class Dto { @Test void map2MethodParameter_mapsSetToTypeNameSet() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - result.set(paramType(dto, "setIds", 0, context(processingEnv))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setIds", 0, context(processingEnv))); + }, + """ package test; import java.util.Set; public class Dto { public void setIds(Set ids) {} } """); - - assertThat(compilation).succeeded(); assertInstanceOf(TypeNameSet.class, result.get()); assertEquals("Integer", ((TypeNameSet) result.get()).getElementType().getClassName()); } @@ -133,21 +122,18 @@ public void setIds(Set ids) {} @Test void map2MethodParameter_mapsMapToTypeNameMap() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - result.set(paramType(dto, "setLookup", 0, context(processingEnv))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setLookup", 0, context(processingEnv))); + }, + """ package test; import java.util.Map; public class Dto { public void setLookup(Map lookup) {} } """); - - assertThat(compilation).succeeded(); TypeNameMap typeName = assertInstanceOf(TypeNameMap.class, result.get()); assertEquals("String", typeName.getKeyType().getClassName()); assertEquals("Integer", typeName.getValueType().getClassName()); @@ -156,38 +142,32 @@ public void setLookup(Map lookup) {} @Test void map2MethodParameter_mapsPrimitive() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - result.set(paramType(dto, "setCount", 0, context(processingEnv))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setCount", 0, context(processingEnv))); + }, + """ package test; public class Dto { public void setCount(int count) {} } """); - - assertThat(compilation).succeeded(); assertInstanceOf(TypeNamePrimitive.class, result.get()); } @Test void createDerivedTypeName_appendsSuffix() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - JavaLangMapper.createDerivedTypeName( - typeElement(processingEnv, "test.Dto"), context(processingEnv), "Builder")), - """ + probe( + (roundEnv, processingEnv) -> + result.set( + JavaLangMapper.createDerivedTypeName( + typeElement(processingEnv, "test.Dto"), context(processingEnv), "Builder")), + """ package test; public class Dto {} """); - - assertThat(compilation).succeeded(); assertEquals("test", result.get().getPackageName()); assertEquals("DtoBuilder", result.get().getClassName()); } @@ -196,23 +176,20 @@ public class Dto {} void extractInterfaceTypeArguments_resolvesInheritedListArgument() { // CustomList extends ArrayList: the List element type is Y, not the declared X/Y pair AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - AnnotationProcessingContext ctx = context(processingEnv); - TypeElement customList = typeElement(processingEnv, "test.CustomList"); - TypeElement listInterface = typeElement(processingEnv, "java.util.List"); - result.set( - JavaLangMapper.extractInterfaceTypeArguments( - customList.asType(), listInterface, ctx)); - }, - """ + probe( + (roundEnv, processingEnv) -> { + AnnotationProcessingContext ctx = context(processingEnv); + TypeElement customList = typeElement(processingEnv, "test.CustomList"); + TypeElement listInterface = typeElement(processingEnv, "java.util.List"); + result.set( + JavaLangMapper.extractInterfaceTypeArguments( + customList.asType(), listInterface, ctx)); + }, + """ package test; import java.util.ArrayList; public class CustomList extends ArrayList {} """); - - assertThat(compilation).succeeded(); assertEquals(1, result.get().size()); assertEquals("Y", result.get().get(0).getClassName()); } @@ -221,18 +198,17 @@ public class CustomList extends ArrayList {} void map2MethodParameter_wrapsConcreteCollections() { // ArrayList/HashMap/TreeMap take the hasConstructorWithParameterOfType path and still wrap AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - AnnotationProcessingContext ctx = context(processingEnv); - result.set( - List.of( - paramType(dto, "setTags", 0, ctx), - paramType(dto, "setLookup", 0, ctx), - paramType(dto, "setSorted", 0, ctx))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + AnnotationProcessingContext ctx = context(processingEnv); + result.set( + List.of( + paramType(dto, "setTags", 0, ctx), + paramType(dto, "setLookup", 0, ctx), + paramType(dto, "setSorted", 0, ctx))); + }, + """ package test; import java.util.ArrayList; import java.util.HashMap; @@ -243,8 +219,6 @@ public void setLookup(HashMap lookup) {} public void setSorted(TreeMap sorted) {} } """); - - assertThat(compilation).succeeded(); assertInstanceOf(TypeNameList.class, result.get().get(0)); assertEquals("String", ((TypeNameList) result.get().get(0)).getElementType().getClassName()); assertInstanceOf(TypeNameMap.class, result.get().get(1)); @@ -255,21 +229,18 @@ public void setSorted(TreeMap sorted) {} @Test void map2MethodParameter_wrapsGenericListToTypeNameList() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - result.set(paramType(dto, "setTags", 0, context(processingEnv))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(paramType(dto, "setTags", 0, context(processingEnv))); + }, + """ package test; import java.util.LinkedList; public class Dto { public void setTags(LinkedList tags) {} } """); - - assertThat(compilation).succeeded(); assertInstanceOf(TypeNameList.class, result.get()); assertEquals("Double", ((TypeNameList) result.get()).getElementType().getClassName()); } @@ -277,18 +248,15 @@ public void setTags(LinkedList tags) {} @Test void map2GenericParameterDtos_mapsTypeParametersWithBounds() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - result.set(JavaLangMapper.map2GenericParameterDtos(dto, context(processingEnv))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(JavaLangMapper.map2GenericParameterDtos(dto, context(processingEnv))); + }, + """ package test; public class Dto {} """); - - assertThat(compilation).succeeded(); assertEquals(2, result.get().size()); assertEquals("T", result.get().get(0).getName()); assertEquals("Number", result.get().get(0).getUpperBounds().get(0).getClassName()); @@ -298,22 +266,19 @@ public class Dto {} @Test void map2MethodParameter_mapsArrayAndTypeVariable() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - AnnotationProcessingContext ctx = context(processingEnv); - result.set(List.of(paramType(dto, "setArr", 0, ctx), paramType(dto, "setT", 0, ctx))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + AnnotationProcessingContext ctx = context(processingEnv); + result.set(List.of(paramType(dto, "setArr", 0, ctx), paramType(dto, "setT", 0, ctx))); + }, + """ package test; public class Dto { public void setArr(String[] arr) {} public void setT(T t) {} } """); - - assertThat(compilation).succeeded(); assertEquals("TypeNameArray", result.get().get(0).getClass().getSimpleName()); assertEquals("T", result.get().get(1).getClassName()); } @@ -331,23 +296,22 @@ void mapToTypeName_nullElement_returnsNull() { @Test void map2MethodParameter_mapsAllPrimitiveKinds() { AtomicReference> result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> { - TypeElement dto = typeElement(processingEnv, "test.Dto"); - AnnotationProcessingContext ctx = context(processingEnv); - result.set( - List.of( - paramType(dto, "setB", 0, ctx), - paramType(dto, "setBy", 0, ctx), - paramType(dto, "setS", 0, ctx), - paramType(dto, "setI", 0, ctx), - paramType(dto, "setL", 0, ctx), - paramType(dto, "setC", 0, ctx), - paramType(dto, "setF", 0, ctx), - paramType(dto, "setD", 0, ctx))); - }, - """ + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + AnnotationProcessingContext ctx = context(processingEnv); + result.set( + List.of( + paramType(dto, "setB", 0, ctx), + paramType(dto, "setBy", 0, ctx), + paramType(dto, "setS", 0, ctx), + paramType(dto, "setI", 0, ctx), + paramType(dto, "setL", 0, ctx), + paramType(dto, "setC", 0, ctx), + paramType(dto, "setF", 0, ctx), + paramType(dto, "setD", 0, ctx))); + }, + """ package test; public class Dto { public void setB(boolean b) {} @@ -360,8 +324,6 @@ public void setF(float f) {} public void setD(double d) {} } """); - - assertThat(compilation).succeeded(); List expected = List.of("BOOLEAN", "BYTE", "SHORT", "INT", "LONG", "CHAR", "FLOAT", "DOUBLE"); for (int i = 0; i < expected.size(); i++) { @@ -377,29 +339,26 @@ public void setD(double d) {} @Test void map2MethodParameter_marksTypeWithEmptyConstructor() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - paramType( - typeElement(processingEnv, "test.Dto"), - "setAddress", - 0, - context(processingEnv))), - """ + probe( + (roundEnv, processingEnv) -> + result.set( + paramType( + typeElement(processingEnv, "test.Dto"), + "setAddress", + 0, + context(processingEnv))), + """ package test; public class Address { public Address() {} } """, - """ + """ package test; public class Dto { public void setAddress(Address a) {} } """); - - assertThat(compilation).succeeded(); assertTrue(result.get().hasEmptyConstructor()); } @@ -410,29 +369,23 @@ public void setAddress(Address a) {} @Test void map2MethodParameter_nestedType_mapsTypeNameNested() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - paramType( - typeElement(processingEnv, "test.Dto"), - "setInner", - 0, - context(processingEnv))), - """ + probe( + (roundEnv, processingEnv) -> + result.set( + paramType( + typeElement(processingEnv, "test.Dto"), "setInner", 0, context(processingEnv))), + """ package test; public class Outer { public static class Inner {} } """, - """ + """ package test; public class Dto { public void setInner(Outer.Inner i) {} } """); - - assertThat(compilation).succeeded(); assertInstanceOf(TypeNameNested.class, result.get()); assertEquals("Outer.Inner", result.get().getClassName()); } @@ -445,16 +398,15 @@ public void setInner(Outer.Inner i) {} @Test void map2MethodParameter_fallsBackWhenMapLacksCopyConstructor() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, processingEnv) -> - result.set( - paramType( - typeElement(processingEnv, "test.Dto"), - "setLookup", - 0, - context(processingEnv))), - """ + probe( + (roundEnv, processingEnv) -> + result.set( + paramType( + typeElement(processingEnv, "test.Dto"), + "setLookup", + 0, + context(processingEnv))), + """ package test; public class WeirdMap extends java.util.AbstractMap { @Override @@ -463,14 +415,12 @@ public java.util.Set> entrySet() { } } """, - """ + """ package test; public class Dto { public void setLookup(WeirdMap lookup) {} } """); - - assertThat(compilation).succeeded(); assertInstanceOf(TypeNameGeneric.class, result.get()); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java index b43ae3c7..d383aedc 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java @@ -24,17 +24,16 @@ package org.javahelpers.codegen.processing; -import static com.google.testing.compile.CompilationSubject.assertThat; -import static org.javahelpers.codegen.processing.ProcessingTestUtils.context; import static org.javahelpers.codegen.testing.ElementTestUtils.field; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.context; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.probe; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.google.testing.compile.Compilation; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -44,7 +43,6 @@ import javax.lang.model.type.TypeMirror; import org.javahelpers.codegen.model.type.TypeName; import org.javahelpers.codegen.testing.CapturingProcessingLogger; -import org.javahelpers.codegen.testing.CodegenTestUtils; import org.junit.jupiter.api.Test; /** @@ -69,35 +67,33 @@ void inherited() {} @Test void delegates_elementAndTypeUtilities() { AtomicReference> results = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = ctx.getTypeElement("test.Dto"); - TypeMirror nameType = field(dto, "name").asType(); - TypeMirror dtoType = dto.asType(); - results.set( - List.of( - dto != null, - ctx.getTypeElement(TypeName.of(String.class)) != null, - ctx.getPackageOf(dto).getQualifiedName().contentEquals("test"), - ctx.getPackageElement("test") != null, - ctx.getPackageName(dto).equals("test"), - ctx.getAllMembers(dto).stream() - .anyMatch(e -> e.getSimpleName().contentEquals("inherited")), - ctx.getDocComment(dto) != null - && ctx.getDocComment(dto).contains("Doc comment on the type."), - ((TypeElement) ctx.asElement(dtoType)) - .getQualifiedName() - .equals(dto.getQualifiedName()), - ctx.isSameType(nameType, nameType), - !ctx.isSameType(nameType, dtoType), - ctx.erasure(nameType) != null, - ctx.isAssignable(ctx.erasure(dtoType), ctx.erasure(dtoType)), - !ctx.directSupertypes(dtoType).isEmpty())); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = ctx.getTypeElement("test.Dto"); + TypeMirror nameType = field(dto, "name").asType(); + TypeMirror dtoType = dto.asType(); + results.set( + List.of( + dto != null, + ctx.getTypeElement(TypeName.of(String.class)) != null, + ctx.getPackageOf(dto).getQualifiedName().contentEquals("test"), + ctx.getPackageElement("test") != null, + ctx.getPackageName(dto).equals("test"), + ctx.getAllMembers(dto).stream() + .anyMatch(e -> e.getSimpleName().contentEquals("inherited")), + ctx.getDocComment(dto) != null + && ctx.getDocComment(dto).contains("Doc comment on the type."), + ((TypeElement) ctx.asElement(dtoType)) + .getQualifiedName() + .equals(dto.getQualifiedName()), + ctx.isSameType(nameType, nameType), + !ctx.isSameType(nameType, dtoType), + ctx.erasure(nameType) != null, + ctx.isAssignable(ctx.erasure(dtoType), ctx.erasure(dtoType)), + !ctx.directSupertypes(dtoType).isEmpty())); + }, + DTO_SOURCE); List names = List.of( "typeElement", @@ -120,41 +116,36 @@ void delegates_elementAndTypeUtilities() { @Test void generatedTypes_addFindAndClear() { - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = ctx.getTypeElement("test.Dto"); - TypeName elementType = TypeName.of(String.class); - TypeName generated = TypeName.of(Integer.class); - assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); - ctx.addGeneratedType(elementType, generated); - assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); // dto != elementType - assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isPresent()); - ctx.getGeneratedTypes().clear(); - assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isEmpty()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = ctx.getTypeElement("test.Dto"); + TypeName elementType = TypeName.of(String.class); + TypeName generated = TypeName.of(Integer.class); + assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); + ctx.addGeneratedType(elementType, generated); + assertTrue(ctx.resolveGeneratedType(dto).isEmpty()); // dto != elementType + assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isPresent()); + ctx.getGeneratedTypes().clear(); + assertTrue(ctx.getGeneratedTypes().findGenerated(elementType).isEmpty()); + }, + DTO_SOURCE); } @Test void loggingDelegates_emitToLogger() { CapturingProcessingLogger capture = CapturingProcessingLogger.create(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = - new AnnotationProcessingContext(capture.logger(), env); - ctx.info("hello %s", "info"); - ctx.debug("hello %s", "debug"); - ctx.warning("hello %s", "warning"); - ctx.error("hello %s", "error"); - ctx.startPerformancePhase(); - ctx.endPerformancePhase("phase"); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = new AnnotationProcessingContext(capture.logger(), env); + ctx.info("hello %s", "info"); + ctx.debug("hello %s", "debug"); + ctx.warning("hello %s", "warning"); + ctx.error("hello %s", "error"); + ctx.startPerformancePhase(); + ctx.endPerformancePhase("phase"); + }, + DTO_SOURCE); assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello info"))); assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello warning"))); assertTrue(capture.messages().stream().anyMatch(m -> m.contains("hello error"))); @@ -163,30 +154,26 @@ void loggingDelegates_emitToLogger() { @Test void currentTask_nullByDefault() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - result.set(ctx.getCurrentTask()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set(ctx.getCurrentTask()); + }, + DTO_SOURCE); assertNull(result.get()); } @Test void getElementValuesWithDefaults_includesDefaultsAndSetValues() { AtomicReference elementsWithDefaults = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - VariableElement nameField = field(typeElement(env, "test.Dto"), "name"); - AnnotationMirror suppress = nameField.getAnnotationMirrors().get(0); - elementsWithDefaults.set(ctx.getElementValuesWithDefaults(suppress).size()); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + VariableElement nameField = field(typeElement(env, "test.Dto"), "name"); + AnnotationMirror suppress = nameField.getAnnotationMirrors().get(0); + elementsWithDefaults.set(ctx.getElementValuesWithDefaults(suppress).size()); + }, + DTO_SOURCE); // @SuppressWarnings declares a single 'value' member assertEquals(1, elementsWithDefaults.get()); } @@ -194,25 +181,20 @@ void getElementValuesWithDefaults_includesDefaultsAndSetValues() { @Test void isAccessibleFromGeneratedPackage_publicMembersAccessible() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Dto"); - result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "getName"))); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Dto"); + result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "getName"))); + }, + DTO_SOURCE); assertNotNull(result.get()); } @Test void performanceTracker_defaultsToNoOp() { AtomicReference tracker = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> tracker.set(context(env).getPerformanceTracker()), DTO_SOURCE); - assertThat(compilation).succeeded(); + probe((roundEnv, env) -> tracker.set(context(env).getPerformanceTracker()), DTO_SOURCE); assertNotNull(tracker.get()); assertEquals("NoOpPerformanceTracker", tracker.get().getClass().getSimpleName()); } @@ -224,29 +206,26 @@ void performanceTracker_defaultsToNoOp() { @Test void loggingDelegates_fullSurface() { CapturingProcessingLogger capture = CapturingProcessingLogger.createDebugEnabled(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - TypeElement dto = typeElement(env, "test.Dto"); - AnnotationProcessingContext ctx = - new AnnotationProcessingContext(capture.logger(), env); - ctx.info("plain info"); - ctx.debugEndOperation(); - ctx.debugEndOperation("closing %s", "op"); - ctx.warning(dto, "warn %s", "elem"); - ctx.error(dto, "err %s", "elem"); - ctx.reportBasedOnStrictMode(dto, "strict %s", "elem"); - ctx.reportBasedOnStrictMode("strict %s", "flat"); - AnnotationProcessingContext lenient = - new AnnotationProcessingContext( - capture.logger(), - env, - AnnotationProcessingOptions.builder().strictModeEnabled(false).build()); - lenient.reportBasedOnStrictMode(dto, "lenient %s", "elem"); - lenient.reportBasedOnStrictMode("lenient %s", "flat"); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + TypeElement dto = typeElement(env, "test.Dto"); + AnnotationProcessingContext ctx = new AnnotationProcessingContext(capture.logger(), env); + ctx.info("plain info"); + ctx.debugEndOperation(); + ctx.debugEndOperation("closing %s", "op"); + ctx.warning(dto, "warn %s", "elem"); + ctx.error(dto, "err %s", "elem"); + ctx.reportBasedOnStrictMode(dto, "strict %s", "elem"); + ctx.reportBasedOnStrictMode("strict %s", "flat"); + AnnotationProcessingContext lenient = + new AnnotationProcessingContext( + capture.logger(), + env, + AnnotationProcessingOptions.builder().strictModeEnabled(false).build()); + lenient.reportBasedOnStrictMode(dto, "lenient %s", "elem"); + lenient.reportBasedOnStrictMode("lenient %s", "flat"); + }, + DTO_SOURCE); for (String expected : List.of( "plain info", @@ -266,11 +245,7 @@ void loggingDelegates_fullSurface() { @Test void getTypeElement_nullTypeName_returnsNull() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> result.set(context(env).getTypeElement((TypeName) null)), - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe((roundEnv, env) -> result.set(context(env).getTypeElement((TypeName) null)), DTO_SOURCE); assertNull(result.get()); } @@ -281,15 +256,13 @@ void getTypeElement_nullTypeName_returnsNull() { @Test void isAccessibleFromGeneratedPackage_packagePrivateWithoutTask_denied() { AtomicReference result = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> { - AnnotationProcessingContext ctx = context(env); - TypeElement dto = typeElement(env, "test.Base"); - result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "inherited"))); - }, - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + TypeElement dto = typeElement(env, "test.Base"); + result.set(ctx.isAccessibleFromGeneratedPackage(method(dto, "inherited"))); + }, + DTO_SOURCE); assertEquals(false, result.get()); } @@ -299,22 +272,20 @@ void isAccessibleFromGeneratedPackage_packagePrivateWithoutTask_denied() { @Test void performanceTracker_activeWhenEnabled() { AtomicReference tracker = new AtomicReference<>(); - Compilation compilation = - CodegenTestUtils.probe( - (roundEnv, env) -> - tracker.set( - new AnnotationProcessingContext( - CapturingProcessingLogger.create().logger(), - env, - AnnotationProcessingOptions.builder() - .performanceTrackingEnabled(true) - .phaseHierarchy( - new org.javahelpers.codegen.logging.PhaseHierarchy( - List.of(), Map.of())) - .build()) - .getPerformanceTracker()), - DTO_SOURCE); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> + tracker.set( + new AnnotationProcessingContext( + CapturingProcessingLogger.create().logger(), + env, + AnnotationProcessingOptions.builder() + .performanceTrackingEnabled(true) + .phaseHierarchy( + new org.javahelpers.codegen.logging.PhaseHierarchy( + List.of(), Map.of())) + .build()) + .getPerformanceTracker()), + DTO_SOURCE); assertEquals("ActivePerformanceTracker", tracker.get().getClass().getSimpleName()); } } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java index 25bcaa0a..a2345289 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java @@ -444,7 +444,6 @@ public void setName(String name) {} """); Compilation compilation = CodegenTestUtils.createCompiler(new EmptyProcessor()).compile(source); - assertThat(compilation).succeeded(); } @@ -466,7 +465,6 @@ public void setName(String name) {} Compilation compilation = CodegenTestUtils.createCompiler(new NoTasksProcessor()).compile(source); - assertThat(compilation).succeeded(); } @@ -488,7 +486,6 @@ public void setName(String name) {} CodegenTestUtils.createCompiler(new VerboseProcessor()) .withOptions("-Averbose=true") .compile(source); - assertThat(compilation).succeeded(); String generatedCode = CodegenTestUtils.readSource( diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java index f0db1adc..100c1db1 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java @@ -27,6 +27,7 @@ import static com.google.testing.compile.CompilationSubject.assertThat; import static org.javahelpers.codegen.testing.ElementTestUtils.method; import static org.javahelpers.codegen.testing.ElementTestUtils.typeElement; +import static org.javahelpers.codegen.testing.ProcessingTestUtils.probe; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -47,7 +48,6 @@ import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.javahelpers.codegen.testing.CodegenTestUtils; -import org.javahelpers.codegen.testing.ProbeProcessor; import org.junit.jupiter.api.Test; /** Unit tests for {@link MessagerProcessingLogger} driven by a real Messager. */ @@ -67,19 +67,15 @@ private record Diag(Diagnostic.Kind kind, String message, Element element) {} @Test void warning_attachesElementInDefaultMode() { List diags = new CopyOnWriteArrayList<>(); - Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - MessagerProcessingLogger logger = - MessagerProcessingLogger.create(recordingEnv(env, diags)); - Element param = - method(typeElement(env, "test.Dto"), "setName").getParameters().get(0); - logger.warning(param, "conflict on %s", "name"); - logger.flushWarningLocations(); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.create(recordingEnv(env, diags)); + Element param = method(typeElement(env, "test.Dto"), "setName").getParameters().get(0); + logger.warning(param, "conflict on %s", "name"); + logger.flushWarningLocations(); + }, + DTO_SOURCE); assertEquals(1, diags.size()); Diag diag = diags.get(0); assertEquals(Diagnostic.Kind.WARNING, diag.kind()); @@ -91,14 +87,13 @@ void warning_attachesElementInDefaultMode() { void error_attachesElement() { List diags = new CopyOnWriteArrayList<>(); Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - MessagerProcessingLogger logger = - MessagerProcessingLogger.create(recordingEnv(env, diags)); - logger.error(typeElement(env, "test.Dto"), "failed on %s", "Dto"); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); + CodegenTestUtils.probe( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.create(recordingEnv(env, diags)); + logger.error(typeElement(env, "test.Dto"), "failed on %s", "Dto"); + }, + DTO_SOURCE); // the emitted error fails the compilation on purpose assertThat(compilation).failed(); assertEquals(1, diags.size()); @@ -109,21 +104,17 @@ void error_attachesElement() { @Test void verboseWarning_deferLocationAndFlushOncePerType() { List diags = new CopyOnWriteArrayList<>(); - Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - MessagerProcessingLogger logger = - MessagerProcessingLogger.createVerbose(recordingEnv(env, diags), "test"); - Element param = - method(typeElement(env, "test.Dto"), "setName").getParameters().get(0); - logger.warning(param, "first %s", "a"); - logger.warning(param, "second %s", "b"); - logger.flushWarningLocations(); - logger.flushWarningLocations(); // cleared -> nothing more - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.createVerbose(recordingEnv(env, diags), "test"); + Element param = method(typeElement(env, "test.Dto"), "setName").getParameters().get(0); + logger.warning(param, "first %s", "a"); + logger.warning(param, "second %s", "b"); + logger.flushWarningLocations(); + logger.flushWarningLocations(); // cleared -> nothing more + }, + DTO_SOURCE); assertEquals(3, diags.size()); // two flat warnings without element + one location marker on the enclosing type assertTrue(diags.get(0).message().contains("first a")); @@ -135,17 +126,14 @@ void verboseWarning_deferLocationAndFlushOncePerType() { @Test void deferWarningLocation_ignoresNullElement() { List diags = new CopyOnWriteArrayList<>(); - Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> { - MessagerProcessingLogger logger = - MessagerProcessingLogger.createVerbose(recordingEnv(env, diags)); - logger.warning((Element) null, "orphan warning"); - logger.flushWarningLocations(); - })) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> { + MessagerProcessingLogger logger = + MessagerProcessingLogger.createVerbose(recordingEnv(env, diags)); + logger.warning((Element) null, "orphan warning"); + logger.flushWarningLocations(); + }, + DTO_SOURCE); assertEquals(1, diags.size()); assertTrue(diags.get(0).message().contains("orphan warning")); } @@ -153,14 +141,11 @@ void deferWarningLocation_ignoresNullElement() { @Test void loggingPrefix_appliesToMessages() { List diags = new CopyOnWriteArrayList<>(); - Compilation compilation = - CodegenTestUtils.createCompiler( - new ProbeProcessor( - (roundEnv, env) -> - MessagerProcessingLogger.create(recordingEnv(env, diags), "myproc") - .info("hello %s", "world"))) - .compile(CodegenTestUtils.forSource(DTO_SOURCE)); - assertThat(compilation).succeeded(); + probe( + (roundEnv, env) -> + MessagerProcessingLogger.create(recordingEnv(env, diags), "myproc") + .info("hello %s", "world"), + DTO_SOURCE); assertTrue(diags.get(0).message().contains("myproc")); } diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessingTestUtils.java b/simple-processor/src/test/java/org/javahelpers/codegen/testing/ProcessingTestUtils.java similarity index 50% rename from simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessingTestUtils.java rename to simple-processor/src/test/java/org/javahelpers/codegen/testing/ProcessingTestUtils.java index dcac4484..9c7bc95c 100644 --- a/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessingTestUtils.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/testing/ProcessingTestUtils.java @@ -22,12 +22,22 @@ * SOFTWARE. */ -package org.javahelpers.codegen.processing; +package org.javahelpers.codegen.testing; +import static com.google.testing.compile.CompilationSubject.assertThat; + +import com.google.testing.compile.Compilation; +import java.util.List; +import java.util.function.BiConsumer; import javax.annotation.processing.ProcessingEnvironment; -import org.javahelpers.codegen.testing.CapturingProcessingLogger; +import javax.annotation.processing.RoundEnvironment; +import org.javahelpers.codegen.processing.AnnotationProcessingContext; -/** Shared helpers for simple-processor tests running against a live compilation. */ +/** + * Shared helpers for simple-processor tests running against a live compilation. Lives in this + * module's test sources (not codegen-testing) because {@link AnnotationProcessingContext} is a + * simple-processor type — codegen-testing sits below it in the dependency graph. + */ public final class ProcessingTestUtils { private ProcessingTestUtils() { @@ -45,4 +55,33 @@ public static AnnotationProcessingContext context(ProcessingEnvironment processi return new AnnotationProcessingContext( CapturingProcessingLogger.create().logger(), processingEnv); } + + /** + * Compiles the given source texts with a {@link ProbeProcessor} running {@code probe} in the + * first processing round and asserts the compilation succeeded. + * + * @param probe callback receiving the {@link RoundEnvironment} and {@link ProcessingEnvironment} + * @param sources the Java source texts to compile + * @return the compilation result + */ + public static Compilation probe( + BiConsumer probe, String... sources) { + Compilation compilation = CodegenTestUtils.probe(probe, sources); + assertThat(compilation).succeeded(); + return compilation; + } + + /** + * Same as {@link #probe(BiConsumer, String...)} for source lists. + * + * @param probe callback receiving the {@link RoundEnvironment} and {@link ProcessingEnvironment} + * @param sources the Java source texts to compile + * @return the compilation result + */ + public static Compilation probe( + BiConsumer probe, List sources) { + Compilation compilation = CodegenTestUtils.probe(probe, sources); + assertThat(compilation).succeeded(); + return compilation; + } } From 9b8cbc27cae8aa85632522bb42ee74404b7eb7d1 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:33:46 +0000 Subject: [PATCH 12/12] test: full textblock for generatesGenericClassAndMethods --- .../codegen/roaster/RoasterCodeGeneratorTest.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java index 77b26082..ed02a2d7 100644 --- a/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -24,7 +24,6 @@ package org.javahelpers.codegen.roaster; -import static org.javahelpers.codegen.testing.ProcessorAsserts.assertContaining; import static org.javahelpers.codegen.testing.ProcessorAsserts.assertNormalizedEquals; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -139,11 +138,15 @@ void generatesGenericClassAndMethods() throws Exception { genericMethod.setCode("return null;"); classDef.addMethod(genericMethod); - assertContaining( - generate(classDef).generatedSource(), - "public class GenericBuilder", - "public static T of(R input) {", - "return null;"); + assertGeneratedSource( + """ + package test; + public class GenericBuilder { + public static T of(R input) { + return null; + } + }""", + classDef); } @Test