diff --git a/codegen-core/pom.xml b/codegen-core/pom.xml index 34c57895..910bba1c 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 + + @@ -340,12 +348,14 @@ - - **/codegen/model/** + + **/model/** + **/enums/** **/*Exception.* + **/exceptions/** - **/JavadocConstants.* + **/*Constants.* 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 e4b32a30..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; @@ -102,6 +103,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), + Arrays.stream(innerTypeArguments).map(TypeName::of).toArray(TypeName[]::new)); + } + /** * Returns the raw type (without type parameters). * 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 67% 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..65b5507d 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("codegen"); tracker.generateReport(capturing.logger()); // Remove the diagnostic kind marker and the exact measurements (durations, percentages, @@ -139,49 +201,48 @@ 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); } @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..bacc315e --- /dev/null +++ b/codegen-core/src/test/java/org/javahelpers/codegen/logging/SinkProcessingLoggerTest.java @@ -0,0 +1,112 @@ +/* + * 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.assertFalse; +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); + assertFalse(messages.isEmpty()); + 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/codegen-roaster/pom.xml b/codegen-roaster/pom.xml index 6bced4ba..886f27af 100644 --- a/codegen-roaster/pom.xml +++ b/codegen-roaster/pom.xml @@ -345,10 +345,14 @@ + + **/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 new file mode 100644 index 00000000..0ca7a06c --- /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.assertNotSame; +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()); + 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/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..10d42bb7 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,12 +22,11 @@ * 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.SourceFormatter; import org.javahelpers.codegen.enums.AccessModifier; @@ -40,15 +39,9 @@ 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.javahelpers.codegen.testing.TestingGenerationEnvironment; import org.junit.jupiter.api.Test; /** @@ -84,14 +77,9 @@ 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); + ProcessingLogger logger = CapturingProcessingLogger.create().logger(); RoasterCodeGenerator generator = - new RoasterCodeGenerator( - new AnnotationProcessingEnvironment( - env, logger, context.getPerformanceTracker(), context::reportBasedOnStrictMode)); + new RoasterCodeGenerator(TestingGenerationEnvironment.createUnwritable(logger)); SourceFormatter formatter = new RoasterSourceFormatter(logger, FormattingMode.NONE); CodeGenerationException thrown = @@ -117,19 +105,11 @@ 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)); + 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 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)'" @@ -142,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 new file mode 100644 index 00000000..ed02a2d7 --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java @@ -0,0 +1,318 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +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.TestingGenerationEnvironment; +import org.junit.jupiter.api.Test; + +/** + * Tests for {@link RoasterCodeGenerator} driving {@link GenerationTargetClassDto}s directly — no + * 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 { + + @Test + void generatesDelegatingBuilderFromDto() throws Exception { + assertGeneratedSource( + """ + 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; + } + }""", + personBuilderDefinition()); + } + + @Test + void writesFileUnderQualifiedName() throws Exception { + GenerationTargetClassDto empty = new GenerationTargetClassDto(); + empty.setTypeName(new TypeName("com.example", "EmptyBuilder")); + empty.setClassAccessModifier(AccessModifier.PUBLIC); + empty.setFormattingMode(FormattingMode.NONE); + + assertEquals("mem:///com/example/EmptyBuilder.java", generate(empty).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); + + 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 + 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); + + assertGeneratedSource( + """ + package test; + public class GenericBuilder { + public static T of(R input) { + return null; + } + }""", + classDef); + } + + @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); + + assertGeneratedSource( + """ + package test; + import test.anno.NonNull; + public class CtorBuilder { + private int DEFAULT_SIZE = 42; + protected CtorBuilder(int capacity) { + } + }""", + classDef); + } + + @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); + + assertGeneratedSource( + """ + package test; + public class OuterBuilder { + /** + * Nested helper. + */ + public class Helper { + public void assist() { + } + } + }""", + classDef); + } + + @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(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(TypeName.of(Override.class)); + method.addAnnotation(override_); + MethodParameterDto param = new MethodParameterDto(); + param.setParameterName("values"); + param.setParameterTypeName(new TypeNameGeneric(List.class, String.class)); + method.addParameter(param); + method.setCode("return null;"); + classDef.addMethod(method); + + assertGeneratedSource( + """ + 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; + } + }""", + 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; + } + + /** 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(TypeName.of(String.class)); + 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-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..bee5f6e9 --- /dev/null +++ b/codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java @@ -0,0 +1,208 @@ +/* + * 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(List.class, String.class); + assertEquals("List", RoasterMapper.mapType(generic)); + } + + @Test + void mapType_rendersRawGenericWithoutArguments() { + TypeNameGeneric generic = new TypeNameGeneric(List.class); + assertEquals("List", RoasterMapper.mapType(generic)); + } + + @Test + void mapType_prependsTypeUseAnnotations() { + TypeName annotated = TypeName.of(String.class); + 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 1914abc5..4b5bfca6 100644 --- a/codegen-testing/pom.xml +++ b/codegen-testing/pom.xml @@ -351,12 +351,14 @@ - - **/codegen/model/** + + **/model/** + **/enums/** **/*Exception.* + **/exceptions/** - **/JavadocConstants.* + **/*Constants.* 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..0fea720c --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/CapturingLogHandler.java @@ -0,0 +1,72 @@ +/* + * 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 logRecord) { + records.append(logRecord.getMessage()).append('\n'); + } + + @Override + public void flush() { + // records accumulate in memory only — nothing to 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 new file mode 100644 index 00000000..1403c6a8 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ElementTestUtils.java @@ -0,0 +1,123 @@ +/* + * 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.List; +import java.util.stream.Stream; +import javax.annotation.processing.ProcessingEnvironment; +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 + * ProbeProcessor} probes to grab compiled test types, their fields, methods and parameters. + */ +public final class ElementTestUtils { + + private static final String ON = "' on "; + + 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 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 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 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 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 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, 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(VariableElement::asType) + .map(TypeMirror::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. */ + 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..aa84ff15 --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/ProbeProcessor.java @@ -0,0 +1,108 @@ +/* + * 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.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. + * + *

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 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
+ * TypeElement dto = ProbeProcessor.probe(
+ *     (roundEnv, processingEnv) ->
+ *         ElementTestUtils.typeElement(processingEnv, "test.Dto"),
+ *     CodegenTestUtils.forSource("package test; public class Dto {}"));
+ * }
+ */ +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 + */ + @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<>(); + 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 + */ + 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); + // Claim the annotations of the round the probe consumed. + return true; + } +} 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..07cc045f --- /dev/null +++ b/codegen-testing/src/main/java/org/javahelpers/codegen/testing/TestingGenerationEnvironment.java @@ -0,0 +1,132 @@ +/* + * 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 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. + */ + 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 new file mode 100644 index 00000000..fe95e53b --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CapturingProcessingLoggerTest.java @@ -0,0 +1,85 @@ +/* + * 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")); + } + + @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 new file mode 100644 index 00000000..d8241a35 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/CodegenTestUtilsTest.java @@ -0,0 +1,163 @@ +/* + * 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 javax.tools.JavaFileObject; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link CodegenTestUtils} — the compile-testing helpers themselves. */ +class CodegenTestUtilsTest { + + @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.probe( + (roundEnv, env) -> emitGeneratedSource(env), + 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")); + } + + @Test + void assertNoWarningContaining_passesWithoutMatchingWarning() { + final String warningMessage = "a warning"; + Compilation compilation = + 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, warningMessage)); + } + + @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_emitToLog() { + Compilation compilation = + CodegenTestUtils.probe( + (roundEnv, env) -> emitGeneratedSource(env), + CodegenTestUtils.forSource("package test;\npublic class Dto {}\n")); + + assertThat(compilation).succeeded(); + String captured; + try (CapturingLogHandler handler = + new CapturingLogHandler( + java.util.logging.Logger.getLogger(CodegenTestUtils.class.getName()))) { + CodegenTestUtils.printDiagnostics(compilation); + CodegenTestUtils.printGeneratedSources(compilation); + captured = handler.output(); + } + assertTrue(captured.contains("Compilation Diagnostics")); + assertTrue(captured.contains("Generated Source Files")); + assertTrue(captured.contains("Generated.java")); + assertTrue(captured.contains("public class Generated")); + } + + /** + * 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/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..2de50024 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ElementTestUtilsTest.java @@ -0,0 +1,111 @@ +/* + * 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.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 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 T probe( + java.util.function.BiFunction< + javax.annotation.processing.RoundEnvironment, + javax.annotation.processing.ProcessingEnvironment, + T> + probeFn) { + return ProbeProcessor.probe(probeFn, CodegenTestUtils.forSource(DTO_SOURCE)); + } + + @Test + void typeElement_findsCompiledType() { + TypeElement dto = probe((roundEnv, env) -> typeElement(env, "test.Dto")); + assertEquals("test.Dto", dto.getQualifiedName().toString()); + } + + @Test + void field_findsDeclaredField() { + 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 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_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")); + } + + @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() { + VariableElement param = + probe( + (roundEnv, env) -> + parameter(method(typeElement(env, "test.Dto"), "setName", "java.lang.String"), 0)); + assertEquals("name", param.getSimpleName().toString()); + } +} 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/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 new file mode 100644 index 00000000..bb7ef9a0 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessingEnvironmentStubTest.java @@ -0,0 +1,69 @@ +/* + * 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.assertNull; +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()); + } + + @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 new file mode 100644 index 00000000..5c9e5090 --- /dev/null +++ b/codegen-testing/src/test/java/org/javahelpers/codegen/testing/ProcessorAssertsTest.java @@ -0,0 +1,174 @@ +/* + * 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 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. */ +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")); + var failingCheck = notContains("class Foo"); + assertThrows(AssertionError.class, () -> ProcessorAsserts.assertingResult(CODE, failingCheck)); + } + + @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")); + } + + @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/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/core/pom.xml b/core/pom.xml index 19c05c4d..5eaa09e8 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,18 @@ report + + + + **/model/** + **/enums/** + + **/*Exception.* + **/exceptions/** + + **/*Constants.* + + diff --git a/processor/pom.xml b/processor/pom.xml index 3a20b441..ca1b6168 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 @@ -379,12 +374,14 @@ - - **/processor/model/** + + **/model/** + **/enums/** + **/*Exception.* **/exceptions/** - **/JavadocConstants.* + **/*Constants.* 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 9ca5024b..c112222e 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 @@ -308,8 +308,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/processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java b/processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java deleted file mode 100644 index 3358a2b8..00000000 --- a/processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java +++ /dev/null @@ -1,215 +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.processing; - -import static com.google.testing.compile.CompilationSubject.assertThat; -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; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.util.List; -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.tools.JavaFileObject; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.Strings; -import org.javahelpers.codegen.analysis.JavaLangAnalyser; -import org.javahelpers.codegen.analysis.JavaLangMapper; -import org.javahelpers.codegen.enums.AccessModifier; -import org.javahelpers.codegen.enums.FormattingMode; -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.type.TypeName; -import org.javahelpers.simple.builders.processor.testing.ProcessorTestUtils; -import org.junit.jupiter.api.Test; - -/** - * A complete codegen processor in minimal form — only the domain members that have no generic - * default are implemented; collection, round-driving, generator and formatter wiring come from - * {@link AbstractCodegenProcessor}. - */ -public class MinimalCodegenProcessorTest { - - /** Marks a type for delegate-builder generation in this test. */ - @Target(ElementType.TYPE) - @Retention(RetentionPolicy.SOURCE) - public @interface GenerateBuilder {} - - /** Analysis result: target type, builder name and the setters to delegate to. */ - record MinimalTargetDefinition( - TypeName sourceTypeName, TypeName builderTypeName, List setters) - implements CodegenDefinition { - @Override - public TypeName getTypeName() { - return sourceTypeName; - } - - @Override - public TypeName targetTypeName() { - return builderTypeName; - } - } - - /** A processor that generates a builder delegating to the target type's setters. */ - static class MinimalProcessor - extends AbstractCodegenProcessor< - AnnotationProcessingContext, CodegenConfiguration, MinimalTargetDefinition> { - - MinimalProcessor() { - super( - CodegenProcessorConfiguration.builder() - .elementCollector(ElementCollector.builder().selector(GenerateBuilder.class).build()) - .loggerPrefix("minimal") - .build()); - } - - @Override - protected AnnotationProcessingContext createContext( - ProcessingEnvironment processingEnv, - CompilerArgumentsReader reader, - ProcessingLogger logger) { - return new AnnotationProcessingContext(logger, processingEnv); - } - - @Override - protected List> planTasks( - ElementGroups collected, AnnotationProcessingContext ctx) { - return collected.all().stream() - .map( - element -> - CodegenTask.builder(CodegenConfiguration.class) - .element(element) - .outputPackage(ctx.getPackageName(element)) - .build()) - .toList(); - } - - @Override - protected List analyse( - CodegenTask task, AnnotationProcessingContext ctx) { - if (!(task.element() instanceof TypeElement target)) { - return List.of(); - } - return List.of( - new MinimalTargetDefinition( - JavaLangMapper.mapToTypeName(target, ctx), - builderName(target, ctx), - JavaLangAnalyser.findSetterMethods(target, ctx))); - } - - @Override - protected GenerationTargetClassDto mapToTargetSpecification( - MinimalTargetDefinition definition, - CodegenConfiguration configuration, - AnnotationProcessingContext ctx) { - GenerationTargetClassDto target = new GenerationTargetClassDto(); - target.setTypeName(definition.builderTypeName()); - target.setClassAccessModifier(AccessModifier.PUBLIC); - target.setFormattingMode(FormattingMode.NONE); - - ClassFieldDto field = new ClassFieldDto(); - field.setFieldName("target"); - field.setFieldType(definition.sourceTypeName()); - field.setVisibility(AccessModifier.PRIVATE); - field.setLiteralInitializer("new " + definition.sourceTypeName().getClassName() + "()"); - target.addClassField(field); - - for (ExecutableElement setter : definition.setters()) { - String setterName = setter.getSimpleName().toString(); - String methodName = StringUtils.uncapitalize(Strings.CI.removeStart(setterName, "set")); - MethodDto method = new MethodDto(methodName, definition.builderTypeName()); - method.setModifier(AccessModifier.PUBLIC); - String paramName = setter.getParameters().get(0).getSimpleName().toString(); - method.addParameter(JavaLangMapper.map2MethodParameter(setter.getParameters().get(0), ctx)); - method.setCode( - """ - target.$setterName:N($paramName:N); - return this;"""); - method.addArgument("setterName", setterName); - method.addArgument("paramName", paramName); - target.addMethod(method); - } - MethodDto build = new MethodDto("build", definition.sourceTypeName()); - build.setModifier(AccessModifier.PUBLIC); - build.setCode("return target;"); - target.addMethod(build); - return target; - } - - private static TypeName builderName(TypeElement target, AnnotationProcessingContext ctx) { - return new TypeName(ctx.getPackageName(target), target.getSimpleName() + "Builder"); - } - } - - @Test - void minimalProcessorGeneratesDelegatingBuilder() { - // Given - JavaFileObject source = - ProcessorTestUtils.forSource( - """ - package test; - import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; - @GenerateBuilder - public class Person { - private String name; - public void setName(String name) { this.name = name; } - } - """); - - // When - Compilation compilation = - ProcessorTestUtils.createCompiler(new MinimalProcessor()).compile(source); - - // Then - assertThat(compilation).succeeded(); - String generatedCode = loadGeneratedSource(compilation, "PersonBuilder"); - // The whole expected target as one textblock — pins structure, delegation and the target - // field; whitespace-normalized compare, nothing generated is left unchecked. - 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; - } - }""", - generatedCode, - "generated PersonBuilder must match the expected source"); - } -} diff --git a/processor/src/test/java/org/javahelpers/simple/builders/processor/JavaLangAnalyserTest.java b/processor/src/test/java/org/javahelpers/simple/builders/processor/JavaLangAnalyserTest.java deleted file mode 100644 index 1a211d13..00000000 --- a/processor/src/test/java/org/javahelpers/simple/builders/processor/JavaLangAnalyserTest.java +++ /dev/null @@ -1,322 +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.simple.builders.processor; - -import static org.junit.jupiter.api.Assertions.*; - -import java.lang.annotation.Annotation; -import java.util.List; -import java.util.Set; -import java.util.stream.Stream; -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.Modifier; -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; -import org.junit.jupiter.params.provider.MethodSource; - -/** Unit tests for {@link JavaLangAnalyser}. */ -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 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)); - } - - @ParameterizedTest(name = "{0}") - @MethodSource("extractParamJavaDocNullCases") - void extractParamJavaDoc_shouldReturnNull( - String testCase, String javaDoc, VariableElement param) { - assertNull(JavaLangAnalyser.extractParamJavaDoc(javaDoc, param)); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @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 */"; - assertEquals( - "this is a test parameter", JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); - } - - @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)); - } - - @Test - void extractParamJavaDoc_shouldHandleEmptyParamTag() { - String javaDoc = "/**\n * @param testParam\n * @return something\n */"; - assertNull(JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); - } - - @Test - void extractParamJavaDoc_shouldHandleWhitespaceOnlyParamTag() { - String javaDoc = - "/**\n * @param testParam \t\n * @return something\n */"; - assertNull(JavaLangAnalyser.extractParamJavaDoc(javaDoc, parameter)); - } - - @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)); - } - - @Test - void findGetterForField_shouldReturnEmpty_whenDtoTypeIsNull() { - assertTrue(JavaLangAnalyser.findGetterForField(null, "fieldName", null, null).isEmpty()); - } - - @Test - void findGetterForField_shouldReturnEmpty_whenFieldNameIsNull() { - assertTrue(JavaLangAnalyser.findGetterForField(null, null, null, null).isEmpty()); - } - - @Test - void findGetterForField_shouldReturnEmpty_whenFieldTypeMirrorIsNull() { - assertTrue(JavaLangAnalyser.findGetterForField(null, "fieldName", null, null).isEmpty()); - } - - @Test - void extractDeprecatedJavaDoc_shouldReturnNull_whenJavaDocHasNoDeprecatedTag() { - String javaDoc = - """ - /** - * Some method description. - * @param name the name - * @return something - */ - """; - assertNull(JavaLangAnalyser.extractDeprecatedJavaDoc(javaDoc)); - } - - @Test - void extractDeprecatedJavaDoc_shouldReturnNull_whenJavaDocIsNull() { - assertNull(JavaLangAnalyser.extractDeprecatedJavaDoc(null)); - } - - @Test - void extractDeprecatedJavaDoc_shouldExtractSingleLineDeprecatedText() { - String javaDoc = - """ - /** - * Some method description. - * @deprecated use {@link #newMethod} instead - * @return something - */ - """; - assertEquals( - "use {@link #newMethod} instead", JavaLangAnalyser.extractDeprecatedJavaDoc(javaDoc)); - } - - @Test - void extractDeprecatedJavaDoc_shouldExtractMultiLineDeprecatedText() { - String javaDoc = - """ - /** - * Some method description. - * @deprecated use {@link #newMethod} instead - * and migrate all callers - * @return something - */ - """; - assertEquals( - "use {@link #newMethod} instead and migrate all callers", - JavaLangAnalyser.extractDeprecatedJavaDoc(javaDoc)); - } - - @Test - void findFieldElement_shouldReturnEmpty_whenClassElementIsNull() { - assertTrue(JavaLangAnalyser.findFieldElement(null, "fieldName").isEmpty()); - } - - @Test - void findFieldElement_shouldReturnEmpty_whenFieldNameIsNull() { - assertTrue(JavaLangAnalyser.findFieldElement(null, null).isEmpty()); - } - - @Test - void findRecordComponent_shouldReturnEmpty_whenTypeElementIsNull() { - assertTrue(JavaLangAnalyser.findRecordComponent(null, "componentName").isEmpty()); - } - - @Test - void findRecordComponent_shouldReturnEmpty_whenComponentNameIsNull() { - assertTrue(JavaLangAnalyser.findRecordComponent(null, null).isEmpty()); - } - - @Test - void findSetterForField_shouldReturnEmpty_whenDtoTypeIsNull() { - assertTrue(JavaLangAnalyser.findSetterForField(null, "fieldName", null).isEmpty()); - } - - @Test - void findSetterForField_shouldReturnEmpty_whenFieldNameIsNull() { - assertTrue(JavaLangAnalyser.findSetterForField(null, null, null).isEmpty()); - } -} diff --git a/simple-processor/pom.xml b/simple-processor/pom.xml index e5a1ac42..3189e649 100644 --- a/simple-processor/pom.xml +++ b/simple-processor/pom.xml @@ -339,12 +339,14 @@ - - **/codegen/model/** + + **/model/** + **/enums/** **/*Exception.* + **/exceptions/** - **/JavadocConstants.* + **/*Constants.* 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..c991eb8c --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/FieldAnnotationExtractorTest.java @@ -0,0 +1,305 @@ +/* + * 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.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 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.junit.jupiter.api.Test; + +/** Unit tests for {@link FieldAnnotationExtractor} against elements captured from a compilation. */ +class FieldAnnotationExtractorTest { + + 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 @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; + } + """; + + private static final String DEFAULT_ANNOTATION_SOURCE = + """ + package test; + public @interface Default { String value(); } + """; + + 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 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<>(); + 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()); + } + + @Test + void extractDeprecatedAnnotation_emptyForPlainField() { + AtomicReference> result = new AtomicReference<>(); + 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<>(); + 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()); + assertEquals("\"GENERAL\"", annotation.getMembers().get("value")); + } + + @Test + void hasNonNullConstraint_detectsNonNullAnnotation() { + AtomicReference nonNull = new AtomicReference<>(); + AtomicReference plain = new AtomicReference<>(); + 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()); + } + + @Test + void extractAnnotationValue_matchesAnnotationBySimpleName() { + AtomicReference> result = new AtomicReference<>(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractAnnotationValue( + field(typeElement(processingEnv, "test.Dto"), "mode"), Set.of("Default"))), + DTO_SOURCES); + assertEquals(Optional.of("GENERAL"), result.get()); + } + + @Test + void formatDefaultExpression_quotesStringValues() { + assertEquals( + "\"GENERAL\"", + 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"); + 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))); + } + + @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<>(); + probe( + (roundEnv, processingEnv) -> + result.set( + FieldAnnotationExtractor.extractDeprecatedAnnotation( + field(typeElement(processingEnv, "test.Dto"), "mode"), context(processingEnv))), + DTO_SOURCES); + 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<>(); + 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()); + } + + /** + * 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<>(); + 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")); + 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<>(); + 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")); + } + + @Test + void extractAnnotationValue_emptyWhenAnnotationHasNoValueMember() { + AtomicReference> result = new AtomicReference<>(); + 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<>(); + 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/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 new file mode 100644 index 00000000..1968505b --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangAnalyserTest.java @@ -0,0 +1,598 @@ +/* + * 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.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 java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +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 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.junit.jupiter.api.Test; + +/** Unit tests for {@link JavaLangAnalyser} against elements captured from a real compilation. */ +class JavaLangAnalyserTest { + + 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 final String PRIVATE_CTOR_SOURCE = + """ + package test; + public class PrivateCtor { + private PrivateCtor() {} + public PrivateCtor(String a) {} + } + """; + + private static final String NESTED_SOURCE = + """ + package test; + public class Outer { + public static class Inner { + public static class Deep {} + } + } + """; + + @Test + void isNoMethodOfObjectClass_filtersObjectMethods() { + AtomicReference onObject = new AtomicReference<>(); + AtomicReference onOwn = new AtomicReference<>(); + 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()); + } + + @Test + void findSetterMethods_returnsSettersSortedByNameAndParameterType() { + AtomicReference> result = new AtomicReference<>(); + 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()); + } + + @Test + void hasNotAnnotation_checksForAnnotationPresence() { + AtomicReference deprecated = new AtomicReference<>(); + AtomicReference plain = new AtomicReference<>(); + 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()); + } + + @Test + void methodPredicates_coverThrowsReturnVisibilityStaticGenerics() { + AtomicReference> results = new AtomicReference<>(); + 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()); + } + + @Test + void hasEmptyConstructor_detectsAccessibleNoArgConstructor() { + AtomicReference dto = new AtomicReference<>(); + AtomicReference ctor = new AtomicReference<>(); + 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()); + } + + @Test + void findAnnotation_locatesDirectAnnotation() { + AtomicReference> result = new AtomicReference<>(); + probe( + (roundEnv, env) -> + result.set( + JavaLangAnalyser.findAnnotation( + method(typeElement(env, "test.Dto"), "old"), Deprecated.class)), + DTO_SOURCE); + assertTrue(result.get().isPresent()); + } + + @Test + void findAnnotationInstances_unwrapsRepeatableContainerAndDirect() { + AtomicReference directCount = new AtomicReference<>(); + AtomicReference containerCount = new AtomicReference<>(); + 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()); + } + + @Test + void findAnnotationAttributeAndArray_readValues() { + AtomicReference value = new AtomicReference<>(); + AtomicReference arraySize = new AtomicReference<>(); + 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()); + } + + @Test + void resolveTypeElement_resolvesAnnotationValueToTypeElement() { + AtomicReference> result = new AtomicReference<>(); + 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()); + } + + @Test + void findMethodsStatic_filtersBySignatureAndStaticModifier() { + AtomicReference> single = new AtomicReference<>(); + AtomicReference> voidReturn = new AtomicReference<>(); + AtomicReference> allStatic = new AtomicReference<>(); + 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()); + } + + @Test + void findMethods_matchesByParametersAndReturnType() { + AtomicReference> result = new AtomicReference<>(); + 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()); + } + + @Test + void findMethodWithoutParameters_matchesNameAndModifiers() { + AtomicReference> found = new AtomicReference<>(); + AtomicReference> missing = new AtomicReference<>(); + 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()); + } + + @Test + void findReadableProperties_combinesRecordComponentsGettersAndFields() { + AtomicReference> recordProps = new AtomicReference<>(); + AtomicReference> dtoProps = new AtomicReference<>(); + 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"))); + } + + @Test + void findSingleParameterMethods_returnsNonStaticOneParamMethods() { + AtomicReference> result = new AtomicReference<>(); + 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()); + } + + @Test + void hasConstructorAccepting_matchesParameterType() { + AtomicReference matching = new AtomicReference<>(); + AtomicReference nonMatching = new AtomicReference<>(); + 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()); + } + + @Test + void isFunctionalInterface_detectsAnnotatedAndSingleAbstractMethod() { + AtomicReference> results = new AtomicReference<>(); + 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<>(); + probe( + (roundEnv, env) -> + mth.set(method(typeElement(env, "test.Dto"), "setName", "java.lang.String")), + DTO_SOURCE); + String javadoc = + """ + Sets the name. + @param name the name + continued description + @return nothing + """; + assertEquals( + "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 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 findGetterForField_matchesRecordBooleanAndStandardAccessors() { + AtomicReference> byGet = new AtomicReference<>(); + AtomicReference> byIs = new AtomicReference<>(); + AtomicReference> absent = new AtomicReference<>(); + 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()); + } + + @Test + void findFieldElementAndRecordComponent_locateMembers() { + AtomicReference fieldFound = new AtomicReference<>(); + AtomicReference fieldMissing = new AtomicReference<>(); + AtomicReference compFound = new AtomicReference<>(); + 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()); + } + + @Test + void findSetterForField_matchesVoidSingleParamSetter() { + AtomicReference> found = new AtomicReference<>(); + AtomicReference> missing = new AtomicReference<>(); + 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()); + } + + @Test + void findAccessibleConstructors_excludesPrivate() { + AtomicReference twoCtor = new AtomicReference<>(); + AtomicReference privateCtor = new AtomicReference<>(); + 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()); + } + + @Test + void findConstructorsAnnotatedWith_findsMarkedCtor() { + AtomicReference> annotated = new AtomicReference<>(); + 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()); + } + + @Test + void findConstructorsAnnotatedWith_emptyWhenUnmarked() { + AtomicReference> annotated = new AtomicReference<>(); + probe( + (roundEnv, env) -> + annotated.set( + JavaLangAnalyser.findConstructorsAnnotatedWith( + typeElement(env, "test.Dto"), Deprecated.class, context(env))), + DTO_SOURCE); + assertTrue(annotated.get().isEmpty()); + } + + @Test + void findTopLevelType_walksToOutermostType() { + AtomicReference deepTop = new AtomicReference<>(); + AtomicReference outerTop = new AtomicReference<>(); + 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 new file mode 100644 index 00000000..0f1b9e76 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/analysis/JavaLangMapperTest.java @@ -0,0 +1,432 @@ +/* + * 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.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 java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import javax.lang.model.element.TypeElement; +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; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link JavaLangMapper} against elements captured from a real compilation. */ +class JavaLangMapperTest { + + @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<>(); + probe( + (roundEnv, processingEnv) -> + result.set( + JavaLangMapper.mapToTypeName( + typeElement(processingEnv, "test.Dto"), context(processingEnv))), + """ + package test; + public class Dto {} + """); + assertEquals("test", result.get().getPackageName()); + assertEquals("Dto", result.get().getClassName()); + } + + @Test + void map2MethodParameter_mapsNameAndListType() { + AtomicReference result = new AtomicReference<>(); + 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 { + private List tags; + public void setTags(List tags) { this.tags = tags; } + } + """); + 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 map2MethodParameter_mapsSetToTypeNameSet() { + AtomicReference result = new AtomicReference<>(); + 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) {} + } + """); + assertInstanceOf(TypeNameSet.class, result.get()); + assertEquals("Integer", ((TypeNameSet) result.get()).getElementType().getClassName()); + } + + @Test + void map2MethodParameter_mapsMapToTypeNameMap() { + AtomicReference result = new AtomicReference<>(); + 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) {} + } + """); + 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<>(); + 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) {} + } + """); + assertInstanceOf(TypeNamePrimitive.class, result.get()); + } + + @Test + void createDerivedTypeName_appendsSuffix() { + AtomicReference result = new AtomicReference<>(); + probe( + (roundEnv, processingEnv) -> + result.set( + JavaLangMapper.createDerivedTypeName( + typeElement(processingEnv, "test.Dto"), context(processingEnv), "Builder")), + """ + package test; + public class Dto {} + """); + 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<>(); + 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 {} + """); + 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<>(); + 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; + import java.util.TreeMap; + public class Dto { + public void setTags(ArrayList tags) {} + public void setLookup(HashMap lookup) {} + public void setSorted(TreeMap sorted) {} + } + """); + 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<>(); + 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) {} + } + """); + assertInstanceOf(TypeNameList.class, result.get()); + assertEquals("Double", ((TypeNameList) result.get()).getElementType().getClassName()); + } + + @Test + void map2GenericParameterDtos_mapsTypeParametersWithBounds() { + AtomicReference> result = new AtomicReference<>(); + probe( + (roundEnv, processingEnv) -> { + TypeElement dto = typeElement(processingEnv, "test.Dto"); + result.set(JavaLangMapper.map2GenericParameterDtos(dto, context(processingEnv))); + }, + """ + package test; + public class Dto {} + """); + 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<>(); + 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) {} + } + """); + 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<>(); + 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) {} + 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) {} + } + """); + 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<>(); + 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) {} + } + """); + 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<>(); + 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) {} + } + """); + 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<>(); + probe( + (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) {} + } + """); + 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/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..d383aedc --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/AnnotationProcessingContextTest.java @@ -0,0 +1,291 @@ +/* + * 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.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 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.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 { + void inherited() {} + } + """; + + @Test + void delegates_elementAndTypeUtilities() { + AtomicReference> results = new AtomicReference<>(); + 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", + "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() { + 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(); + 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"))); + } + + @Test + void currentTask_nullByDefault() { + AtomicReference result = new AtomicReference<>(); + probe( + (roundEnv, env) -> { + AnnotationProcessingContext ctx = context(env); + result.set(ctx.getCurrentTask()); + }, + DTO_SOURCE); + assertNull(result.get()); + } + + @Test + void getElementValuesWithDefaults_includesDefaultsAndSetValues() { + AtomicReference elementsWithDefaults = new AtomicReference<>(); + 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()); + } + + @Test + void isAccessibleFromGeneratedPackage_publicMembersAccessible() { + AtomicReference result = new AtomicReference<>(); + 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<>(); + probe((roundEnv, env) -> tracker.set(context(env).getPerformanceTracker()), DTO_SOURCE); + 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(); + 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", + "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<>(); + probe((roundEnv, env) -> result.set(context(env).getTypeElement((TypeName) null)), DTO_SOURCE); + 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<>(); + 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()); + } + + /** + * {@code performanceTrackingEnabled} switches the context to the real tracker writing the report. + */ + @Test + void performanceTracker_activeWhenEnabled() { + AtomicReference tracker = new AtomicReference<>(); + 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/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/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/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/processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ElementCollectorTest.java similarity index 51% 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 index 0000edad..fb228649 100644 --- a/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 new file mode 100644 index 00000000..a2345289 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/MinimalCodegenProcessorTest.java @@ -0,0 +1,548 @@ +/* + * 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.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; +import org.javahelpers.codegen.analysis.JavaLangMapper; +import org.javahelpers.codegen.enums.AccessModifier; +import org.javahelpers.codegen.enums.FormattingMode; +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.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 + * default are implemented; collection, round-driving, generator and formatter wiring come from + * {@link AbstractCodegenProcessor}. + */ +public class MinimalCodegenProcessorTest { + + /** Marks a type for delegate-builder generation in this test. */ + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.SOURCE) + public @interface GenerateBuilder {} + + /** Analysis result: target type, builder name and the setters to delegate to. */ + record MinimalTargetDefinition( + TypeName sourceTypeName, TypeName builderTypeName, List setters) + implements CodegenDefinition { + @Override + public TypeName getTypeName() { + return sourceTypeName; + } + + @Override + public TypeName targetTypeName() { + return builderTypeName; + } + } + + /** + * 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> { + + 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, + CompilerArgumentsReader reader, + ProcessingLogger logger) { + return new AnnotationProcessingContext(logger, processingEnv); + } + + @Override + protected List> planTasks( + ElementGroups collected, AnnotationProcessingContext ctx) { + return collected.all().stream() + .map( + element -> + CodegenTask.builder(CodegenConfiguration.class) + .element(element) + .outputPackage(ctx.getPackageName(element)) + .build()) + .toList(); + } + + @Override + protected List analyse( + CodegenTask task, AnnotationProcessingContext ctx) { + if (!(task.element() instanceof TypeElement target)) { + return List.of(); + } + return List.of( + new MinimalTargetDefinition( + JavaLangMapper.mapToTypeName(target, ctx), + builderName(target, ctx), + JavaLangAnalyser.findSetterMethods(target, ctx))); + } + + @Override + protected GenerationTargetClassDto mapToTargetSpecification( + MinimalTargetDefinition definition, + CodegenConfiguration configuration, + AnnotationProcessingContext ctx) { + GenerationTargetClassDto target = new GenerationTargetClassDto(); + target.setTypeName(definition.builderTypeName()); + target.setClassAccessModifier(AccessModifier.PUBLIC); + target.setFormattingMode(FormattingMode.NONE); + + ClassFieldDto field = new ClassFieldDto(); + field.setFieldName("target"); + field.setFieldType(definition.sourceTypeName()); + field.setVisibility(AccessModifier.PRIVATE); + field.setLiteralInitializer("new " + definition.sourceTypeName().getClassName() + "()"); + target.addClassField(field); + + for (ExecutableElement setter : definition.setters()) { + String setterName = setter.getSimpleName().toString(); + String methodName = StringUtils.uncapitalize(Strings.CI.removeStart(setterName, "set")); + MethodDto method = new MethodDto(methodName, definition.builderTypeName()); + method.setModifier(AccessModifier.PUBLIC); + String paramName = setter.getParameters().get(0).getSimpleName().toString(); + method.addParameter(JavaLangMapper.map2MethodParameter(setter.getParameters().get(0), ctx)); + method.setCode( + """ + target.$setterName:N($paramName:N); + return this;"""); + method.addArgument("setterName", setterName); + method.addArgument("paramName", paramName); + target.addMethod(method); + } + MethodDto build = new MethodDto("build", definition.sourceTypeName()); + build.setModifier(AccessModifier.PUBLIC); + build.setCode("return target;"); + target.addMethod(build); + return target; + } + + private static TypeName builderName(TypeElement target, AnnotationProcessingContext ctx) { + return new TypeName(ctx.getPackageName(target), target.getSimpleName() + "Builder"); + } + } + + /** 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()); + } + } + + /** + * 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 + JavaFileObject source = + CodegenTestUtils.forSource( + """ + package test; + import org.javahelpers.codegen.processing.MinimalCodegenProcessorTest.GenerateBuilder; + @GenerateBuilder + public class Person { + private String name; + public void setName(String name) { this.name = name; } + } + """); + + // When + Compilation compilation = + CodegenTestUtils.createCompiler(new MinimalProcessor()).compile(source); + + // Then + assertThat(compilation).succeeded(); + String generatedCode = loadGeneratedSource(compilation, "PersonBuilder"); + // The whole expected target as one textblock — pins structure, delegation and the target + // field; whitespace-normalized compare, nothing generated is left unchecked. + 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; + } + }""", + 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()); + } + + /** + * 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"); + 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(); + } +} 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/PipelinePhasesTest.java similarity index 64% rename from processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java rename to simple-processor/src/test/java/org/javahelpers/codegen/processing/PipelinePhasesTest.java index 4f1e2809..4814a262 100644 --- a/processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/PipelinePhasesTest.java @@ -24,25 +24,25 @@ package org.javahelpers.codegen.processing; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.Set; +import java.util.List; import org.junit.jupiter.api.Test; -/** Unit tests for {@link ProcessorOptionRegistry}. */ -class ProcessorOptionRegistryTest { - - private static ProcessorOptionRegistry minimalRegistry() { - return ProcessorOptionRegistry.builder().options(Set.of()).build(); - } - - @Test - void reader_returnsReaderForEnvironment() { - assertNotNull(minimalRegistry().reader(null)); - } +/** Unit tests for {@link PipelinePhases}. */ +class PipelinePhasesTest { @Test - void formatterProfile_withoutConfiguredOption_returnsNull() { - assertNull(minimalRegistry().formatterProfile(new CompilerArgumentsReader(null))); + 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 new file mode 100644 index 00000000..ce9ef3f2 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/ProcessorOptionRegistryTest.java @@ -0,0 +1,102 @@ +/* + * 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.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 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 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 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..100c1db1 --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/processing/logging/MessagerProcessingLoggerTest.java @@ -0,0 +1,222 @@ +/* + * 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.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; + +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.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<>(); + 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()); + assertTrue(diag.message().contains("conflict on name")); + assertEquals("name", diag.element().getSimpleName().toString()); + } + + @Test + void error_attachesElement() { + List diags = new CopyOnWriteArrayList<>(); + Compilation compilation = + 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()); + assertEquals(Diagnostic.Kind.ERROR, diags.get(0).kind()); + assertEquals("Dto", diags.get(0).element().getSimpleName().toString()); + } + + @Test + void verboseWarning_deferLocationAndFlushOncePerType() { + List diags = new CopyOnWriteArrayList<>(); + 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")); + 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<>(); + 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")); + } + + @Test + void loggingPrefix_appliesToMessages() { + List diags = new CopyOnWriteArrayList<>(); + probe( + (roundEnv, env) -> + MessagerProcessingLogger.create(recordingEnv(env, diags), "myproc") + .info("hello %s", "world"), + DTO_SOURCE); + 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(); + } + }; + } +} diff --git a/simple-processor/src/test/java/org/javahelpers/codegen/testing/ProcessingTestUtils.java b/simple-processor/src/test/java/org/javahelpers/codegen/testing/ProcessingTestUtils.java new file mode 100644 index 00000000..9c7bc95c --- /dev/null +++ b/simple-processor/src/test/java/org/javahelpers/codegen/testing/ProcessingTestUtils.java @@ -0,0 +1,87 @@ +/* + * 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 com.google.testing.compile.Compilation; +import java.util.List; +import java.util.function.BiConsumer; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; +import org.javahelpers.codegen.processing.AnnotationProcessingContext; + +/** + * 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() { + // 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); + } + + /** + * 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; + } +}