Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 66 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,45 +138,47 @@ open module my.tests {
```java

@DisplayName("Example tests")
@ExtendWith(JctExtension.class)
class ExampleTest {

@Managed
Workspace workspace;

@DisplayName("I can compile a Hello World application")
@JavacCompilerTest
void canCompileHelloWorld(JctCompiler<?, ?> compiler) {
try (var workspace = Workspaces.newWorkspace()) {
// Given
workspace
.createSourcePathPackage()
.createFile("org/example/Message.java").withContents("""
package org.example;

import lombok.Data;
import lombok.NonNull;

@Data
public class Message {
private String content;

public static void main(String[] args) {
Message message = new Message("Hello, World!");
System.out.println(message);
}
// Given
workspace
.createSourcePathPackage()
.createFile("org/example/Message.java").withContents("""
package org.example;

import lombok.Data;
import lombok.NonNull;

@Data
public class Message {
private String content;

public static void main(String[] args) {
Message message = new Message("Hello, World!");
System.out.println(message);
}
"""
);
}
"""
);

// When
var compilation = compiler.compile(workspace);
// When
var compilation = compiler.compile(workspace);

// Then
assertThatCompilation(compilation)
.isSuccessfulWithoutWarnings();
// Then
assertThatCompilation(compilation)
.isSuccessfulWithoutWarnings();

assertThatCompilation(compilation)
.classOutput().packages()
.fileExists("com/example/Message.class")
.isNotEmptyFile();
}
assertThatCompilation(compilation)
.classOutput().packages()
.fileExists("com/example/Message.class")
.isNotEmptyFile();
}
}
```
Expand All @@ -192,42 +194,44 @@ import io.github.ascopes.jct.workspaces.Workspaces;
import org.example.processor.JsonSchemaAnnotationProcessor;
import org.skyscreamer.jsonassert.JSONAssert;

@ExtendWith(JctExtension.class)
class JsonSchemaAnnotationProcessorTest {

@Managed
Workspace workspace;

@JavacCompilerTest(minVersion = 11, maxVersion = 19)
void theJsonSchemaIsCreatedFromTheInputCode(JctCompiler<?, ?> compiler) {
try (var workspace = Workspaces.newWorkspace()) {
// Given
workspace
.createSourcePathPackage()
.createDirectory("org", "example", "tests")
.copyContentsFrom("src", "test", "resources", "code", "schematest");

// When
var compilation = compiler
.addAnnotationProcessors(new JsonSchemaAnnotationProcessor())
.addAnnotationProcessorOptions("jsonschema.verbose=true")
.failOnWarnings(true)
.showDeprecationWarnings(true)
.compile(workspace);

// Then
assertThatCompilation(compilation)
.isSuccessfulWithoutWarnings();

assertThatCompilation(compilation)
.diagnostics().notes().singleElement()
.message().isEqualTo(
"Creating JSON schema in Java %s for package org.example.tests",
compiler.getRelease()
);

assertThatCompilation(compilation)
.classOutputs().packages()
.fileExists("json-schemas", "UserSchema.json").contents()
.isNotEmpty()
.satisfies(contents -> JSONAssert.assertEquals(...));
}
// Given
workspace
.createSourcePathPackage()
.createDirectory("org", "example", "tests")
.copyContentsFrom("src", "test", "resources", "code", "schematest");

// When
var compilation = compiler
.addAnnotationProcessors(new JsonSchemaAnnotationProcessor())
.addAnnotationProcessorOptions("jsonschema.verbose=true")
.failOnWarnings(true)
.showDeprecationWarnings(true)
.compile(workspace);

// Then
assertThatCompilation(compilation)
.isSuccessfulWithoutWarnings();

assertThatCompilation(compilation)
.diagnostics().notes().singleElement()
.message().isEqualTo(
"Creating JSON schema in Java %s for package org.example.tests",
compiler.getRelease()
);

assertThatCompilation(compilation)
.classOutputs().packages()
.fileExists("json-schemas", "UserSchema.json").contents()
.isNotEmpty()
.satisfies(contents -> JSONAssert.assertEquals(...));
}
}
```
Expand Down
24 changes: 24 additions & 0 deletions acceptance-tests/acceptance-tests-dogfood/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,30 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-testkit</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
requires transitive org.junit.jupiter.api;
requires transitive org.junit.jupiter.engine;
requires transitive org.junit.jupiter.params;
requires transitive org.junit.platform.commons; // required to make IntelliJ happy.
requires transitive org.junit.platform.engine; // required to make IntelliJ happy.
requires transitive org.junit.platform.commons; // required to make IntelliJ happy.
requires transitive org.junit.platform.engine; // required to make IntelliJ happy.
requires transitive org.junit.platform.launcher; // required to make IntelliJ happy.
}
7 changes: 7 additions & 0 deletions java-compiler-testing/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-testkit</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
Expand Down Expand Up @@ -138,6 +144,7 @@
<excludePackageNames>
io.github.ascopes.jct.compilers.javac;
io.github.ascopes.jct.**.impl;
io.github.ascopes.jct.junit.ext;
io.github.ascopes.jct.utils;
</excludePackageNames>
</configuration>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*
* Copyright (C) 2022 - 2023, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.ascopes.jct.junit;

import io.github.ascopes.jct.workspaces.Workspace;
import io.github.ascopes.jct.workspaces.Workspaces;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.apiguardian.api.API;
import org.apiguardian.api.API.Status;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Implicit extension that will manage the lifecycle of {@link Managed}-annotated {@link Workspace}
* fields within JUnit5 test classes.
*
* @author Ashley Scopes
* @since 0.4.0
*/
@API(since = "0.4.0", status = Status.STABLE)
public final class JctExtension implements
Extension, BeforeEachCallback, BeforeAllCallback, AfterEachCallback, AfterAllCallback {

private static final Logger LOGGER = LoggerFactory.getLogger(JctExtension.class);

@Override
public void beforeAll(ExtensionContext context) throws Exception {
for (var field : getManagedStaticWorkspaceFields(context.getRequiredTestClass())) {
initWorkspaceForField(field, null);
}
}

@Override
public void beforeEach(ExtensionContext context) throws Exception {
for (var instance : context.getRequiredTestInstances().getAllInstances()) {
for (var field : getManagedInstanceWorkspaceFields(instance.getClass())) {
initWorkspaceForField(field, instance);
}
}
}

@Override
public void afterAll(ExtensionContext context) throws Exception {
for (var field : getManagedStaticWorkspaceFields(context.getRequiredTestClass())) {
closeWorkspaceForField(field, null);
}
}

@Override
public void afterEach(ExtensionContext context) throws Exception {
for (var instance : context.getRequiredTestInstances().getAllInstances()) {
for (var field : getManagedInstanceWorkspaceFields(instance.getClass())) {
closeWorkspaceForField(field, instance);
}
}
}

private List<Field> getManagedStaticWorkspaceFields(Class<?> clazz) {
// Do not recurse for static fields, as the state of any parent classes may be shared
// with other classes running in parallel. Need to look up how JUnit expects us to handle that
// case, if at all.

var fields = new ArrayList<Field>();

for (var field : clazz.getDeclaredFields()) {
if (isWorkspaceField(field) && Modifier.isStatic(field.getModifiers())) {
fields.add(field);
}
}

return fields;
}

private List<Field> getManagedInstanceWorkspaceFields(Class<?> clazz) {
// For instances, discover all the fields recursively in superclasses as well that are
// non-static.

var fields = new ArrayList<Field>();

while (clazz != null) {
for (var field : clazz.getDeclaredFields()) {
if (isWorkspaceField(field) && !Modifier.isStatic(field.getModifiers())) {
fields.add(field);
}
}
clazz = clazz.getSuperclass();
}

return fields;
}

private boolean isWorkspaceField(Field field) {
return field.getType().equals(Workspace.class)
&& field.isAnnotationPresent(Managed.class);
}

private void initWorkspaceForField(Field field, @Nullable Object instance) throws Exception {
LOGGER
.atTrace()
.setMessage("Initialising workspace for field in {}: {} {} on instance {}")
.addArgument(() -> field.getDeclaringClass().getSimpleName())
.addArgument(() -> field.getType().getSimpleName())
.addArgument(field::getName)
.addArgument(instance)
.log();

field.setAccessible(true);
var managedWorkspace = field.getAnnotation(Managed.class);
var workspace = Workspaces.newWorkspace(managedWorkspace.pathStrategy());
field.set(instance, workspace);
}

private void closeWorkspaceForField(Field field, @Nullable Object instance) throws Exception {
LOGGER
.atTrace()
.setMessage("Closing workspace for field in {}: {} {} on instance {}")
.addArgument(() -> field.getDeclaringClass().getSimpleName())
.addArgument(() -> field.getType().getSimpleName())
.addArgument(field::getName)
.addArgument(instance)
.log();

field.setAccessible(true);
((Workspace) field.get(instance)).close();
}
}
Loading