diff --git a/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java index 208fd63e8f..38c5a5c33d 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java @@ -72,8 +72,9 @@ class AsciidoctorConventions { makeAllWarningsFatal(project); upgradeAsciidoctorJVersion(project); createAsciidoctorExtensionsConfiguration(project); - project.getTasks().withType(AbstractAsciidoctorTask.class, - (asciidoctorTask) -> configureAsciidoctorTask(project, asciidoctorTask)); + project.getTasks() + .withType(AbstractAsciidoctorTask.class, + (asciidoctorTask) -> configureAsciidoctorTask(project, asciidoctorTask)); }); } @@ -87,12 +88,14 @@ class AsciidoctorConventions { private void createAsciidoctorExtensionsConfiguration(Project project) { project.getConfigurations().create(EXTENSIONS_CONFIGURATION_NAME, (configuration) -> { - project.getConfigurations().matching((candidate) -> "dependencyManagement".equals(candidate.getName())) - .all(configuration::extendsFrom); - configuration.getDependencies().add(project.getDependencies() + project.getConfigurations() + .matching((candidate) -> "dependencyManagement".equals(candidate.getName())) + .all(configuration::extendsFrom); + configuration.getDependencies() + .add(project.getDependencies() .create("io.spring.asciidoctor.backends:spring-asciidoctor-backends:0.0.4")); configuration.getDependencies() - .add(project.getDependencies().create("org.asciidoctor:asciidoctorj-pdf:1.5.3")); + .add(project.getDependencies().create("org.asciidoctor:asciidoctorj-pdf:1.5.3")); }); } @@ -140,13 +143,15 @@ class AsciidoctorConventions { private Sync createSyncDocumentationSourceTask(Project project, AbstractAsciidoctorTask asciidoctorTask) { Sync syncDocumentationSource = project.getTasks() - .create("syncDocumentationSourceFor" + StringUtils.capitalize(asciidoctorTask.getName()), Sync.class); + .create("syncDocumentationSourceFor" + StringUtils.capitalize(asciidoctorTask.getName()), Sync.class); File syncedSource = new File(project.getBuildDir(), "docs/src/" + asciidoctorTask.getName()); syncDocumentationSource.setDestinationDir(syncedSource); syncDocumentationSource.from("src/docs/"); asciidoctorTask.dependsOn(syncDocumentationSource); - asciidoctorTask.getInputs().dir(syncedSource).withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("synced source"); + asciidoctorTask.getInputs() + .dir(syncedSource) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("synced source"); asciidoctorTask.setSourceDir(project.relativePath(new File(syncedSource, "asciidoc/"))); return syncDocumentationSource; } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java index e3afc9f2e9..e2aae45f80 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/DeployedPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,12 +46,16 @@ public class DeployedPlugin implements Plugin { MavenPublication mavenPublication = publishing.getPublications().create("maven", MavenPublication.class); project.afterEvaluate((evaluated) -> project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> { if (((Jar) project.getTasks().getByName(JavaPlugin.JAR_TASK_NAME)).isEnabled()) { - project.getComponents().matching((component) -> component.getName().equals("java")) - .all(mavenPublication::from); + project.getComponents() + .matching((component) -> component.getName().equals("java")) + .all(mavenPublication::from); } })); - project.getPlugins().withType(JavaPlatformPlugin.class).all((javaPlugin) -> project.getComponents() - .matching((component) -> component.getName().equals("javaPlatform")).all(mavenPublication::from)); + project.getPlugins() + .withType(JavaPlatformPlugin.class) + .all((javaPlugin) -> project.getComponents() + .matching((component) -> component.getName().equals("javaPlatform")) + .all(mavenPublication::from)); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java index 01050c03aa..43ff4e8826 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/JavaConventions.java @@ -121,16 +121,18 @@ class JavaConventions { } private void configureJarManifestConventions(Project project) { - ExtractResources extractLegalResources = project.getTasks().create("extractLegalResources", - ExtractResources.class); + ExtractResources extractLegalResources = project.getTasks() + .create("extractLegalResources", ExtractResources.class); extractLegalResources.getDestinationDirectory().set(project.getLayout().getBuildDirectory().dir("legal")); extractLegalResources.setResourcesNames(Arrays.asList("LICENSE.txt", "NOTICE.txt")); extractLegalResources.property("version", project.getVersion().toString()); SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class); - Set sourceJarTaskNames = sourceSets.stream().map(SourceSet::getSourcesJarTaskName) - .collect(Collectors.toSet()); - Set javadocJarTaskNames = sourceSets.stream().map(SourceSet::getJavadocJarTaskName) - .collect(Collectors.toSet()); + Set sourceJarTaskNames = sourceSets.stream() + .map(SourceSet::getSourcesJarTaskName) + .collect(Collectors.toSet()); + Set javadocJarTaskNames = sourceSets.stream() + .map(SourceSet::getJavadocJarTaskName) + .collect(Collectors.toSet()); project.getTasks().withType(Jar.class, (jar) -> project.afterEvaluate((evaluated) -> { jar.metaInf((metaInf) -> metaInf.from(extractLegalResources)); jar.manifest((manifest) -> { @@ -167,7 +169,8 @@ class JavaConventions { testRetry.getFailOnPassedAfterRetry().set(true); testRetry.getMaxRetries().set(isCi() ? 3 : 0); }); - project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> project.getDependencies() + project.getPlugins() + .withType(JavaPlugin.class, (javaPlugin) -> project.getDependencies() .add(JavaPlugin.TEST_RUNTIME_ONLY_CONFIGURATION_NAME, "org.junit.platform:junit-platform-launcher")); } @@ -220,7 +223,7 @@ class JavaConventions { String version = SpringJavaFormatPlugin.class.getPackage().getImplementationVersion(); DependencySet checkstyleDependencies = project.getConfigurations().getByName("checkstyle").getDependencies(); checkstyleDependencies - .add(project.getDependencies().create("io.spring.javaformat:spring-javaformat-checkstyle:" + version)); + .add(project.getDependencies().create("io.spring.javaformat:spring-javaformat-checkstyle:" + version)); } private void configureDependencyManagement(Project project) { @@ -231,14 +234,18 @@ class JavaConventions { configuration.setCanBeResolved(false); }); configurations - .matching((configuration) -> configuration.getName().endsWith("Classpath") - || JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME.equals(configuration.getName())) - .all((configuration) -> configuration.extendsFrom(dependencyManagement)); - Dependency springBootParent = project.getDependencies().enforcedPlatform(project.getDependencies() + .matching((configuration) -> configuration.getName().endsWith("Classpath") + || JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME.equals(configuration.getName())) + .all((configuration) -> configuration.extendsFrom(dependencyManagement)); + Dependency springBootParent = project.getDependencies() + .enforcedPlatform(project.getDependencies() .project(Collections.singletonMap("path", ":spring-boot-project:spring-boot-parent"))); dependencyManagement.getDependencies().add(springBootParent); - project.getPlugins().withType(OptionalDependenciesPlugin.class, (optionalDependencies) -> configurations - .getByName(OptionalDependenciesPlugin.OPTIONAL_CONFIGURATION_NAME).extendsFrom(dependencyManagement)); + project.getPlugins() + .withType(OptionalDependenciesPlugin.class, + (optionalDependencies) -> configurations + .getByName(OptionalDependenciesPlugin.OPTIONAL_CONFIGURATION_NAME) + .extendsFrom(dependencyManagement)); } private void configureToolchain(Project project) { @@ -260,9 +267,9 @@ class JavaConventions { } private void createProhibitedDependenciesCheck(Configuration classpath, Project project) { - CheckClasspathForProhibitedDependencies checkClasspathForProhibitedDependencies = project.getTasks().create( - "check" + StringUtils.capitalize(classpath.getName() + "ForProhibitedDependencies"), - CheckClasspathForProhibitedDependencies.class); + CheckClasspathForProhibitedDependencies checkClasspathForProhibitedDependencies = project.getTasks() + .create("check" + StringUtils.capitalize(classpath.getName() + "ForProhibitedDependencies"), + CheckClasspathForProhibitedDependencies.class); checkClasspathForProhibitedDependencies.setClasspath(classpath); project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(checkClasspathForProhibitedDependencies); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java index 901a5678d7..c5e896160b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/KotlinConventions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,8 +44,9 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile; class KotlinConventions { void apply(Project project) { - project.getPlugins().withId("org.jetbrains.kotlin.jvm", - (plugin) -> project.getTasks().withType(KotlinCompile.class, this::configure)); + project.getPlugins() + .withId("org.jetbrains.kotlin.jvm", + (plugin) -> project.getTasks().withType(KotlinCompile.class, this::configure)); } private void configure(KotlinCompile compile) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java index 7ff8d9fb93..fc1f5cb357 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/MavenPublishingConventions.java @@ -67,8 +67,9 @@ class MavenPublishingConventions { mavenRepository.setName("deployment"); }); } - publishing.getPublications().withType(MavenPublication.class) - .all((mavenPublication) -> customizeMavenPublication(mavenPublication, project)); + publishing.getPublications() + .withType(MavenPublication.class) + .all((mavenPublication) -> customizeMavenPublication(mavenPublication, project)); project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> { JavaPluginExtension extension = project.getExtensions().getByType(JavaPluginExtension.class); extension.withJavadocJar(); @@ -79,8 +80,9 @@ class MavenPublishingConventions { private void customizeMavenPublication(MavenPublication publication, Project project) { customizePom(publication.getPom(), project); - project.getPlugins().withType(JavaPlugin.class) - .all((javaPlugin) -> customizeJavaMavenPublication(publication, project)); + project.getPlugins() + .withType(JavaPlugin.class) + .all((javaPlugin) -> customizeJavaMavenPublication(publication, project)); suppressMavenOptionalFeatureWarnings(publication); } @@ -102,7 +104,7 @@ class MavenPublishingConventions { private void customizeJavaMavenPublication(MavenPublication publication, Project project) { addMavenOptionalFeature(project); publication.versionMapping((strategy) -> strategy.usage(Usage.JAVA_API, (mappingStrategy) -> mappingStrategy - .fromResolutionOf(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))); + .fromResolutionOf(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))); publication.versionMapping( (strategy) -> strategy.usage(Usage.JAVA_RUNTIME, VariantVersionMappingStrategy::fromResolutionResult)); } @@ -117,7 +119,7 @@ class MavenPublishingConventions { extension.registerFeature("mavenOptional", (feature) -> feature.usingSourceSet(extension.getSourceSets().getByName("main"))); AdhocComponentWithVariants javaComponent = (AdhocComponentWithVariants) project.getComponents() - .findByName("java"); + .findByName("java"); javaComponent.addVariantsFromConfiguration( project.getConfigurations().findByName("mavenOptionalRuntimeElements"), ConfigurationVariantDetails::mapToOptional); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java index d7fcbfdcbc..915c3448e4 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/MavenRepositoryPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -61,36 +61,45 @@ public class MavenRepositoryPlugin implements Plugin { mavenRepository.setName("project"); mavenRepository.setUrl(repositoryLocation.toURI()); }); - project.getTasks().matching((task) -> task.getName().equals(PUBLISH_TO_PROJECT_REPOSITORY_TASK_NAME)) - .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); - project.getTasks().matching((task) -> task.getName().equals("publishPluginMavenPublicationToProjectRepository")) - .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); + project.getTasks() + .matching((task) -> task.getName().equals(PUBLISH_TO_PROJECT_REPOSITORY_TASK_NAME)) + .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); + project.getTasks() + .matching((task) -> task.getName().equals("publishPluginMavenPublicationToProjectRepository")) + .all((task) -> setUpProjectRepository(project, task, repositoryLocation)); } private void setUpProjectRepository(Project project, Task publishTask, File repositoryLocation) { publishTask.doFirst(new CleanAction(repositoryLocation)); Configuration projectRepository = project.getConfigurations().create(MAVEN_REPOSITORY_CONFIGURATION_NAME); - project.getArtifacts().add(projectRepository.getName(), repositoryLocation, - (artifact) -> artifact.builtBy(publishTask)); + project.getArtifacts() + .add(projectRepository.getName(), repositoryLocation, (artifact) -> artifact.builtBy(publishTask)); DependencySet target = projectRepository.getDependencies(); - project.getPlugins().withType(JavaPlugin.class).all((javaPlugin) -> addMavenRepositoryDependencies(project, - JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, target)); - project.getPlugins().withType(JavaLibraryPlugin.class) - .all((javaLibraryPlugin) -> addMavenRepositoryDependencies(project, JavaPlugin.API_CONFIGURATION_NAME, - target)); - project.getPlugins().withType(JavaPlatformPlugin.class) - .all((javaPlugin) -> addMavenRepositoryDependencies(project, JavaPlatformPlugin.API_CONFIGURATION_NAME, - target)); + project.getPlugins() + .withType(JavaPlugin.class) + .all((javaPlugin) -> addMavenRepositoryDependencies(project, JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, + target)); + project.getPlugins() + .withType(JavaLibraryPlugin.class) + .all((javaLibraryPlugin) -> addMavenRepositoryDependencies(project, JavaPlugin.API_CONFIGURATION_NAME, + target)); + project.getPlugins() + .withType(JavaPlatformPlugin.class) + .all((javaPlugin) -> addMavenRepositoryDependencies(project, JavaPlatformPlugin.API_CONFIGURATION_NAME, + target)); } private void addMavenRepositoryDependencies(Project project, String sourceConfigurationName, DependencySet target) { - project.getConfigurations().getByName(sourceConfigurationName).getDependencies() - .withType(ProjectDependency.class).all((dependency) -> { - Map dependencyDescriptor = new HashMap<>(); - dependencyDescriptor.put("path", dependency.getDependencyProject().getPath()); - dependencyDescriptor.put("configuration", MAVEN_REPOSITORY_CONFIGURATION_NAME); - target.add(project.getDependencies().project(dependencyDescriptor)); - }); + project.getConfigurations() + .getByName(sourceConfigurationName) + .getDependencies() + .withType(ProjectDependency.class) + .all((dependency) -> { + Map dependencyDescriptor = new HashMap<>(); + dependencyDescriptor.put("path", dependency.getDependencyProject().getPath()); + dependencyDescriptor.put("configuration", MAVEN_REPOSITORY_CONFIGURATION_NAME); + target.add(project.getDependencies().project(dependencyDescriptor)); + }); } private static final class CleanAction implements Action { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java b/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java index 9d274b8115..5a863d221a 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/SyncAppSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2021-2021 the original author or authors. + * Copyright 2021-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. @@ -44,7 +44,7 @@ public class SyncAppSource extends DefaultTask { this.sourceDirectory = objects.directoryProperty(); this.destinationDirectory = objects.directoryProperty(); this.pluginVersion = objects.property(String.class) - .convention(getProject().provider(() -> getProject().getVersion().toString())); + .convention(getProject().provider(() -> getProject().getVersion().toString())); } @TaskAction diff --git a/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java index dbb2842d54..c95c433572 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitecturePlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,14 +46,14 @@ public class ArchitecturePlugin implements Plugin { JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class); List> packageTangleChecks = new ArrayList<>(); for (SourceSet sourceSet : javaPluginExtension.getSourceSets()) { - TaskProvider checkPackageTangles = project.getTasks().register( - "checkForPackageTangles" + StringUtils.capitalize(sourceSet.getName()), PackageTangleCheck.class, - (task) -> { - task.setClasses(sourceSet.getOutput().getClassesDirs()); - task.setDescription("Checks the classes of the " + sourceSet.getName() - + " source set for package tangles."); - task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); - }); + TaskProvider checkPackageTangles = project.getTasks() + .register("checkForPackageTangles" + StringUtils.capitalize(sourceSet.getName()), + PackageTangleCheck.class, (task) -> { + task.setClasses(sourceSet.getOutput().getClassesDirs()); + task.setDescription("Checks the classes of the " + sourceSet.getName() + + " source set for package tangles."); + task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); + }); packageTangleChecks.add(checkPackageTangles); } if (!packageTangleChecks.isEmpty()) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java b/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java index 5cca955435..f416c6344b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/architecture/PackageTangleCheck.java @@ -61,7 +61,7 @@ public abstract class PackageTangleCheck extends DefaultTask { @TaskAction void checkForPackageTangles() throws IOException { JavaClasses javaClasses = new ClassFileImporter() - .importPaths(this.classes.getFiles().stream().map(File::toPath).collect(Collectors.toList())); + .importPaths(this.classes.getFiles().stream().map(File::toPath).collect(Collectors.toList())); SliceRule freeOfCycles = SlicesRuleDefinition.slices().matching("(**)").should().beFreeOfCycles(); EvaluationResult result = freeOfCycles.evaluate(javaClasses); File outputFile = getOutputDirectory().file("failure-report.txt").get().getAsFile(); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java index 02275a6baf..4f65e0ec71 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,14 +58,14 @@ public class AutoConfigurationMetadata extends DefaultTask { public AutoConfigurationMetadata() { getInputs() - .file((Callable) () -> new File(this.sourceSet.getOutput().getResourcesDir(), - "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports")) - .withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("org.springframework.boot.autoconfigure.AutoConfiguration"); + .file((Callable) () -> new File(this.sourceSet.getOutput().getResourcesDir(), + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports")) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("org.springframework.boot.autoconfigure.AutoConfiguration"); dependsOn((Callable) () -> this.sourceSet.getProcessResourcesTaskName()); getProject().getConfigurations() - .maybeCreate(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME); + .maybeCreate(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME); } public void setSourceSet(SourceSet sourceSet) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java index 52e081d270..f3e751e48b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,21 +58,27 @@ public class AutoConfigurationPlugin implements Plugin { project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> { project.getPlugins().apply(ConfigurationPropertiesPlugin.class); Configuration annotationProcessors = project.getConfigurations() - .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); + .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); annotationProcessors.getDependencies() - .add(project.getDependencies().project(Collections.singletonMap("path", + .add(project.getDependencies() + .project(Collections.singletonMap("path", ":spring-boot-project:spring-boot-tools:spring-boot-autoconfigure-processor"))); annotationProcessors.getDependencies() - .add(project.getDependencies().project(Collections.singletonMap("path", + .add(project.getDependencies() + .project(Collections.singletonMap("path", ":spring-boot-project:spring-boot-tools:spring-boot-configuration-processor"))); project.getTasks().create("autoConfigurationMetadata", AutoConfigurationMetadata.class, (task) -> { - SourceSet main = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet main = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); task.setSourceSet(main); task.dependsOn(main.getClassesTaskName()); task.setOutputFile(new File(project.getBuildDir(), "auto-configuration-metadata.properties")); - project.getArtifacts().add(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME, - project.provider((Callable) task::getOutputFile), (artifact) -> artifact.builtBy(task)); + project.getArtifacts() + .add(AutoConfigurationPlugin.AUTO_CONFIGURATION_METADATA_CONFIGURATION_NAME, + project.provider((Callable) task::getOutputFile), + (artifact) -> artifact.builtBy(task)); }); }); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java index 0521a12e67..bc723493dd 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java @@ -125,39 +125,41 @@ public class BomExtension { public void effectiveBomArtifact() { Configuration effectiveBomConfiguration = this.project.getConfigurations().create("effectiveBom"); - this.project.getTasks().matching((task) -> task.getName().equals(DeployedPlugin.GENERATE_POM_TASK_NAME)) - .all((task) -> { - Sync syncBom = this.project.getTasks().create("syncBom", Sync.class); - syncBom.dependsOn(task); - File generatedBomDir = new File(this.project.getBuildDir(), "generated/bom"); - syncBom.setDestinationDir(generatedBomDir); - syncBom.from(((GenerateMavenPom) task).getDestination(), (pom) -> pom.rename((name) -> "pom.xml")); - try { - String settingsXmlContent = FileCopyUtils - .copyToString(new InputStreamReader( - getClass().getClassLoader().getResourceAsStream("effective-bom-settings.xml"), - StandardCharsets.UTF_8)) - .replace("localRepositoryPath", - new File(this.project.getBuildDir(), "local-m2-repository").getAbsolutePath()); - syncBom.from(this.project.getResources().getText().fromString(settingsXmlContent), - (settingsXml) -> settingsXml.rename((name) -> "settings.xml")); - } - catch (IOException ex) { - throw new GradleException("Failed to prepare settings.xml", ex); - } - MavenExec generateEffectiveBom = this.project.getTasks().create("generateEffectiveBom", - MavenExec.class); - generateEffectiveBom.setProjectDir(generatedBomDir); - File effectiveBom = new File(this.project.getBuildDir(), - "generated/effective-bom/" + this.project.getName() + "-effective-bom.xml"); - generateEffectiveBom.args("--settings", "settings.xml", "help:effective-pom", - "-Doutput=" + effectiveBom); - generateEffectiveBom.dependsOn(syncBom); - generateEffectiveBom.getOutputs().file(effectiveBom); - generateEffectiveBom.doLast(new StripUnrepeatableOutputAction(effectiveBom)); - this.project.getArtifacts().add(effectiveBomConfiguration.getName(), effectiveBom, + this.project.getTasks() + .matching((task) -> task.getName().equals(DeployedPlugin.GENERATE_POM_TASK_NAME)) + .all((task) -> { + Sync syncBom = this.project.getTasks().create("syncBom", Sync.class); + syncBom.dependsOn(task); + File generatedBomDir = new File(this.project.getBuildDir(), "generated/bom"); + syncBom.setDestinationDir(generatedBomDir); + syncBom.from(((GenerateMavenPom) task).getDestination(), (pom) -> pom.rename((name) -> "pom.xml")); + try { + String settingsXmlContent = FileCopyUtils + .copyToString(new InputStreamReader( + getClass().getClassLoader().getResourceAsStream("effective-bom-settings.xml"), + StandardCharsets.UTF_8)) + .replace("localRepositoryPath", + new File(this.project.getBuildDir(), "local-m2-repository").getAbsolutePath()); + syncBom.from(this.project.getResources().getText().fromString(settingsXmlContent), + (settingsXml) -> settingsXml.rename((name) -> "settings.xml")); + } + catch (IOException ex) { + throw new GradleException("Failed to prepare settings.xml", ex); + } + MavenExec generateEffectiveBom = this.project.getTasks() + .create("generateEffectiveBom", MavenExec.class); + generateEffectiveBom.setProjectDir(generatedBomDir); + File effectiveBom = new File(this.project.getBuildDir(), + "generated/effective-bom/" + this.project.getName() + "-effective-bom.xml"); + generateEffectiveBom.args("--settings", "settings.xml", "help:effective-pom", + "-Doutput=" + effectiveBom); + generateEffectiveBom.dependsOn(syncBom); + generateEffectiveBom.getOutputs().file(effectiveBom); + generateEffectiveBom.doLast(new StripUnrepeatableOutputAction(effectiveBom)); + this.project.getArtifacts() + .add(effectiveBomConfiguration.getName(), effectiveBom, (artifact) -> artifact.builtBy(generateEffectiveBom)); - }); + }); } private String createDependencyNotation(String groupId, String artifactId, DependencyVersion version) { @@ -196,8 +198,9 @@ public class BomExtension { for (Group group : library.getGroups()) { for (Module module : group.getModules()) { putArtifactVersionProperty(group.getId(), module.getName(), module.getClassifier(), versionProperty); - this.dependencyHandler.getConstraints().add(JavaPlatformPlugin.API_CONFIGURATION_NAME, - createDependencyNotation(group.getId(), module.getName(), library.getVersion().getVersion())); + this.dependencyHandler.getConstraints() + .add(JavaPlatformPlugin.API_CONFIGURATION_NAME, createDependencyNotation(group.getId(), + module.getName(), library.getVersion().getVersion())); } for (String bomImport : group.getBoms()) { putArtifactVersionProperty(group.getId(), bomImport, versionProperty); @@ -242,7 +245,7 @@ public class BomExtension { GroupHandler groupHandler = new GroupHandler(id); action.execute(groupHandler); this.groups - .add(new Group(groupHandler.id, groupHandler.modules, groupHandler.plugins, groupHandler.imports)); + .add(new Group(groupHandler.id, groupHandler.modules, groupHandler.plugins, groupHandler.imports)); } public void prohibit(Action action) { @@ -254,7 +257,7 @@ public class BomExtension { public void dependencyVersions(Action action) { DependencyVersionsHandler dependencyVersionsHandler = this.objectFactory - .newInstance(DependencyVersionsHandler.class, this.version); + .newInstance(DependencyVersionsHandler.class, this.version); action.execute(dependencyVersionsHandler); this.dependencyVersions = dependencyVersionsHandler.dependencyVersions; } @@ -336,8 +339,8 @@ public class BomExtension { public void setModules(List modules) { this.modules = modules.stream() - .map((input) -> (input instanceof Module module) ? module : new Module((String) input)) - .toList(); + .map((input) -> (input instanceof Module module) ? module : new Module((String) input)) + .toList(); } public void setImports(List imports) { @@ -530,8 +533,9 @@ public class BomExtension { org.w3c.dom.Node reporting = (org.w3c.dom.Node) xpath.evaluate("/project/reporting", document, XPathConstants.NODE); reporting.getParentNode().removeChild(reporting); - TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), - new StreamResult(this.effectiveBom)); + TransformerFactory.newInstance() + .newTransformer() + .transform(new DOMSource(document), new StreamResult(this.effectiveBom)); } catch (Exception ex) { throw new TaskExecutionException(task, ex); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java index 4fffec4562..d6db769e46 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java @@ -60,8 +60,8 @@ public class BomPlugin implements Plugin { JavaPlatformExtension javaPlatform = project.getExtensions().getByType(JavaPlatformExtension.class); javaPlatform.allowDependencies(); createApiEnforcedConfiguration(project); - BomExtension bom = project.getExtensions().create("bom", BomExtension.class, project.getDependencies(), - project); + BomExtension bom = project.getExtensions() + .create("bom", BomExtension.class, project.getDependencies(), project); project.getTasks().create("bomrCheck", CheckBom.class, bom); project.getTasks().create("bomrUpgrade", UpgradeBom.class, bom); project.getTasks().create("moveToSnapshots", MoveToSnapshots.class, bom); @@ -70,16 +70,18 @@ public class BomPlugin implements Plugin { } private void createApiEnforcedConfiguration(Project project) { - Configuration apiEnforced = project.getConfigurations().create(API_ENFORCED_CONFIGURATION_NAME, - (configuration) -> { - configuration.setCanBeConsumed(false); - configuration.setCanBeResolved(false); - configuration.setVisible(false); - }); - project.getConfigurations().getByName(JavaPlatformPlugin.ENFORCED_API_ELEMENTS_CONFIGURATION_NAME) - .extendsFrom(apiEnforced); - project.getConfigurations().getByName(JavaPlatformPlugin.ENFORCED_RUNTIME_ELEMENTS_CONFIGURATION_NAME) - .extendsFrom(apiEnforced); + Configuration apiEnforced = project.getConfigurations() + .create(API_ENFORCED_CONFIGURATION_NAME, (configuration) -> { + configuration.setCanBeConsumed(false); + configuration.setCanBeResolved(false); + configuration.setVisible(false); + }); + project.getConfigurations() + .getByName(JavaPlatformPlugin.ENFORCED_API_ELEMENTS_CONFIGURATION_NAME) + .extendsFrom(apiEnforced); + project.getConfigurations() + .getByName(JavaPlatformPlugin.ENFORCED_RUNTIME_ELEMENTS_CONFIGURATION_NAME) + .extendsFrom(apiEnforced); } private static final class PublishingCustomizer { @@ -155,16 +157,19 @@ public class BomPlugin implements Plugin { for (Node dependency : findChildren(dependencies, "dependency")) { String groupId = findChild(dependency, "groupId").text(); String artifactId = findChild(dependency, "artifactId").text(); - this.bom.getLibraries().stream().flatMap((library) -> library.getGroups().stream()) - .filter((group) -> group.getId().equals(groupId)) - .flatMap((group) -> group.getModules().stream()) - .filter((module) -> module.getName().equals(artifactId)) - .flatMap((module) -> module.getExclusions().stream()).forEach((exclusion) -> { - Node exclusions = findOrCreateNode(dependency, "exclusions"); - Node node = new Node(exclusions, "exclusion"); - node.appendNode("groupId", exclusion.getGroupId()); - node.appendNode("artifactId", exclusion.getArtifactId()); - }); + this.bom.getLibraries() + .stream() + .flatMap((library) -> library.getGroups().stream()) + .filter((group) -> group.getId().equals(groupId)) + .flatMap((group) -> group.getModules().stream()) + .filter((module) -> module.getName().equals(artifactId)) + .flatMap((module) -> module.getExclusions().stream()) + .forEach((exclusion) -> { + Node exclusions = findOrCreateNode(dependency, "exclusions"); + Node node = new Node(exclusions, "exclusion"); + node.appendNode("groupId", exclusion.getGroupId()); + node.appendNode("artifactId", exclusion.getArtifactId()); + }); } } } @@ -175,12 +180,15 @@ public class BomPlugin implements Plugin { for (Node dependency : findChildren(dependencies, "dependency")) { String groupId = findChild(dependency, "groupId").text(); String artifactId = findChild(dependency, "artifactId").text(); - Set types = this.bom.getLibraries().stream() - .flatMap((library) -> library.getGroups().stream()) - .filter((group) -> group.getId().equals(groupId)) - .flatMap((group) -> group.getModules().stream()) - .filter((module) -> module.getName().equals(artifactId)).map(Module::getType) - .filter(Objects::nonNull).collect(Collectors.toSet()); + Set types = this.bom.getLibraries() + .stream() + .flatMap((library) -> library.getGroups().stream()) + .filter((group) -> group.getId().equals(groupId)) + .flatMap((group) -> group.getModules().stream()) + .filter((module) -> module.getName().equals(artifactId)) + .map(Module::getType) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); if (types.size() > 1) { throw new IllegalStateException( "Multiple types for " + groupId + ":" + artifactId + ": " + types); @@ -201,12 +209,15 @@ public class BomPlugin implements Plugin { String groupId = findChild(dependency, "groupId").text(); String artifactId = findChild(dependency, "artifactId").text(); String version = findChild(dependency, "version").text(); - Set classifiers = this.bom.getLibraries().stream() - .flatMap((library) -> library.getGroups().stream()) - .filter((group) -> group.getId().equals(groupId)) - .flatMap((group) -> group.getModules().stream()) - .filter((module) -> module.getName().equals(artifactId)).map(Module::getClassifier) - .filter(Objects::nonNull).collect(Collectors.toSet()); + Set classifiers = this.bom.getLibraries() + .stream() + .flatMap((library) -> library.getGroups().stream()) + .filter((group) -> group.getId().equals(groupId)) + .flatMap((group) -> group.getModules().stream()) + .filter((module) -> module.getName().equals(artifactId)) + .map(Module::getClassifier) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); Node target = dependency; for (String classifier : classifiers) { if (classifier.length() > 0) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java index 410aebb09d..3aeaf0161b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/CheckBom.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -59,14 +59,18 @@ public class CheckBom extends DefaultTask { private void checkExclusions(String groupId, Module module, DependencyVersion version) { Set resolved = getProject().getConfigurations() - .detachedConfiguration( - getProject().getDependencies().create(groupId + ":" + module.getName() + ":" + version)) - .getResolvedConfiguration().getResolvedArtifacts().stream() - .map((artifact) -> artifact.getModuleVersion().getId()) - .map((id) -> id.getGroup() + ":" + id.getModule().getName()).collect(Collectors.toSet()); - Set exclusions = module.getExclusions().stream() - .map((exclusion) -> exclusion.getGroupId() + ":" + exclusion.getArtifactId()) - .collect(Collectors.toSet()); + .detachedConfiguration( + getProject().getDependencies().create(groupId + ":" + module.getName() + ":" + version)) + .getResolvedConfiguration() + .getResolvedArtifacts() + .stream() + .map((artifact) -> artifact.getModuleVersion().getId()) + .map((id) -> id.getGroup() + ":" + id.getModule().getName()) + .collect(Collectors.toSet()); + Set exclusions = module.getExclusions() + .stream() + .map((exclusion) -> exclusion.getGroupId() + ":" + exclusion.getArtifactId()) + .collect(Collectors.toSet()); Set unused = new TreeSet<>(); for (String exclusion : exclusions) { if (!resolved.contains(exclusion)) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java index 438fb5e095..b7a0bcea3b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java @@ -322,7 +322,7 @@ public class Library { if (!line.startsWith("#")) { String[] components = line.split(":"); Map groupDependencies = this.dependencyVersions - .computeIfAbsent(components[0], (key) -> new HashMap<>()); + .computeIfAbsent(components[0], (key) -> new HashMap<>()); groupDependencies.put(components[1], components[2]); } } @@ -372,7 +372,7 @@ public class Library { Matcher matcher = CONSTRAINT_PATTERN.matcher(line.trim()); if (matcher.matches()) { Map groupDependencies = this.dependencyVersions - .computeIfAbsent(matcher.group(1), (key) -> new HashMap<>()); + .computeIfAbsent(matcher.group(1), (key) -> new HashMap<>()); groupDependencies.put(matcher.group(2), matcher.group(3)); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java index 25a2e68394..840665d78d 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/InteractiveUpgradeResolver.java @@ -50,7 +50,7 @@ public final class InteractiveUpgradeResolver implements UpgradeResolver { librariesByName.put(library.getName(), library); } List libraryUpdates = this.libraryUpdateResolver - .findLibraryUpdates(librariesToUpgrade, librariesByName); + .findLibraryUpdates(librariesToUpgrade, librariesByName); return libraryUpdates.stream().map(this::resolveUpgrade).filter(Objects::nonNull).toList(); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java index 8f938b755e..b7c23092e6 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/MavenMetadataVersionResolver.java @@ -75,10 +75,12 @@ final class MavenMetadataVersionResolver implements VersionResolver { URI url = repositoryUrl.resolve(groupId.replace('.', '/') + "/" + artifactId + "/maven-metadata.xml"); try { String metadata = this.rest.getForObject(url, String.class); - Document metadataDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder() - .parse(new InputSource(new StringReader(metadata))); - NodeList versionNodes = (NodeList) XPathFactory.newInstance().newXPath() - .evaluate("/metadata/versioning/versions/version", metadataDocument, XPathConstants.NODESET); + Document metadataDocument = DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .parse(new InputSource(new StringReader(metadata))); + NodeList versionNodes = (NodeList) XPathFactory.newInstance() + .newXPath() + .evaluate("/metadata/versioning/versions/version", metadataDocument, XPathConstants.NODESET); for (int i = 0; i < versionNodes.getLength(); i++) { versions.add(versionNodes.item(i).getTextContent()); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java index c7c1f45bb8..03f6184dc5 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/StandardLibraryUpdateResolver.java @@ -106,14 +106,19 @@ class StandardLibraryUpdateResolver implements LibraryUpdateResolver { getLaterVersionsForModule(group.getId(), plugin, libraryVersion)); } } - List allVersions = moduleVersions.values().stream().flatMap(SortedSet::stream).distinct() - .filter((dependencyVersion) -> isPermitted(dependencyVersion, library.getProhibitedVersions())) - .collect(Collectors.toList()); + List allVersions = moduleVersions.values() + .stream() + .flatMap(SortedSet::stream) + .distinct() + .filter((dependencyVersion) -> isPermitted(dependencyVersion, library.getProhibitedVersions())) + .collect(Collectors.toList()); if (allVersions.isEmpty()) { return Collections.emptyList(); } - return allVersions.stream().map((version) -> new VersionOption.ResolvedVersionOption(version, - getMissingModules(moduleVersions, version))).collect(Collectors.toList()); + return allVersions.stream() + .map((version) -> new VersionOption.ResolvedVersionOption(version, + getMissingModules(moduleVersions, version))) + .collect(Collectors.toList()); } private List determineAlignedVersionOption(Library library, Map libraries) { @@ -165,7 +170,7 @@ class StandardLibraryUpdateResolver implements LibraryUpdateResolver { for (ProhibitedVersion prohibitedVersion : prohibitedVersions) { String dependencyVersionToString = dependencyVersion.toString(); if (prohibitedVersion.getRange() != null && prohibitedVersion.getRange() - .containsVersion(new DefaultArtifactVersion(dependencyVersionToString))) { + .containsVersion(new DefaultArtifactVersion(dependencyVersionToString))) { return false; } for (String startsWith : prohibitedVersion.getStartsWith()) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java index 47e24ceb79..71d8872e4b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,12 +43,12 @@ class UpgradeApplicator { Path apply(Upgrade upgrade) throws IOException { String buildFileContents = Files.readString(this.buildFile); Matcher matcher = Pattern.compile("library\\(\"" + upgrade.getLibrary().getName() + "\", \"(.+)\"\\)") - .matcher(buildFileContents); + .matcher(buildFileContents); if (!matcher.find()) { matcher = Pattern - .compile("library\\(\"" + upgrade.getLibrary().getName() + "\"\\) \\{\\s+version\\(\"(.+)\"\\)", - Pattern.MULTILINE) - .matcher(buildFileContents); + .compile("library\\(\"" + upgrade.getLibrary().getName() + "\"\\) \\{\\s+version\\(\"(.+)\"\\)", + Pattern.MULTILINE) + .matcher(buildFileContents); if (!matcher.find()) { throw new IllegalStateException("Failed to find definition for library '" + upgrade.getLibrary().getName() + "' in bom '" + this.buildFile + "'"); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java index 359355a1ba..ae2625c0e4 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeDependencies.java @@ -129,12 +129,14 @@ public abstract class UpgradeDependencies extends DefaultTask { existingUpgradeIssue.label(Arrays.asList("type: task", "status: superseded")); } } - if (new ProcessBuilder().command("git", "add", modified.toFile().getAbsolutePath()).start() - .waitFor() != 0) { + if (new ProcessBuilder().command("git", "add", modified.toFile().getAbsolutePath()) + .start() + .waitFor() != 0) { throw new IllegalStateException("git add failed"); } - if (new ProcessBuilder().command("git", "commit", "-m", commitMessage(upgrade, issueNumber)).start() - .waitFor() != 0) { + if (new ProcessBuilder().command("git", "commit", "-m", commitMessage(upgrade, issueNumber)) + .start() + .waitFor() != 0) { throw new IllegalStateException("git commit failed"); } } @@ -175,7 +177,8 @@ public abstract class UpgradeDependencies extends DefaultTask { private Milestone determineMilestone(GitHubRepository repository) { List milestones = repository.getMilestones(); java.util.Optional matchingMilestone = milestones.stream() - .filter((milestone) -> milestone.getName().equals(getMilestone().get())).findFirst(); + .filter((milestone) -> milestone.getName().equals(getMilestone().get())) + .findFirst(); if (!matchingMilestone.isPresent()) { throw new InvalidUserDataException("Unknown milestone: " + getMilestone().get()); } @@ -185,8 +188,9 @@ public abstract class UpgradeDependencies extends DefaultTask { private Issue findExistingUpgradeIssue(List existingUpgradeIssues, Upgrade upgrade) { String toMatch = "Upgrade to " + upgrade.getLibrary().getName(); for (Issue existingUpgradeIssue : existingUpgradeIssues) { - if (existingUpgradeIssue.getTitle().substring(0, existingUpgradeIssue.getTitle().lastIndexOf(' ')) - .equals(toMatch)) { + if (existingUpgradeIssue.getTitle() + .substring(0, existingUpgradeIssue.getTitle().lastIndexOf(' ')) + .equals(toMatch)) { return existingUpgradeIssue; } } @@ -197,8 +201,8 @@ public abstract class UpgradeDependencies extends DefaultTask { private List resolveUpgrades() { List upgrades = new InteractiveUpgradeResolver(getServices().get(UserInputHandler.class), new MultithreadedLibraryUpdateResolver(new MavenMetadataVersionResolver(getRepositoryUris().get()), - this.bom.getUpgrade().getPolicy(), getThreads().get())).resolveUpgrades( - matchingLibraries(getLibraries().getOrNull()), this.bom.getLibraries()); + this.bom.getUpgrade().getPolicy(), getThreads().get())) + .resolveUpgrades(matchingLibraries(getLibraries().getOrNull()), this.bom.getLibraries()); return upgrades; } @@ -207,8 +211,10 @@ public abstract class UpgradeDependencies extends DefaultTask { return this.bom.getLibraries(); } Predicate libraryPredicate = Pattern.compile(pattern).asPredicate(); - List matchingLibraries = this.bom.getLibraries().stream() - .filter((library) -> libraryPredicate.test(library.getName())).toList(); + List matchingLibraries = this.bom.getLibraries() + .stream() + .filter((library) -> libraryPredicate.test(library.getName())) + .toList(); if (matchingLibraries.isEmpty()) { throw new InvalidUserDataException("No libraries matched '" + pattern + "'"); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java index ec5db84fba..1c880fb99c 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHub.java @@ -49,7 +49,8 @@ final class StandardGitHub implements GitHub { Collections.singletonList(new MappingJackson2HttpMessageConverter(new ObjectMapper()))); restTemplate.getInterceptors().add((request, body, execution) -> { request.getHeaders().add("User-Agent", StandardGitHub.this.username); - request.getHeaders().add("Authorization", "Basic " + Base64.getEncoder() + request.getHeaders() + .add("Authorization", "Basic " + Base64.getEncoder() .encodeToString((StandardGitHub.this.username + ":" + StandardGitHub.this.password).getBytes())); request.getHeaders().add("Accept", MediaType.APPLICATION_JSON_VALUE); return execution.execute(request, body); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java index 0628362345..72cdc09461 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForConflicts.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,8 +70,8 @@ public class CheckClasspathForConflicts extends DefaultTask { if (file.isDirectory()) { Path root = file.toPath(); try (Stream pathStream = Files.walk(root)) { - pathStream.filter(Files::isRegularFile).forEach( - (entry) -> classpathContents.add(root.relativize(entry).toString(), root.toString())); + pathStream.filter(Files::isRegularFile) + .forEach((entry) -> classpathContents.add(root.relativize(entry).toString(), root.toString())); } } else { @@ -111,9 +111,11 @@ public class CheckClasspathForConflicts extends DefaultTask { } private Map> getConflicts(List> ignores) { - return this.classpathContents.entrySet().stream().filter((entry) -> entry.getValue().size() > 1) - .filter((entry) -> canConflict(entry.getKey(), ignores)) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new)); + return this.classpathContents.entrySet() + .stream() + .filter((entry) -> entry.getValue().size() > 1) + .filter((entry) -> canConflict(entry.getKey(), ignores)) + .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new)); } private boolean canConflict(String name, List> ignores) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java index 56814c827e..548344b731 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForProhibitedDependencies.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,9 +52,13 @@ public class CheckClasspathForProhibitedDependencies extends DefaultTask { @TaskAction public void checkForProhibitedDependencies() { - TreeSet prohibited = this.classpath.getResolvedConfiguration().getResolvedArtifacts().stream() - .map((artifact) -> artifact.getModuleVersion().getId()).filter(this::prohibited) - .map((id) -> id.getGroup() + ":" + id.getName()).collect(Collectors.toCollection(TreeSet::new)); + TreeSet prohibited = this.classpath.getResolvedConfiguration() + .getResolvedArtifacts() + .stream() + .map((artifact) -> artifact.getModuleVersion().getId()) + .filter(this::prohibited) + .map((id) -> id.getGroup() + ":" + id.getName()) + .collect(Collectors.toCollection(TreeSet::new)); if (!prohibited.isEmpty()) { StringBuilder message = new StringBuilder(String.format("Found prohibited dependencies:%n")); for (String dependency : prohibited) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java index a97bf106df..a7010c94b1 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,8 +67,8 @@ public class CheckClasspathForUnnecessaryExclusions extends DefaultTask { ConfigurationContainer configurations) { this.dependencyHandler = getProject().getDependencies(); this.configurations = getProject().getConfigurations(); - this.platform = this.dependencyHandler.create( - this.dependencyHandler.platform(this.dependencyHandler.project(SPRING_BOOT_DEPENDENCIES_PROJECT))); + this.platform = this.dependencyHandler + .create(this.dependencyHandler.platform(this.dependencyHandler.project(SPRING_BOOT_DEPENDENCIES_PROJECT))); getOutputs().upToDateWhen((task) -> true); } @@ -86,8 +86,10 @@ public class CheckClasspathForUnnecessaryExclusions extends DefaultTask { private void processDependency(ModuleDependency dependency) { String dependencyId = getId(dependency); - TreeSet exclusions = dependency.getExcludeRules().stream().map(this::getId) - .collect(Collectors.toCollection(TreeSet::new)); + TreeSet exclusions = dependency.getExcludeRules() + .stream() + .map(this::getId) + .collect(Collectors.toCollection(TreeSet::new)); this.exclusionsByDependencyId.put(dependencyId, exclusions); if (!exclusions.isEmpty()) { this.dependencyById.put(dependencyId, getProject().getDependencies().create(dependencyId)); @@ -106,7 +108,12 @@ public class CheckClasspathForUnnecessaryExclusions extends DefaultTask { if (!exclusions.isEmpty()) { Dependency toCheck = this.dependencyById.get(dependencyId); List dependencies = this.configurations.detachedConfiguration(toCheck, this.platform) - .getIncoming().getArtifacts().getArtifacts().stream().map(this::getId).toList(); + .getIncoming() + .getArtifacts() + .getArtifacts() + .stream() + .map(this::getId) + .toList(); exclusions.removeAll(dependencies); removeProfileExclusions(dependencyId, exclusions); if (!exclusions.isEmpty()) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java b/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java index 572bf2af3b..4d14b2977d 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/constraints/ExtractVersionConstraints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -64,8 +64,10 @@ public class ExtractVersionConstraints extends DefaultTask { } public void enforcedPlatform(String projectPath) { - this.configuration.getDependencies().add(getProject().getDependencies().enforcedPlatform( - getProject().getDependencies().project(Collections.singletonMap("path", projectPath)))); + this.configuration.getDependencies() + .add(getProject().getDependencies() + .enforcedPlatform( + getProject().getDependencies().project(Collections.singletonMap("path", projectPath)))); this.projectPaths.add(projectPath); } @@ -89,8 +91,10 @@ public class ExtractVersionConstraints extends DefaultTask { this.configuration.resolve(); for (String projectPath : this.projectPaths) { extractVersionProperties(projectPath); - for (DependencyConstraint constraint : getProject().project(projectPath).getConfigurations() - .getByName("apiElements").getAllDependencyConstraints()) { + for (DependencyConstraint constraint : getProject().project(projectPath) + .getConfigurations() + .getByName("apiElements") + .getAllDependencyConstraints()) { this.versionConstraints.put(constraint.getGroup() + ":" + constraint.getName(), constraint.getVersionConstraint().toString()); this.constrainedVersions.add(new ConstrainedVersion(constraint.getGroup(), constraint.getName(), diff --git a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java index ccc094539e..3e895d4fe3 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,75 +87,102 @@ public class ConfigurationPropertiesPlugin implements Plugin { private void configureConfigurationPropertiesAnnotationProcessor(Project project) { Configuration annotationProcessors = project.getConfigurations() - .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); - annotationProcessors.getDependencies().add(project.getDependencies().project(Collections.singletonMap("path", - ":spring-boot-project:spring-boot-tools:spring-boot-configuration-processor"))); + .getByName(JavaPlugin.ANNOTATION_PROCESSOR_CONFIGURATION_NAME); + annotationProcessors.getDependencies() + .add(project.getDependencies() + .project(Collections.singletonMap("path", + ":spring-boot-project:spring-boot-tools:spring-boot-configuration-processor"))); project.getPlugins().apply(ProcessedAnnotationsPlugin.class); } private void disableIncrementalCompilation(Project project) { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); - project.getTasks().named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) - .configure((compileJava) -> compileJava.getOptions().setIncremental(false)); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + project.getTasks() + .named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) + .configure((compileJava) -> compileJava.getOptions().setIncremental(false)); } private void addMetadataArtifact(Project project) { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); project.getConfigurations().maybeCreate(CONFIGURATION_PROPERTIES_METADATA_CONFIGURATION_NAME); - project.afterEvaluate((evaluatedProject) -> evaluatedProject.getArtifacts().add( - CONFIGURATION_PROPERTIES_METADATA_CONFIGURATION_NAME, - mainSourceSet.getJava().getDestinationDirectory().dir("META-INF/spring-configuration-metadata.json"), - (artifact) -> artifact + project.afterEvaluate((evaluatedProject) -> evaluatedProject.getArtifacts() + .add(CONFIGURATION_PROPERTIES_METADATA_CONFIGURATION_NAME, + mainSourceSet.getJava() + .getDestinationDirectory() + .dir("META-INF/spring-configuration-metadata.json"), + (artifact) -> artifact .builtBy(evaluatedProject.getTasks().getByName(mainSourceSet.getClassesTaskName())))); } private void configureAdditionalMetadataLocationsCompilerArgument(Project project) { - JavaCompile compileJava = project.getTasks().withType(JavaCompile.class) - .getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME); - ((Task) compileJava).getInputs().files(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME)) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("processed resources"); - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); - compileJava.getOptions().getCompilerArgs() - .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + StringUtils - .collectionToCommaDelimitedString(mainSourceSet.getResources().getSourceDirectories().getFiles() - .stream().map(project.getRootProject()::relativePath).collect(Collectors.toSet()))); + JavaCompile compileJava = project.getTasks() + .withType(JavaCompile.class) + .getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME); + ((Task) compileJava).getInputs() + .files(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME)) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("processed resources"); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + compileJava.getOptions() + .getCompilerArgs() + .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + + StringUtils.collectionToCommaDelimitedString(mainSourceSet.getResources() + .getSourceDirectories() + .getFiles() + .stream() + .map(project.getRootProject()::relativePath) + .collect(Collectors.toSet()))); } private void registerCheckAdditionalMetadataTask(Project project) { TaskProvider checkConfigurationMetadata = project.getTasks() - .register(CHECK_ADDITIONAL_SPRING_CONFIGURATION_METADATA_TASK_NAME, - CheckAdditionalSpringConfigurationMetadata.class); + .register(CHECK_ADDITIONAL_SPRING_CONFIGURATION_METADATA_TASK_NAME, + CheckAdditionalSpringConfigurationMetadata.class); checkConfigurationMetadata.configure((check) -> { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); check.setSource(mainSourceSet.getResources()); check.include("META-INF/additional-spring-configuration-metadata.json"); - check.getReportLocation().set(project.getLayout().getBuildDirectory() + check.getReportLocation() + .set(project.getLayout() + .getBuildDirectory() .file("reports/additional-spring-configuration-metadata/check.txt")); }); - project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME) - .configure((check) -> check.dependsOn(checkConfigurationMetadata)); + project.getTasks() + .named(LifecycleBasePlugin.CHECK_TASK_NAME) + .configure((check) -> check.dependsOn(checkConfigurationMetadata)); } private void registerCheckMetadataTask(Project project) { TaskProvider checkConfigurationMetadata = project.getTasks() - .register(CHECK_SPRING_CONFIGURATION_METADATA_TASK_NAME, CheckSpringConfigurationMetadata.class); + .register(CHECK_SPRING_CONFIGURATION_METADATA_TASK_NAME, CheckSpringConfigurationMetadata.class); checkConfigurationMetadata.configure((check) -> { - SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + SourceSet mainSourceSet = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); Provider metadataLocation = project.getTasks() - .named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) - .flatMap((javaCompile) -> javaCompile.getDestinationDirectory() - .file("META-INF/spring-configuration-metadata.json")); + .named(mainSourceSet.getCompileJavaTaskName(), JavaCompile.class) + .flatMap((javaCompile) -> javaCompile.getDestinationDirectory() + .file("META-INF/spring-configuration-metadata.json")); check.getMetadataLocation().set(metadataLocation); - check.getReportLocation().set( - project.getLayout().getBuildDirectory().file("reports/spring-configuration-metadata/check.txt")); + check.getReportLocation() + .set(project.getLayout().getBuildDirectory().file("reports/spring-configuration-metadata/check.txt")); }); - project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME) - .configure((check) -> check.dependsOn(checkConfigurationMetadata)); + project.getTasks() + .named(LifecycleBasePlugin.CHECK_TASK_NAME) + .configure((check) -> check.dependsOn(checkConfigurationMetadata)); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java index 2ced4cf15d..65f6bb3625 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/SingleRow.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,9 @@ class SingleRow extends Row { return null; } if (defaultValue.getClass().isArray()) { - return Arrays.stream((Object[]) defaultValue).map(Object::toString) - .collect(Collectors.joining("," + System.lineSeparator())); + return Arrays.stream((Object[]) defaultValue) + .map(Object::toString) + .collect(Collectors.joining("," + System.lineSeparator())); } return defaultValue.toString(); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java index 0930b2f7fe..3e7d7ebf19 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippets.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,8 +52,10 @@ class Snippets { void writeTo(Path outputDirectory) throws IOException { createDirectory(outputDirectory); - Set remaining = this.properties.stream().filter((property) -> !property.isDeprecated()) - .map(ConfigurationProperty::getName).collect(Collectors.toSet()); + Set remaining = this.properties.stream() + .filter((property) -> !property.isDeprecated()) + .map(ConfigurationProperty::getName) + .collect(Collectors.toSet()); for (Snippet snippet : this.snippets) { Set written = writeSnippet(outputDirectory, snippet, remaining); remaining.removeAll(written); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java b/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java index ef86b4a7ff..515228ce70 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/devtools/DocumentDevtoolsPropertyDefaults.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,8 +48,9 @@ public class DocumentDevtoolsPropertyDefaults extends DefaultTask { public DocumentDevtoolsPropertyDefaults() { this.devtools = getProject().getConfigurations().create("devtools"); this.outputFile = getProject().getObjects().fileProperty(); - this.outputFile.convention(getProject().getLayout().getBuildDirectory() - .file("docs/generated/using/devtools-property-defaults.adoc")); + this.outputFile.convention(getProject().getLayout() + .getBuildDirectory() + .file("docs/generated/using/devtools-property-defaults.adoc")); Map dependency = new HashMap<>(); dependency.put("path", ":spring-boot-project:spring-boot-devtools"); dependency.put("configuration", "propertyDefaults"); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java b/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java index ee08b9eac7..0f95d55d3d 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/docs/ApplicationRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,9 @@ public class ApplicationRunner extends DefaultTask { private final Property expectedLogging = getProject().getObjects().property(String.class); - private final Property applicationJar = getProject().getObjects().property(String.class) - .convention("/opt/apps/myapp.jar"); + private final Property applicationJar = getProject().getObjects() + .property(String.class) + .convention("/opt/apps/myapp.jar"); private final Map normalizations = new HashMap<>(); @@ -118,13 +119,17 @@ public class ApplicationRunner extends DefaultTask { File executable = Jvm.current().getExecutable("java"); command.add(executable.getAbsolutePath()); command.add("-cp"); - command.add(this.classpath.getFiles().stream().map(File::getAbsolutePath) - .collect(Collectors.joining(File.pathSeparator))); + command.add(this.classpath.getFiles() + .stream() + .map(File::getAbsolutePath) + .collect(Collectors.joining(File.pathSeparator))); command.add(this.mainClass.get()); command.addAll(this.args.get()); File outputFile = this.output.getAsFile().get(); - Process process = new ProcessBuilder().redirectOutput(outputFile).redirectError(outputFile).command(command) - .start(); + Process process = new ProcessBuilder().redirectOutput(outputFile) + .redirectError(outputFile) + .command(command) + .start(); awaitLogging(process); process.destroy(); normalizeLogging(); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java index 954f9467a7..0419f33496 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/DocumentPluginGoals.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -108,8 +108,9 @@ public class DocumentPluginGoals extends DefaultTask { writer.println("== Required parameters"); writeParametersTable(writer, detailsSectionId, requiredParameters); } - List optionalParameters = parameters.stream().filter((parameter) -> !parameter.isRequired()) - .toList(); + List optionalParameters = parameters.stream() + .filter((parameter) -> !parameter.isRequired()) + .toList(); if (!optionalParameters.isEmpty()) { writer.println(); writer.println(); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java index d3e9875f4d..70339d0714 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenExec.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,8 +51,9 @@ public class MavenExec extends JavaExec { public void setProjectDir(File projectDir) { this.projectDir = projectDir; - getInputs().file(new File(projectDir, "pom.xml")).withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("pom"); + getInputs().file(new File(projectDir, "pom.xml")) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("pom"); } @Override @@ -88,10 +89,11 @@ public class MavenExec extends JavaExec { maven.getDependencies().add(project.getDependencies().create("org.apache.maven:maven-embedder:3.6.2")); maven.getDependencies().add(project.getDependencies().create("org.apache.maven:maven-compat:3.6.2")); maven.getDependencies().add(project.getDependencies().create("org.slf4j:slf4j-simple:1.7.5")); - maven.getDependencies().add( - project.getDependencies().create("org.apache.maven.resolver:maven-resolver-connector-basic:1.4.1")); - maven.getDependencies().add( - project.getDependencies().create("org.apache.maven.resolver:maven-resolver-transport-http:1.4.1")); + maven.getDependencies() + .add(project.getDependencies() + .create("org.apache.maven.resolver:maven-resolver-connector-basic:1.4.1")); + maven.getDependencies() + .add(project.getDependencies().create("org.apache.maven.resolver:maven-resolver-transport-http:1.4.1")); }); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java index c182feb2e1..d8c7b1977f 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -128,15 +128,15 @@ public class MavenPluginPlugin implements Plugin { private void addPopulateIntTestMavenRepositoryTask(Project project) { Configuration runtimeClasspathWithMetadata = project.getConfigurations().create("runtimeClasspathWithMetadata"); runtimeClasspathWithMetadata - .extendsFrom(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)); + .extendsFrom(project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)); runtimeClasspathWithMetadata.attributes((attributes) -> attributes.attribute(DocsType.DOCS_TYPE_ATTRIBUTE, project.getObjects().named(DocsType.class, "maven-repository"))); RuntimeClasspathMavenRepository runtimeClasspathMavenRepository = project.getTasks() - .create("runtimeClasspathMavenRepository", RuntimeClasspathMavenRepository.class); + .create("runtimeClasspathMavenRepository", RuntimeClasspathMavenRepository.class); runtimeClasspathMavenRepository.getOutputDirectory() - .set(new File(project.getBuildDir(), "runtime-classpath-repository")); + .set(new File(project.getBuildDir(), "runtime-classpath-repository")); project.getDependencies() - .components((components) -> components.all(MavenRepositoryComponentMetadataRule.class)); + .components((components) -> components.all(MavenRepositoryComponentMetadataRule.class)); Sync task = project.getTasks().create("populateIntTestMavenRepository", Sync.class); task.setDestinationDir(new File(project.getBuildDir(), "int-test-maven-repository")); task.with(copyIntTestMavenRepositoryFiles(project, runtimeClasspathMavenRepository)); @@ -219,8 +219,8 @@ public class MavenPluginPlugin implements Plugin { private FormatHelpMojoSource createFormatHelpMojoSource(Project project, MavenExec generateHelpMojoTask, File generatedHelpMojoDir) { - FormatHelpMojoSource formatHelpMojoSource = project.getTasks().create("formatHelpMojoSource", - FormatHelpMojoSource.class); + FormatHelpMojoSource formatHelpMojoSource = project.getTasks() + .create("formatHelpMojoSource", FormatHelpMojoSource.class); formatHelpMojoSource.setGenerator(generateHelpMojoTask); formatHelpMojoSource.setOutputDir(generatedHelpMojoDir); return formatHelpMojoSource; @@ -241,8 +241,10 @@ public class MavenPluginPlugin implements Plugin { MavenExec generatePluginDescriptor = project.getTasks().create("generatePluginDescriptor", MavenExec.class); generatePluginDescriptor.args("org.apache.maven.plugins:maven-plugin-plugin:3.6.1:descriptor"); generatePluginDescriptor.getOutputs().dir(new File(mavenDir, "target/classes/META-INF/maven")); - generatePluginDescriptor.getInputs().dir(new File(mavenDir, "target/classes/org")) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("plugin classes"); + generatePluginDescriptor.getInputs() + .dir(new File(mavenDir, "target/classes/org")) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("plugin classes"); generatePluginDescriptor.setProjectDir(mavenDir); return generatePluginDescriptor; } @@ -267,10 +269,13 @@ public class MavenPluginPlugin implements Plugin { } private void addExtractVersionPropertiesTask(Project project) { - ExtractVersionProperties extractVersionProperties = project.getTasks().create("extractVersionProperties", - ExtractVersionProperties.class); + ExtractVersionProperties extractVersionProperties = project.getTasks() + .create("extractVersionProperties", ExtractVersionProperties.class); extractVersionProperties.setEffectiveBoms(project.getConfigurations().create("versionProperties")); - extractVersionProperties.getDestination().set(project.getLayout().getBuildDirectory().dir("generated-resources") + extractVersionProperties.getDestination() + .set(project.getLayout() + .getBuildDirectory() + .dir("generated-resources") .map((dir) -> dir.file("extracted-versions.properties"))); } @@ -282,8 +287,9 @@ public class MavenPluginPlugin implements Plugin { void setGenerator(Task generator) { this.generator = generator; - getInputs().files(this.generator).withPathSensitivity(PathSensitivity.RELATIVE) - .withPropertyName("generated source"); + getInputs().files(this.generator) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("generated source"); } @OutputDirectory @@ -300,7 +306,7 @@ public class MavenPluginPlugin implements Plugin { FileFormatter formatter = new FileFormatter(); for (File output : this.generator.getOutputs().getFiles()) { formatter.formatFiles(getProject().fileTree(output), StandardCharsets.UTF_8) - .forEach((edit) -> save(output, edit)); + .forEach((edit) -> save(output, edit)); } } @@ -329,10 +335,11 @@ public class MavenPluginPlugin implements Plugin { @Override public void execute(ComponentMetadataContext context) { - context.getDetails().maybeAddVariant("compileWithMetadata", "compile", - (variant) -> configureVariant(context, variant)); - context.getDetails().maybeAddVariant("apiElementsWithMetadata", "apiElements", - (variant) -> configureVariant(context, variant)); + context.getDetails() + .maybeAddVariant("compileWithMetadata", "compile", (variant) -> configureVariant(context, variant)); + context.getDetails() + .maybeAddVariant("apiElementsWithMetadata", "apiElements", + (variant) -> configureVariant(context, variant)); } private void configureVariant(ComponentMetadataContext context, VariantMetadata variant) { @@ -374,11 +381,14 @@ public class MavenPluginPlugin implements Plugin { public void createRepository() { for (ResolvedArtifactResult result : this.runtimeClasspath.getIncoming().getArtifacts()) { if (result.getId().getComponentIdentifier() instanceof ModuleComponentIdentifier identifier) { - String fileName = result.getFile().getName() - .replace(identifier.getVersion() + "-" + identifier.getVersion(), identifier.getVersion()); - File repositoryLocation = this.outputDirectory.dir(identifier.getGroup().replace('.', '/') + "/" - + identifier.getModule() + "/" + identifier.getVersion() + "/" + fileName).get() - .getAsFile(); + String fileName = result.getFile() + .getName() + .replace(identifier.getVersion() + "-" + identifier.getVersion(), identifier.getVersion()); + File repositoryLocation = this.outputDirectory + .dir(identifier.getGroup().replace('.', '/') + "/" + identifier.getModule() + "/" + + identifier.getVersion() + "/" + fileName) + .get() + .getAsFile(); repositoryLocation.getParentFile().mkdirs(); try { Files.copy(result.getFile().toPath(), repositoryLocation.toPath(), @@ -487,8 +497,8 @@ public class MavenPluginPlugin implements Plugin { private String get(String expression) { try { - Node node = (Node) this.xpath.compile("/project/" + expression).evaluate(this.document, - XPathConstants.NODE); + Node node = (Node) this.xpath.compile("/project/" + expression) + .evaluate(this.document, XPathConstants.NODE); String text = (node != null) ? node.getTextContent() : null; Assert.hasLength(text, () -> "No result for expression " + expression); return text; diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java index fd7eee0010..d8a5f5a593 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PluginXmlParser.java @@ -111,10 +111,17 @@ class PluginXmlParser { } private String format(String input) { - return input.replace("", "`").replace("", "`").replace("<", "<").replace(">", ">") - .replace("
", " ").replace("\n", " ").replace(""", "\"").replaceAll("\\{@code (.*?)}", "`$1`") - .replaceAll("\\{@link (.*?)}", "`$1`").replaceAll("\\{@literal (.*?)}", "`$1`") - .replaceAll("(.*?)", "$1[$2]"); + return input.replace("", "`") + .replace("", "`") + .replace("<", "<") + .replace(">", ">") + .replace("
", " ") + .replace("\n", " ") + .replace(""", "\"") + .replaceAll("\\{@code (.*?)}", "`$1`") + .replaceAll("\\{@link (.*?)}", "`$1`") + .replaceAll("\\{@literal (.*?)}", "`$1`") + .replaceAll("(.*?)", "$1[$2]"); } private static final class IterableNodeList implements Iterable { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java index 4517b4a50e..3ebc30a4e9 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/PrepareMavenBinaries.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,10 +60,11 @@ public class PrepareMavenBinaries extends DefaultTask { @TaskAction public void prepareBinaries() { for (String version : this.versions) { - Configuration configuration = getProject().getConfigurations().detachedConfiguration( - getProject().getDependencies().create("org.apache.maven:apache-maven:" + version + ":bin@zip")); - getProject().copy( - (copy) -> copy.into(this.outputDir).from(getProject().zipTree(configuration.getSingleFile()))); + Configuration configuration = getProject().getConfigurations() + .detachedConfiguration( + getProject().getDependencies().create("org.apache.maven:apache-maven:" + version + ":bin@zip")); + getProject() + .copy((copy) -> copy.into(this.outputDir).from(getProject().zipTree(configuration.getSingleFile()))); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java index 8b37308b15..9dfdfa5176 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,13 +44,16 @@ public class OptionalDependenciesPlugin implements Plugin { optional.setCanBeConsumed(false); optional.setCanBeResolved(false); project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> { - SourceSetContainer sourceSets = project.getExtensions().getByType(JavaPluginExtension.class) - .getSourceSets(); + SourceSetContainer sourceSets = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets(); sourceSets.all((sourceSet) -> { - project.getConfigurations().getByName(sourceSet.getCompileClasspathConfigurationName()) - .extendsFrom(optional); - project.getConfigurations().getByName(sourceSet.getRuntimeClasspathConfigurationName()) - .extendsFrom(optional); + project.getConfigurations() + .getByName(sourceSet.getCompileClasspathConfigurationName()) + .extendsFrom(optional); + project.getConfigurations() + .getByName(sourceSet.getRuntimeClasspathConfigurationName()) + .extendsFrom(optional); }); }); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/processors/ProcessedAnnotationsPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/processors/ProcessedAnnotationsPlugin.java index a26b703917..b8abfe90f8 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/processors/ProcessedAnnotationsPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/processors/ProcessedAnnotationsPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2022-2022 the original author or authors. + * Copyright 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. @@ -31,8 +31,9 @@ public class ProcessedAnnotationsPlugin implements Plugin { @Override public void apply(Project project) { project.getPlugins().apply(AptEclipsePlugin.class); - project.getExtensions().getByType(EclipseModel.class).synchronizationTasks("eclipseJdtApt", "eclipseJdt", - "eclipseFactorypath"); + project.getExtensions() + .getByType(EclipseModel.class) + .synchronizationTasks("eclipseJdtApt", "eclipseJdt", "eclipseFactorypath"); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java b/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java index 52eab4dd80..669eeb40a0 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -84,8 +84,10 @@ public class DocumentStarters extends DefaultTask { @TaskAction void documentStarters() { - Set starters = this.starters.getFiles().stream().map(this::loadStarter) - .collect(Collectors.toCollection(TreeSet::new)); + Set starters = this.starters.getFiles() + .stream() + .map(this::loadStarter) + .collect(Collectors.toCollection(TreeSet::new)); writeTable("application-starters", starters.stream().filter(Starter::isApplication)); writeTable("production-starters", starters.stream().filter(Starter::isProduction)); writeTable("technical-starters", starters.stream().filter(Starter::isTechnical)); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java index 38ce419760..4125182d6e 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -73,8 +73,13 @@ public class StarterMetadata extends DefaultTask { Properties properties = CollectionFactory.createSortedProperties(true); properties.setProperty("name", getProject().getName()); properties.setProperty("description", getProject().getDescription()); - properties.setProperty("dependencies", String.join(",", this.dependencies.getResolvedConfiguration() - .getResolvedArtifacts().stream().map(ResolvedArtifact::getName).collect(Collectors.toSet()))); + properties.setProperty("dependencies", + String.join(",", + this.dependencies.getResolvedConfiguration() + .getResolvedArtifacts() + .stream() + .map(ResolvedArtifact::getName) + .collect(Collectors.toSet()))); this.destination.getParentFile().mkdirs(); try (FileWriter writer = new FileWriter(this.destination)) { properties.store(writer, null); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java index ec39845573..846efd43be 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -58,25 +58,26 @@ public class StarterPlugin implements Plugin { File destination = new File(project.getBuildDir(), "starter-metadata.properties"); starterMetadata.setDestination(destination); configurations.create("starterMetadata"); - project.getArtifacts().add("starterMetadata", project.provider(starterMetadata::getDestination), - (artifact) -> artifact.builtBy(starterMetadata)); + project.getArtifacts() + .add("starterMetadata", project.provider(starterMetadata::getDestination), + (artifact) -> artifact.builtBy(starterMetadata)); createClasspathConflictsCheck(runtimeClasspath, project); createUnnecessaryExclusionsCheck(runtimeClasspath, project); configureJarManifest(project); } private void createClasspathConflictsCheck(Configuration classpath, Project project) { - CheckClasspathForConflicts checkClasspathForConflicts = project.getTasks().create( - "check" + StringUtils.capitalize(classpath.getName() + "ForConflicts"), - CheckClasspathForConflicts.class); + CheckClasspathForConflicts checkClasspathForConflicts = project.getTasks() + .create("check" + StringUtils.capitalize(classpath.getName() + "ForConflicts"), + CheckClasspathForConflicts.class); checkClasspathForConflicts.setClasspath(classpath); project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(checkClasspathForConflicts); } private void createUnnecessaryExclusionsCheck(Configuration classpath, Project project) { - CheckClasspathForUnnecessaryExclusions checkClasspathForUnnecessaryExclusions = project.getTasks().create( - "check" + StringUtils.capitalize(classpath.getName() + "ForUnnecessaryExclusions"), - CheckClasspathForUnnecessaryExclusions.class); + CheckClasspathForUnnecessaryExclusions checkClasspathForUnnecessaryExclusions = project.getTasks() + .create("check" + StringUtils.capitalize(classpath.getName() + "ForUnnecessaryExclusions"), + CheckClasspathForUnnecessaryExclusions.class); checkClasspathForUnnecessaryExclusions.setClasspath(classpath); project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(checkClasspathForUnnecessaryExclusions); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java index 29af0140d2..6286df7601 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/test/IntegrationTestPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,8 +55,8 @@ public class IntegrationTestPlugin implements Plugin { project.getTasks().getByName(LifecycleBasePlugin.CHECK_TASK_NAME).dependsOn(intTest); project.getPlugins().withType(EclipsePlugin.class, (eclipsePlugin) -> { EclipseModel eclipse = project.getExtensions().getByType(EclipseModel.class); - eclipse.classpath((classpath) -> classpath.getPlusConfigurations().add( - project.getConfigurations().getByName(intTestSourceSet.getRuntimeClasspathConfigurationName()))); + eclipse.classpath((classpath) -> classpath.getPlusConfigurations() + .add(project.getConfigurations().getByName(intTestSourceSet.getRuntimeClasspathConfigurationName()))); }); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java index 777e94fafc..9259f8e369 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/test/SystemTestPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,8 +59,9 @@ public class SystemTestPlugin implements Plugin { createTestTask(project, systemTestSourceSet); project.getPlugins().withType(EclipsePlugin.class, (eclipsePlugin) -> { EclipseModel eclipse = project.getExtensions().getByType(EclipseModel.class); - eclipse.classpath((classpath) -> classpath.getPlusConfigurations().add( - project.getConfigurations().getByName(systemTestSourceSet.getRuntimeClasspathConfigurationName()))); + eclipse.classpath((classpath) -> classpath.getPlusConfigurations() + .add(project.getConfigurations() + .getByName(systemTestSourceSet.getRuntimeClasspathConfigurationName()))); }); } @@ -69,9 +70,9 @@ public class SystemTestPlugin implements Plugin { SourceSet systemTestSourceSet = sourceSets.create(SYSTEM_TEST_SOURCE_SET_NAME); SourceSet mainSourceSet = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME); systemTestSourceSet - .setCompileClasspath(systemTestSourceSet.getCompileClasspath().plus(mainSourceSet.getOutput())); + .setCompileClasspath(systemTestSourceSet.getCompileClasspath().plus(mainSourceSet.getOutput())); systemTestSourceSet - .setRuntimeClasspath(systemTestSourceSet.getRuntimeClasspath().plus(mainSourceSet.getOutput())); + .setRuntimeClasspath(systemTestSourceSet.getRuntimeClasspath().plus(mainSourceSet.getOutput())); return systemTestSourceSet; } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java b/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java index 598ed89954..c32073f492 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/TestSliceMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,9 +67,11 @@ public class TestSliceMetadata extends DefaultTask { public TestSliceMetadata() { getInputs().dir((Callable) () -> this.sourceSet.getOutput().getResourcesDir()) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("resources"); + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("resources"); getInputs().files((Callable) () -> this.sourceSet.getOutput().getClassesDirs()) - .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("classes"); + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName("classes"); } public void setSourceSet(SourceSet sourceSet) { @@ -84,8 +86,9 @@ public class TestSliceMetadata extends DefaultTask { public void setOutputFile(File outputFile) { this.outputFile = outputFile; Configuration testSliceMetadata = getProject().getConfigurations().maybeCreate("testSliceMetadata"); - getProject().getArtifacts().add(testSliceMetadata.getName(), - getProject().provider((Callable) this::getOutputFile), (artifact) -> artifact.builtBy(this)); + getProject().getArtifacts() + .add(testSliceMetadata.getName(), getProject().provider((Callable) this::getOutputFile), + (artifact) -> artifact.builtBy(this)); } @TaskAction @@ -100,8 +103,9 @@ public class TestSliceMetadata extends DefaultTask { private Properties readTestSlices() throws IOException { Properties testSlices = CollectionFactory.createSortedProperties(true); try (URLClassLoader classLoader = new URLClassLoader( - StreamSupport.stream(this.sourceSet.getRuntimeClasspath().spliterator(), false).map(this::toURL) - .toArray(URL[]::new))) { + StreamSupport.stream(this.sourceSet.getRuntimeClasspath().spliterator(), false) + .map(this::toURL) + .toArray(URL[]::new))) { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(classLoader); Properties springFactories = readSpringFactories( new File(this.sourceSet.getOutput().getResourcesDir(), "META-INF/spring.factories")); @@ -129,8 +133,8 @@ public class TestSliceMetadata extends DefaultTask { for (File file : files) { try { List lines = removeComments(Files.readAllLines(file.toPath())); - String fileNameWithoutExtension = file.getName().substring(0, - file.getName().length() - ".imports".length()); + String fileNameWithoutExtension = file.getName() + .substring(0, file.getName().length() - ".imports".length()); springFactories.setProperty(fileNameWithoutExtension, StringUtils.collectionToCommaDelimitedString(lines)); } @@ -176,9 +180,9 @@ public class TestSliceMetadata extends DefaultTask { Properties springFactories) throws IOException { try (Stream classes = Files.walk(classesDir.toPath())) { classes.filter((path) -> path.toString().endsWith("Test.class")) - .map((path) -> getMetadataReader(path, metadataReaderFactory)) - .filter((metadataReader) -> metadataReader.getClassMetadata().isAnnotation()) - .forEach((metadataReader) -> addTestSlice(testSlices, springFactories, metadataReader)); + .map((path) -> getMetadataReader(path, metadataReaderFactory)) + .filter((metadataReader) -> metadataReader.getClassMetadata().isAnnotation()) + .forEach((metadataReader) -> addTestSlice(testSlices, springFactories, metadataReader)); } } @@ -204,19 +208,20 @@ public class TestSliceMetadata extends DefaultTask { if (annotationMetadata.isAnnotated("org.springframework.boot.autoconfigure.ImportAutoConfiguration")) { importers = Stream.concat(importers, Stream.of(annotationMetadata.getClassName())); } - return importers.flatMap( - (importer) -> StringUtils.commaDelimitedListToSet(springFactories.getProperty(importer)).stream()) - .collect(Collectors.toCollection(TreeSet::new)); + return importers + .flatMap((importer) -> StringUtils.commaDelimitedListToSet(springFactories.getProperty(importer)).stream()) + .collect(Collectors.toCollection(TreeSet::new)); } private Stream findMetaImporters(AnnotationMetadata annotationMetadata) { - return annotationMetadata.getAnnotationTypes().stream() - .filter((annotationType) -> isAutoConfigurationImporter(annotationType, annotationMetadata)); + return annotationMetadata.getAnnotationTypes() + .stream() + .filter((annotationType) -> isAutoConfigurationImporter(annotationType, annotationMetadata)); } private boolean isAutoConfigurationImporter(String annotationType, AnnotationMetadata metadata) { return metadata.getMetaAnnotationTypes(annotationType) - .contains("org.springframework.boot.autoconfigure.ImportAutoConfiguration"); + .contains("org.springframework.boot.autoconfigure.ImportAutoConfiguration"); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java index 6fdb9bec49..f9ebc52f78 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -36,11 +36,13 @@ public class TestFailuresPlugin implements Plugin { @Override public void apply(Project project) { - Provider testResultsOverview = project.getGradle().getSharedServices() - .registerIfAbsent("testResultsOverview", TestResultsOverview.class, (spec) -> { - }); - project.getTasks().withType(Test.class, - (test) -> test.addTestListener(new FailureRecordingTestListener(testResultsOverview, test))); + Provider testResultsOverview = project.getGradle() + .getSharedServices() + .registerIfAbsent("testResultsOverview", TestResultsOverview.class, (spec) -> { + }); + project.getTasks() + .withType(Test.class, + (test) -> test.addTestListener(new FailureRecordingTestListener(testResultsOverview, test))); } private final class FailureRecordingTestListener implements TestListener { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java index 6319024eda..56618f05c4 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/testing/TestResultsOverview.java @@ -66,7 +66,7 @@ public abstract class TestResultsOverview System.err.println(); System.err.println(task.getPath()); failures.forEach((failure) -> System.err - .println(" " + failure.descriptor.getClassName() + " > " + failure.descriptor.getName())); + .println(" " + failure.descriptor.getClassName() + " > " + failure.descriptor.getName())); }); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java index 395209c81a..82abe1cd65 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/toolchain/ToolchainPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,16 +52,18 @@ public class ToolchainPlugin implements Plugin { disableToolchainTasks(project); } else { - JavaToolchainSpec toolchainSpec = project.getExtensions().getByType(JavaPluginExtension.class) - .getToolchain(); + JavaToolchainSpec toolchainSpec = project.getExtensions() + .getByType(JavaPluginExtension.class) + .getToolchain(); toolchainSpec.getLanguageVersion().set(toolchain.getJavaVersion()); configureTestToolchain(project, toolchain); } } private boolean isJavaVersionSupported(ToolchainExtension toolchain, JavaLanguageVersion toolchainVersion) { - return toolchain.getMaximumCompatibleJavaVersion().map((version) -> version.canCompileOrRun(toolchainVersion)) - .getOrElse(true); + return toolchain.getMaximumCompatibleJavaVersion() + .map((version) -> version.canCompileOrRun(toolchainVersion)) + .getOrElse(true); } private void disableToolchainTasks(Project project) { diff --git a/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java b/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java index ad76b0cb7a..6f7c1d0f76 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/ConventionsPluginTests.java @@ -88,9 +88,9 @@ class ConventionsPluginTests { assertThatNoticeIsPresent(jar); Attributes mainAttributes = jar.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Implementation-Title")) - .isEqualTo("Test project for manifest customization"); + .isEqualTo("Test project for manifest customization"); assertThat(mainAttributes.getValue("Automatic-Module-Name")) - .isEqualTo(this.projectDir.getName().replace("-", ".")); + .isEqualTo(this.projectDir.getName().replace("-", ".")); assertThat(mainAttributes.getValue("Implementation-Version")).isEqualTo("1.2.3"); assertThat(mainAttributes.getValue("Built-By")).isEqualTo("Spring"); assertThat(mainAttributes.getValue("Build-Jdk-Spec")).isEqualTo("17"); @@ -117,9 +117,9 @@ class ConventionsPluginTests { assertThatNoticeIsPresent(jar); Attributes mainAttributes = jar.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Implementation-Title")) - .isEqualTo("Source for " + this.projectDir.getName()); + .isEqualTo("Source for " + this.projectDir.getName()); assertThat(mainAttributes.getValue("Automatic-Module-Name")) - .isEqualTo(this.projectDir.getName().replace("-", ".")); + .isEqualTo(this.projectDir.getName().replace("-", ".")); assertThat(mainAttributes.getValue("Implementation-Version")).isEqualTo("1.2.3"); assertThat(mainAttributes.getValue("Built-By")).isEqualTo("Spring"); assertThat(mainAttributes.getValue("Build-Jdk-Spec")).isEqualTo("17"); @@ -146,9 +146,9 @@ class ConventionsPluginTests { assertThatNoticeIsPresent(jar); Attributes mainAttributes = jar.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Implementation-Title")) - .isEqualTo("Javadoc for " + this.projectDir.getName()); + .isEqualTo("Javadoc for " + this.projectDir.getName()); assertThat(mainAttributes.getValue("Automatic-Module-Name")) - .isEqualTo(this.projectDir.getName().replace("-", ".")); + .isEqualTo(this.projectDir.getName().replace("-", ".")); assertThat(mainAttributes.getValue("Implementation-Version")).isEqualTo("1.2.3"); assertThat(mainAttributes.getValue("Built-By")).isEqualTo("Spring"); assertThat(mainAttributes.getValue("Build-Jdk-Spec")).isEqualTo("17"); @@ -186,7 +186,8 @@ class ConventionsPluginTests { out.println("}"); } assertThat(runGradle(Collections.singletonMap("CI", "true"), "retryConfig", "--stacktrace").getOutput()) - .contains("maxRetries: 3").contains("failOnPassedAfterRetry: true"); + .contains("maxRetries: 3") + .contains("failOnPassedAfterRetry: true"); } @Test @@ -207,7 +208,8 @@ class ConventionsPluginTests { out.println("}"); } assertThat(runGradle(Collections.singletonMap("CI", "local"), "retryConfig", "--stacktrace").getOutput()) - .contains("maxRetries: 0").contains("failOnPassedAfterRetry: true"); + .contains("maxRetries: 0") + .contains("failOnPassedAfterRetry: true"); } private BuildResult runGradle(String... args) { @@ -215,8 +217,12 @@ class ConventionsPluginTests { } private BuildResult runGradle(Map environment, String... args) { - return GradleRunner.create().withProjectDir(this.projectDir).withEnvironment(environment).withArguments(args) - .withPluginClasspath().build(); + return GradleRunner.create() + .withProjectDir(this.projectDir) + .withEnvironment(environment) + .withArguments(args) + .withPluginClasspath() + .build(); } } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java b/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java index ad3c991606..c4f19c4508 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/architecture/PackageTangleCheckTests.java @@ -48,7 +48,8 @@ class PackageTangleCheckTests { assertThatExceptionOfType(GradleException.class).isThrownBy(packageTangleCheck::checkForPackageTangles); assertThat( new File(packageTangleCheck.getProject().getBuildDir(), "checkForPackageTangles/failure-report.txt") - .length()).isGreaterThan(0); + .length()) + .isGreaterThan(0); }); } @@ -58,7 +59,8 @@ class PackageTangleCheckTests { packageTangleCheck.checkForPackageTangles(); assertThat( new File(packageTangleCheck.getProject().getBuildDir(), "checkForPackageTangles/failure-report.txt") - .length()).isEqualTo(0); + .length()) + .isEqualTo(0); }); } @@ -67,8 +69,9 @@ class PackageTangleCheckTests { projectDir.mkdirs(); copyClasses(classes, projectDir); Project project = ProjectBuilder.builder().withProjectDir(projectDir).build(); - PackageTangleCheck packageTangleCheck = project.getTasks().create("checkForPackageTangles", - PackageTangleCheck.class, (task) -> task.setClasses(project.files("classes"))); + PackageTangleCheck packageTangleCheck = project.getTasks() + .create("checkForPackageTangles", PackageTangleCheck.class, + (task) -> task.setClasses(project.files("classes"))); callback.accept(packageTangleCheck); } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java b/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java index 0a9d5e420a..48ae5db62e 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/artifacts/ArtifactReleaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -84,7 +84,7 @@ class ArtifactReleaseTests { Project project = ProjectBuilder.builder().build(); project.setVersion("1.2.3"); assertThat(ArtifactRelease.forProject(project).getDownloadRepo()) - .contains("https://repo.maven.apache.org/maven2"); + .contains("https://repo.maven.apache.org/maven2"); } } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java b/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java index 6bc78ebc58..d6baf87b88 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/bom/BomPluginIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -319,8 +319,12 @@ class BomPluginIntegrationTests { // } private BuildResult runGradle(String... args) { - return GradleRunner.create().withDebug(true).withProjectDir(this.projectDir).withArguments(args) - .withPluginClasspath().build(); + return GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments(args) + .withPluginClasspath() + .build(); } private void generatePom(Consumer consumer) { diff --git a/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java b/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java index 7ab586bc68..5474d4aca0 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/context/properties/ConfigurationPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -33,7 +33,7 @@ class ConfigurationPropertiesTests { @Test void whenJsonHasAnIntegerDefaultValueThenItRemainsAnIntegerWhenRead() { ConfigurationProperties properties = ConfigurationProperties - .fromFiles(Arrays.asList(new File("src/test/resources/spring-configuration-metadata.json"))); + .fromFiles(Arrays.asList(new File("src/test/resources/spring-configuration-metadata.json"))); assertThat(properties.get("example.counter").getDefaultValue()).isEqualTo(0); } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java b/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java index 4333aa83f8..14755846df 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/mavenplugin/PluginXmlParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,8 @@ class PluginXmlParserTests { @Test void parseNonExistingFileThrowException() { assertThatThrownBy(() -> this.parser.parse(new File("src/test/resources/nonexistent.xml"))) - .isInstanceOf(RuntimeException.class).hasCauseInstanceOf(FileNotFoundException.class); + .isInstanceOf(RuntimeException.class) + .hasCauseInstanceOf(FileNotFoundException.class); } } diff --git a/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java b/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java index 9b63eae5d6..4df3756576 100644 --- a/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java +++ b/buildSrc/src/test/java/org/springframework/boot/build/testing/TestFailuresPluginIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,8 +50,12 @@ class TestFailuresPluginIntegrationTests { @Test void singleProject() { createProject(this.projectDir); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 1 test task:", "", ":test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", ""); @@ -60,8 +64,12 @@ class TestFailuresPluginIntegrationTests { @Test void multiProject() { createMultiProjectBuild(); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 1 test task:", "", ":project-one:test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", ""); @@ -70,8 +78,12 @@ class TestFailuresPluginIntegrationTests { @Test void multiProjectContinue() { createMultiProjectBuild(); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build", "--continue").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build", "--continue") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 2 test tasks:", "", ":project-one:test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", "", ":project-two:test", @@ -82,8 +94,12 @@ class TestFailuresPluginIntegrationTests { @Test void multiProjectParallel() { createMultiProjectBuild(); - BuildResult result = GradleRunner.create().withDebug(true).withProjectDir(this.projectDir) - .withArguments("build", "--parallel", "--stacktrace").withPluginClasspath().buildAndFail(); + BuildResult result = GradleRunner.create() + .withDebug(true) + .withProjectDir(this.projectDir) + .withArguments("build", "--parallel", "--stacktrace") + .withPluginClasspath() + .buildAndFail(); assertThat(readLines(result.getOutput())).containsSequence("Found test failures in 2 test tasks:", "", ":project-one:test", " example.ExampleTests > bad()", " example.ExampleTests > fail()", " example.MoreTests > bad()", " example.MoreTests > fail()", "", ":project-two:test", diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java index af4a7b000d..44703d5761 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java @@ -48,7 +48,7 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); + .fromMap(metadata.getAnnotationAttributes(this.annotationType.getName())); String endpointName = annotationAttributes.getString("value"); ConditionOutcome outcome = getEndpointOutcome(context, endpointName); if (outcome != null) { @@ -63,7 +63,7 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { if (environment.containsProperty(enabledProperty)) { boolean match = environment.getProperty(enabledProperty, Boolean.class, true); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) - .because(this.prefix + endpointName + ".enabled is " + match)); + .because(this.prefix + endpointName + ".enabled is " + match)); } return null; } @@ -79,9 +79,9 @@ public abstract class OnEndpointElementCondition extends SpringBootCondition { */ protected ConditionOutcome getDefaultOutcome(ConditionContext context, AnnotationAttributes annotationAttributes) { boolean match = Boolean - .parseBoolean(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true")); + .parseBoolean(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true")); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) - .because(this.prefix + "defaults.enabled is considered " + match)); + .because(this.prefix + "defaults.enabled is considered " + match)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java index ecc5a80805..fae61a186b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessor implements HealthEndpo AvailabilityProbesHealthEndpointGroupsPostProcessor(Environment environment) { this.addAdditionalPaths = "true" - .equalsIgnoreCase(environment.getProperty("management.endpoint.health.probes.add-additional-paths")); + .equalsIgnoreCase(environment.getProperty("management.endpoint.health.probes.add-additional-paths")); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java index 76b711a018..173bcbe9e9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,8 +73,11 @@ public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer { } private boolean isHealthEndpointExtension(Class extensionBeanType) { - return MergedAnnotations.from(extensionBeanType).get(EndpointWebExtension.class) - .getValue("endpoint", Class.class).map(HealthEndpoint.class::isAssignableFrom).orElse(false); + return MergedAnnotations.from(extensionBeanType) + .get(EndpointWebExtension.class) + .getValue("endpoint", Class.class) + .map(HealthEndpoint.class::isAssignableFrom) + .orElse(false); } private boolean isCloudFoundryHealthEndpointExtension(Class extensionBeanType) { @@ -85,8 +88,8 @@ public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - hints.reflection().registerType(CloudFoundryEndpointFilter.class, - MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); + hints.reflection() + .registerType(CloudFoundryEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java index dd209ff8be..1e4df11c0f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -80,12 +80,12 @@ class CloudFoundrySecurityInterceptor { try { Token token = getToken(exchange.getRequest()); return this.tokenValidator.validate(token) - .then(this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId)) - .filter((accessLevel) -> accessLevel.isAccessAllowed(id)) - .switchIfEmpty( - Mono.error(new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"))) - .doOnSuccess((accessLevel) -> exchange.getAttributes().put("cloudFoundryAccessLevel", accessLevel)) - .then(); + .then(this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId)) + .filter((accessLevel) -> accessLevel.isAccessAllowed(id)) + .switchIfEmpty( + Mono.error(new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"))) + .doOnSuccess((accessLevel) -> exchange.getAttributes().put("cloudFoundryAccessLevel", accessLevel)) + .then(); } catch (CloudFoundryAuthorizationException ex) { return Mono.error(ex); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java index aa50daab06..7376ca25cf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -91,26 +91,26 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH public Publisher> links(ServerWebExchange exchange) { ServerHttpRequest request = exchange.getRequest(); return CloudFoundryWebFluxEndpointHandlerMapping.this.securityInterceptor.preHandle(exchange, "") - .map((securityResponse) -> { - if (!securityResponse.getStatus().equals(HttpStatus.OK)) { - return new ResponseEntity<>(securityResponse.getStatus()); - } - AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); - Map links = CloudFoundryWebFluxEndpointHandlerMapping.this.linksResolver - .resolveLinks(request.getURI().toString()); - return new ResponseEntity<>( - Collections.singletonMap("_links", getAccessibleLinks(accessLevel, links)), - HttpStatus.OK); - }); + .map((securityResponse) -> { + if (!securityResponse.getStatus().equals(HttpStatus.OK)) { + return new ResponseEntity<>(securityResponse.getStatus()); + } + AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + Map links = CloudFoundryWebFluxEndpointHandlerMapping.this.linksResolver + .resolveLinks(request.getURI().toString()); + return new ResponseEntity<>( + Collections.singletonMap("_links", getAccessibleLinks(accessLevel, links)), HttpStatus.OK); + }); } private Map getAccessibleLinks(AccessLevel accessLevel, Map links) { if (accessLevel == null) { return new LinkedHashMap<>(); } - return links.entrySet().stream() - .filter((entry) -> entry.getKey().equals("self") || accessLevel.isAccessAllowed(entry.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return links.entrySet() + .stream() + .filter((entry) -> entry.getKey().equals("self") || accessLevel.isAccessAllowed(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override @@ -141,7 +141,7 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH @Override public Mono> handle(ServerWebExchange exchange, Map body) { return this.securityInterceptor.preHandle(exchange, this.endpointId.toLowerCaseString()) - .flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse)); + .flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse)); } private Mono> flatMapResponse(ServerWebExchange exchange, Map body, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java index ca6478a457..7dc19baddf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -96,9 +96,9 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension(GitProperties properties, ObjectProvider infoContributors) { List contributors = infoContributors.orderedStream() - .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) - ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) - .toList(); + .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) + ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) + .toList(); return new CloudFoundryInfoEndpointWebExtension(new InfoEndpoint(contributors)); } @@ -143,8 +143,8 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - corsConfiguration.setAllowedHeaders( - Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); + corsConfiguration + .setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); return corsConfiguration; } @@ -171,7 +171,7 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration { private WebFilterChainProxy postProcess(WebFilterChainProxy existing) { ServerWebExchangeMatcher cloudFoundryRequestMatcher = ServerWebExchangeMatchers - .pathMatchers("/cloudfoundryapplication/**"); + .pathMatchers("/cloudfoundryapplication/**"); WebFilter noOpFilter = (exchange, chain) -> chain.filter(exchange); MatcherSecurityWebFilterChain ignoredRequestFilterChain = new MatcherSecurityWebFilterChain( cloudFoundryRequestMatcher, Collections.singletonList(noOpFilter)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java index ac4ee8b39b..4add4c0943 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java @@ -72,8 +72,9 @@ class ReactiveCloudFoundrySecurityService { } private Http11SslContextSpec createSslContextSpec() { - return Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + return Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); } /** @@ -85,8 +86,13 @@ class ReactiveCloudFoundrySecurityService { */ Mono getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { String uri = getPermissionsUri(applicationId); - return this.webClient.get().uri(uri).header("Authorization", "bearer " + token).retrieve().bodyToMono(Map.class) - .map(this::getAccessLevel).onErrorMap(this::mapError); + return this.webClient.get() + .uri(uri) + .header("Authorization", "bearer " + token) + .retrieve() + .bodyToMono(Map.class) + .map(this::getAccessLevel) + .onErrorMap(this::mapError); } private Throwable mapError(Throwable throwable) { @@ -123,8 +129,10 @@ class ReactiveCloudFoundrySecurityService { private Mono> fetchTokenKeys(String url) { RequestHeadersSpec uri = this.webClient.get().uri(url + "/token_keys"); - return uri.retrieve().bodyToMono(STRING_OBJECT_MAP).map(this::extractTokenKeys).onErrorMap( - ((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, ex.getMessage()))); + return uri.retrieve() + .bodyToMono(STRING_OBJECT_MAP) + .map(this::extractTokenKeys) + .onErrorMap(((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, ex.getMessage()))); } private Map extractTokenKeys(Map response) { @@ -141,10 +149,14 @@ class ReactiveCloudFoundrySecurityService { * @return the UAA url Mono */ Mono getUaaUrl() { - this.uaaUrl = this.webClient.get().uri(this.cloudControllerUrl + "/info").retrieve().bodyToMono(Map.class) - .map((response) -> (String) response.get("token_endpoint")).cache() - .onErrorMap((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, - "Unable to fetch token keys from UAA.")); + this.uaaUrl = this.webClient.get() + .uri(this.cloudControllerUrl + "/info") + .retrieve() + .bodyToMono(Map.class) + .map((response) -> (String) response.get("token_endpoint")) + .cache() + .onErrorMap((ex) -> new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, + "Unable to fetch token keys from UAA.")); return this.uaaUrl; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java index 6decc61033..e31fc3797a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -51,8 +51,10 @@ class ReactiveTokenValidator { } Mono validate(Token token) { - return validateAlgorithm(token).then(validateKeyIdAndSignature(token)).then(validateExpiry(token)) - .then(validateIssuer(token)).then(validateAudience(token)); + return validateAlgorithm(token).then(validateKeyIdAndSignature(token)) + .then(validateExpiry(token)) + .then(validateIssuer(token)) + .then(validateAudience(token)); } private Mono validateAlgorithm(Token token) { @@ -70,9 +72,9 @@ class ReactiveTokenValidator { private Mono validateKeyIdAndSignature(Token token) { return getTokenKey(token).filter((tokenKey) -> hasValidSignature(token, tokenKey)) - .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, - "RSA Signature did not match content"))) - .then(); + .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_SIGNATURE, + "RSA Signature did not match content"))) + .then(); } private Mono getTokenKey(Token token) { @@ -81,10 +83,12 @@ class ReactiveTokenValidator { if (cached != null) { return Mono.just(cached); } - return this.securityService.fetchTokenKeys().doOnSuccess(this::cacheTokenKeys) - .filter((tokenKeys) -> tokenKeys.containsKey(keyId)).map((tokenKeys) -> tokenKeys.get(keyId)) - .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, - "Key Id present in token header does not match"))); + return this.securityService.fetchTokenKeys() + .doOnSuccess(this::cacheTokenKeys) + .filter((tokenKeys) -> tokenKeys.containsKey(keyId)) + .map((tokenKeys) -> tokenKeys.get(keyId)) + .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, + "Key Id present in token header does not match"))); } private void cacheTokenKeys(Map tokenKeys) { @@ -122,11 +126,12 @@ class ReactiveTokenValidator { } private Mono validateIssuer(Token token) { - return this.securityService.getUaaUrl().map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl)) - .filter((issuerUri) -> issuerUri.equals(token.getIssuer())) - .switchIfEmpty(Mono.error( - new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match"))) - .then(); + return this.securityService.getUaaUrl() + .map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl)) + .filter((issuerUri) -> issuerUri.equals(token.getIssuer())) + .switchIfEmpty(Mono + .error(new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match"))) + .then(); } private Mono validateAudience(Token token) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java index cf588469dd..15fb1fcecd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -100,9 +100,9 @@ public class CloudFoundryActuatorAutoConfiguration { public CloudFoundryInfoEndpointWebExtension cloudFoundryInfoEndpointWebExtension(GitProperties properties, ObjectProvider infoContributors) { List contributors = infoContributors.orderedStream() - .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) - ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) - .toList(); + .map((infoContributor) -> (infoContributor instanceof GitInfoContributor) + ? new GitInfoContributor(properties, InfoPropertiesInfoContributor.Mode.FULL) : infoContributor) + .toList(); return new CloudFoundryInfoEndpointWebExtension(new InfoEndpoint(contributors)); } @@ -147,8 +147,8 @@ public class CloudFoundryActuatorAutoConfiguration { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - corsConfiguration.setAllowedHeaders( - Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); + corsConfiguration + .setAllowedHeaders(Arrays.asList(HttpHeaders.AUTHORIZATION, "X-Cf-App-Instance", HttpHeaders.CONTENT_TYPE)); return corsConfiguration; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java index abc0dd76aa..4513c7ad3d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -94,7 +94,7 @@ class CloudFoundryWebEndpointServletHandlerMapping extends AbstractWebMvcEndpoin @Reflective public Map> links(HttpServletRequest request, HttpServletResponse response) { SecurityResponse securityResponse = CloudFoundryWebEndpointServletHandlerMapping.this.securityInterceptor - .preHandle(request, null); + .preHandle(request, null); if (!securityResponse.getStatus().equals(HttpStatus.OK)) { sendFailureResponse(response, securityResponse); } @@ -104,10 +104,11 @@ class CloudFoundryWebEndpointServletHandlerMapping extends AbstractWebMvcEndpoin return Collections.singletonMap("_links", filteredLinks); } Map links = CloudFoundryWebEndpointServletHandlerMapping.this.linksResolver - .resolveLinks(request.getRequestURL().toString()); - filteredLinks = links.entrySet().stream() - .filter((e) -> e.getKey().equals("self") || accessLevel.isAccessAllowed(e.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + .resolveLinks(request.getRequestURL().toString()); + filteredLinks = links.entrySet() + .stream() + .filter((e) -> e.getKey().equals("self") || accessLevel.isAccessAllowed(e.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return Collections.singletonMap("_links", filteredLinks); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java index dafecbe57e..4478b0ed94 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class OnAvailableEndpointCondition extends SpringBootCondition { public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); MergedAnnotation conditionAnnotation = metadata.getAnnotations() - .get(ConditionalOnAvailableEndpoint.class); + .get(ConditionalOnAvailableEndpoint.class); Class target = getTarget(context, metadata, conditionAnnotation); MergedAnnotation endpointAnnotation = getEndpointAnnotation(target); return getMatchOutcome(environment, conditionAnnotation, endpointAnnotation); @@ -134,8 +134,8 @@ class OnAvailableEndpointCondition extends SpringBootCondition { } Boolean userDefinedDefault = isEnabledByDefault(environment); if (userDefinedDefault != null) { - return new ConditionOutcome(userDefinedDefault, message.because( - "no property " + key + " found so using user defined default from " + ENABLED_BY_DEFAULT_KEY)); + return new ConditionOutcome(userDefinedDefault, message + .because("no property " + key + " found so using user defined default from " + ENABLED_BY_DEFAULT_KEY)); } boolean endpointDefault = endpointAnnotation.getBoolean("enableByDefault"); return new ConditionOutcome(endpointDefault, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfiguration.java index 14ec5bfccf..9a409fa55d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,9 +45,10 @@ public class JacksonEndpointAutoConfiguration { @ConditionalOnClass({ ObjectMapper.class, Jackson2ObjectMapperBuilder.class }) public EndpointObjectMapper endpointObjectMapper() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() - .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, - SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) - .serializationInclusion(Include.NON_NULL).build(); + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, + SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) + .serializationInclusion(Include.NON_NULL) + .build(); return () -> objectMapper; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java index eac4b9403c..23c18f400d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -89,7 +89,7 @@ class DefaultEndpointObjectNameFactory implements EndpointObjectNameFactory { } StringBuilder builder = new StringBuilder(); this.properties.getStaticNames() - .forEach((name, value) -> builder.append(",").append(name).append("=").append(value)); + .forEach((name, value) -> builder.append(",").append(name).append("=").append(value)); return builder.toString(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java index faaf723127..84c39eade7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -101,7 +101,9 @@ class JerseyWebEndpointManagementContextConfiguration { WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups healthEndpointGroups) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HEALTH_ENDPOINT_ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HEALTH_ENDPOINT_ID)) + .findFirst() + .get(); return new JerseyAdditionalHealthEndpointPathsManagementResourcesRegistrar(health, healthEndpointGroups); } @@ -195,8 +197,10 @@ class JerseyWebEndpointManagementContextConfiguration { JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.MANAGEMENT, this.groups); Collection endpointResources = resourceFactory - .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) - .stream().filter(Objects::nonNull).toList(); + .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) + .stream() + .filter(Objects::nonNull) + .toList(); register(endpointResources, config); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java index b94f19ad39..9e117dd3b7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/reactive/WebFluxEndpointManagementContextConfiguration.java @@ -118,7 +118,9 @@ public class WebFluxEndpointManagementContextConfiguration { WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups groups) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); return new AdditionalHealthEndpointPathsWebFluxHandlerMapping(new EndpointMapping(""), health, groups.getAllWithAdditionalPath(WebServerNamespace.MANAGEMENT)); } @@ -149,7 +151,7 @@ public class WebFluxEndpointManagementContextConfiguration { static class ServerCodecConfigurerEndpointObjectMapperBeanPostProcessor implements BeanPostProcessor { private static final List MEDIA_TYPES = Collections - .unmodifiableList(Arrays.asList(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"))); + .unmodifiableList(Arrays.asList(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"))); private final Supplier endpointObjectMapper; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java index 07d507aaab..f271c663ab 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/servlet/WebMvcEndpointManagementContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -113,7 +113,9 @@ public class WebMvcEndpointManagementContextConfiguration { WebEndpointsSupplier webEndpointsSupplier, HealthEndpointGroups groups) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); return new AdditionalHealthEndpointPathsWebMvcHandlerMapping(health, groups.getAllWithAdditionalPath(WebServerNamespace.MANAGEMENT)); } @@ -144,7 +146,7 @@ public class WebMvcEndpointManagementContextConfiguration { static class EndpointObjectMapperWebMvcConfigurer implements WebMvcConfigurer { private static final List MEDIA_TYPES = Collections - .unmodifiableList(Arrays.asList(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"))); + .unmodifiableList(Arrays.asList(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"))); private final EndpointObjectMapper endpointObjectMapper; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfiguration.java index 1628446456..5a7454b08a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -93,7 +93,7 @@ public abstract class AbstractCompositeHealthContributorConfiguration webEndpoints = webEndpointsSupplier.getEndpoints(); ExposableWebEndpoint health = webEndpoints.stream() - .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)).findFirst().get(); + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); return new AdditionalHealthEndpointPathsWebFluxHandlerMapping(new EndpointMapping(""), health, groups.getAllWithAdditionalPath(WebServerNamespace.SERVER)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java index e81fbad461..6a027585c7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointWebExtensionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,8 +78,10 @@ class HealthEndpointWebExtensionConfiguration { private static ExposableWebEndpoint getHealthEndpoint(WebEndpointsSupplier webEndpointsSupplier) { Collection webEndpoints = webEndpointsSupplier.getEndpoints(); - return webEndpoints.stream().filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) - .findFirst().get(); + return webEndpoints.stream() + .filter((endpoint) -> endpoint.getEndpointId().equals(HealthEndpoint.ID)) + .findFirst() + .get(); } @ConditionalOnBean(DispatcherServlet.class) @@ -160,8 +162,10 @@ class HealthEndpointWebExtensionConfiguration { JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.SERVER, this.groups); Collection endpointResources = resourceFactory - .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) - .stream().filter(Objects::nonNull).toList(); + .createEndpointResources(mapping, Collections.singletonList(this.endpoint), null, null, false) + .stream() + .filter(Objects::nonNull) + .toList(); register(endpointResources, config); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java index a36a2f9d65..f13af4a67b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/info/OnEnabledInfoContributorCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class OnEnabledInfoContributorCondition extends OnEndpointElementCondition { InfoContributorFallback fallback = annotationAttributes.getEnum("fallback"); if (fallback == InfoContributorFallback.DISABLE) { return new ConditionOutcome(false, ConditionMessage.forCondition(ConditionalOnEnabledInfoContributor.class) - .because("management.info." + annotationAttributes.getString("value") + ".enabled is not true")); + .because("management.info." + annotationAttributes.getString("value") + ".enabled is not true")); } return super.getDefaultOutcome(context, annotationAttributes); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java index 9abf74c1af..966296cd00 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -86,9 +86,10 @@ public class DataSourceHealthContributorAutoConfiguration implements Initializin public HealthContributor dbHealthContributor(Map dataSources, DataSourceHealthIndicatorProperties dataSourceHealthIndicatorProperties) { if (dataSourceHealthIndicatorProperties.isIgnoreRoutingDataSources()) { - Map filteredDatasources = dataSources.entrySet().stream() - .filter((e) -> !(e.getValue() instanceof AbstractRoutingDataSource)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Map filteredDatasources = dataSources.entrySet() + .stream() + .filter((e) -> !(e.getValue() instanceof AbstractRoutingDataSource)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return createContributor(filteredDatasources); } return createContributor(dataSources); @@ -127,9 +128,11 @@ public class DataSourceHealthContributorAutoConfiguration implements Initializin RoutingDataSourceHealthContributor(AbstractRoutingDataSource routingDataSource, Function contributorFunction) { - Map routedDataSources = routingDataSource.getResolvedDataSources().entrySet().stream() - .collect(Collectors.toMap((e) -> Objects.toString(e.getKey(), UNNAMED_DATASOURCE_KEY), - Map.Entry::getValue)); + Map routedDataSources = routingDataSource.getResolvedDataSources() + .entrySet() + .stream() + .collect(Collectors.toMap((e) -> Objects.toString(e.getKey(), UNNAMED_DATASOURCE_KEY), + Map.Entry::getValue)); this.delegate = CompositeHealthContributor.fromMap(routedDataSources, contributorFunction); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java index af4296bb9e..a803aba296 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,8 +59,8 @@ public class LoggersEndpointAutoConfiguration { ConditionMessage.Builder message = ConditionMessage.forCondition("Logging System"); String loggingSystem = System.getProperty(LoggingSystem.SYSTEM_PROPERTY); if (LoggingSystem.NONE.equals(loggingSystem)) { - return ConditionOutcome.noMatch( - message.because("system property " + LoggingSystem.SYSTEM_PROPERTY + " is set to none")); + return ConditionOutcome + .noMatch(message.because("system property " + LoggingSystem.SYSTEM_PROPERTY + " is set to none")); } return ConditionOutcome.match(message.because("enabled")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java index d2039e0466..9da1b3aef5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,14 +60,14 @@ public class Log4J2MetricsAutoConfiguration { try { if (Class.forName("org.apache.logging.log4j.core.LoggerContext").isInstance(loggerContext)) { return ConditionOutcome - .match("LoggerContext was an instance of org.apache.logging.log4j.core.LoggerContext"); + .match("LoggerContext was an instance of org.apache.logging.log4j.core.LoggerContext"); } } catch (Throwable ex) { // Continue with no match } return ConditionOutcome - .noMatch("Logger context was not an instance of org.apache.logging.log4j.core.LoggerContext"); + .noMatch("Logger context was not an instance of org.apache.logging.log4j.core.LoggerContext"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java index b554a4b12b..06a0789ec6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -108,8 +108,8 @@ class MeterRegistryPostProcessor implements BeanPostProcessor, SmartInitializing private void applyCustomizers(MeterRegistry meterRegistry) { List> customizers = this.customizers.orderedStream().toList(); LambdaSafe.callbacks(MeterRegistryCustomizer.class, customizers, meterRegistry) - .withLogger(MeterRegistryPostProcessor.class) - .invoke((customizer) -> customizer.customize(meterRegistry)); + .withLogger(MeterRegistryPostProcessor.class) + .invoke((customizer) -> customizer.customize(meterRegistry)); } private void applyFilters(MeterRegistry meterRegistry) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesAutoTimer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesAutoTimer.java index 0269c0bbba..7255ff0324 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesAutoTimer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesAutoTimer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ public class PropertiesAutoTimer implements AutoTimer { @Override public void apply(Builder builder) { builder.publishPercentileHistogram(this.properties.isPercentilesHistogram()) - .publishPercentiles(this.properties.getPercentiles()); + .publishPercentiles(this.properties.getPercentiles()); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java index da6dc9ca14..bf50675647 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,24 +84,29 @@ public class PropertiesMeterFilter implements MeterFilter { public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) { Distribution distribution = this.properties.getDistribution(); return DistributionStatisticConfig.builder() - .percentilesHistogram(lookupWithFallbackToAll(distribution.getPercentilesHistogram(), id, null)) - .percentiles(lookupWithFallbackToAll(distribution.getPercentiles(), id, null)) - .serviceLevelObjectives( - convertServiceLevelObjectives(id.getType(), lookup(distribution.getSlo(), id, null))) - .minimumExpectedValue( - convertMeterValue(id.getType(), lookup(distribution.getMinimumExpectedValue(), id, null))) - .maximumExpectedValue( - convertMeterValue(id.getType(), lookup(distribution.getMaximumExpectedValue(), id, null))) - .expiry(lookupWithFallbackToAll(distribution.getExpiry(), id, null)) - .bufferLength(lookupWithFallbackToAll(distribution.getBufferLength(), id, null)).build().merge(config); + .percentilesHistogram(lookupWithFallbackToAll(distribution.getPercentilesHistogram(), id, null)) + .percentiles(lookupWithFallbackToAll(distribution.getPercentiles(), id, null)) + .serviceLevelObjectives( + convertServiceLevelObjectives(id.getType(), lookup(distribution.getSlo(), id, null))) + .minimumExpectedValue( + convertMeterValue(id.getType(), lookup(distribution.getMinimumExpectedValue(), id, null))) + .maximumExpectedValue( + convertMeterValue(id.getType(), lookup(distribution.getMaximumExpectedValue(), id, null))) + .expiry(lookupWithFallbackToAll(distribution.getExpiry(), id, null)) + .bufferLength(lookupWithFallbackToAll(distribution.getBufferLength(), id, null)) + .build() + .merge(config); } private double[] convertServiceLevelObjectives(Meter.Type meterType, ServiceLevelObjectiveBoundary[] slo) { if (slo == null) { return null; } - double[] converted = Arrays.stream(slo).map((candidate) -> candidate.getValue(meterType)) - .filter(Objects::nonNull).mapToDouble(Double::doubleValue).toArray(); + double[] converted = Arrays.stream(slo) + .map((candidate) -> candidate.getValue(meterType)) + .filter(Objects::nonNull) + .mapToDouble(Double::doubleValue) + .toArray(); return (converted.length != 0) ? converted : null; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java index 9c074c77da..be54d5baf7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsRegistrarConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class CacheMetricsRegistrarConfiguration { private void bindCacheManagerToRegistry(String beanName, CacheManager cacheManager) { cacheManager.getCacheNames() - .forEach((cacheName) -> bindCacheToRegistry(beanName, cacheManager.getCache(cacheName))); + .forEach((cacheName) -> bindCacheToRegistry(beanName, cacheManager.getCache(cacheName))); } private void bindCacheToRegistry(String beanName, Cache cache) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/OnMetricsExportEnabledCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/OnMetricsExportEnabledCondition.java index ad568a4998..9c5f70bf54 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/OnMetricsExportEnabledCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/OnMetricsExportEnabledCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,7 +40,7 @@ class OnMetricsExportEnabledCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ConditionalOnEnabledMetricsExport.class.getName())); + .fromMap(metadata.getAnnotationAttributes(ConditionalOnEnabledMetricsExport.class.getName())); String endpointName = annotationAttributes.getString("value"); ConditionOutcome outcome = getProductOutcome(context, endpointName); if (outcome != null) { @@ -55,7 +55,7 @@ class OnMetricsExportEnabledCondition extends SpringBootCondition { if (environment.containsProperty(enabledProperty)) { boolean match = environment.getProperty(enabledProperty, Boolean.class, true); return new ConditionOutcome(match, ConditionMessage.forCondition(ConditionalOnEnabledMetricsExport.class) - .because(enabledProperty + " is " + match)); + .because(enabledProperty + " is " + match)); } return null; } @@ -70,7 +70,7 @@ class OnMetricsExportEnabledCondition extends SpringBootCondition { private ConditionOutcome getDefaultOutcome(ConditionContext context) { boolean match = Boolean.parseBoolean(context.getEnvironment().getProperty(DEFAULT_PROPERTY_NAME, "true")); return new ConditionOutcome(match, ConditionMessage.forCondition(ConditionalOnEnabledMetricsExport.class) - .because(DEFAULT_PROPERTY_NAME + " is considered " + match)); + .because(DEFAULT_PROPERTY_NAME + " is considered " + match)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java index 52359430ec..45188b5cc5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,9 +64,11 @@ public class AppOpticsMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public AppOpticsMeterRegistry appOpticsMeterRegistry(AppOpticsConfig config, Clock clock) { - return AppOpticsMeterRegistry.builder(config).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return AppOpticsMeterRegistry.builder(config) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java index 9d48d4cd57..463eba9422 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,9 +64,11 @@ public class DatadogMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public DatadogMeterRegistry datadogMeterRegistry(DatadogConfig datadogConfig, Clock clock) { - return DatadogMeterRegistry.builder(datadogConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return DatadogMeterRegistry.builder(datadogConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java index 47a144ddde..60c57d2acc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,9 +64,11 @@ public class DynatraceMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public DynatraceMeterRegistry dynatraceMeterRegistry(DynatraceConfig dynatraceConfig, Clock clock) { - return DynatraceMeterRegistry.builder(dynatraceConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return DynatraceMeterRegistry.builder(dynatraceConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java index 3363b4fa40..8040723791 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,9 +73,11 @@ public class ElasticMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public ElasticMeterRegistry elasticMeterRegistry(ElasticConfig elasticConfig, Clock clock) { - return ElasticMeterRegistry.builder(elasticConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return ElasticMeterRegistry.builder(elasticConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java index a208ee7378..afa4f9ebde 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,9 +64,11 @@ public class HumioMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public HumioMeterRegistry humioMeterRegistry(HumioConfig humioConfig, Clock clock) { - return HumioMeterRegistry.builder(humioConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return HumioMeterRegistry.builder(humioConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java index daec199473..3615f0d143 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,9 +64,11 @@ public class InfluxMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public InfluxMeterRegistry influxMeterRegistry(InfluxConfig influxConfig, Clock clock) { - return InfluxMeterRegistry.builder(influxConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return InfluxMeterRegistry.builder(influxConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java index 9378a6dc50..8e079fb9a4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,9 +64,11 @@ public class KairosMetricsExportAutoConfiguration { @Bean @ConditionalOnMissingBean public KairosMeterRegistry kairosMeterRegistry(KairosConfig kairosConfig, Clock clock) { - return KairosMeterRegistry.builder(kairosConfig).clock(clock).httpClient( - new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) - .build(); + return KairosMeterRegistry.builder(kairosConfig) + .clock(clock) + .httpClient( + new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())) + .build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java index 694eedfacf..e65f922883 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -81,8 +81,10 @@ public class NewRelicMetricsExportAutoConfiguration { @ConditionalOnMissingBean public NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, Clock clock, NewRelicClientProvider newRelicClientProvider) { - return NewRelicMeterRegistry.builder(newRelicConfig).clock(clock).clientProvider(newRelicClientProvider) - .build(); + return NewRelicMeterRegistry.builder(newRelicConfig) + .clock(clock) + .clientProvider(newRelicClientProvider) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java index a64dc7fcd6..dfa11f953d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -95,7 +95,7 @@ public class DataSourcePoolMetricsAutoConfiguration { Collection metadataProviders, MeterRegistry registry) { String dataSourceName = getDataSourceName(beanName); new DataSourcePoolMetrics(dataSource, metadataProviders, dataSourceName, Collections.emptyList()) - .bindTo(registry); + .bindTo(registry); } /** diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java index 1e448b46f0..e900d07674 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -98,8 +98,8 @@ public class MongoMetricsAutoConfiguration { MongoClientSettingsBuilderCustomizer mongoMetricsConnectionPoolListenerClientSettingsBuilderCustomizer( MongoMetricsConnectionPoolListener mongoMetricsConnectionPoolListener) { return (clientSettingsBuilder) -> clientSettingsBuilder - .applyToConnectionPoolSettings((connectionPoolSettingsBuilder) -> connectionPoolSettingsBuilder - .addConnectionPoolListener(mongoMetricsConnectionPoolListener)); + .applyToConnectionPoolSettings((connectionPoolSettingsBuilder) -> connectionPoolSettingsBuilder + .addConnectionPoolListener(mongoMetricsConnectionPoolListener)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java index 0d96bace0f..9de4febb50 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,7 +78,8 @@ public class HibernateMetricsAutoConfiguration implements SmartInitializingSingl String entityManagerFactoryName = getEntityManagerFactoryName(beanName); try { new HibernateMetrics(entityManagerFactory.unwrap(SessionFactory.class), entityManagerFactoryName, - Collections.emptyList()).bindTo(registry); + Collections.emptyList()) + .bindTo(registry); } catch (PersistenceException ex) { // Continue diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurer.java index f14ea34618..f6a325a476 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurer.java @@ -93,7 +93,8 @@ class ObservationRegistryConfigurer { @SuppressWarnings("unchecked") private void customize(ObservationRegistry registry) { LambdaSafe.callbacks(ObservationRegistryCustomizer.class, asOrderedList(this.customizers), registry) - .withLogger(ObservationRegistryConfigurer.class).invoke((customizer) -> customizer.customize(registry)); + .withLogger(ObservationRegistryConfigurer.class) + .invoke((customizer) -> customizer.customize(registry)); } private List asOrderedList(ObjectProvider provider) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/HttpClientObservationsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/HttpClientObservationsAutoConfiguration.java index 8886d48b45..23323d2523 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/HttpClientObservationsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/HttpClientObservationsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -74,7 +74,7 @@ public class HttpClientObservationsAutoConfiguration { String name = (observationName != null) ? observationName : metricName; MeterFilter denyFilter = new OnlyOnceLoggingDenyMeterFilter( () -> "Reached the maximum number of URI tags for '%s'. Are you using 'uriVariables'?" - .formatted(name)); + .formatted(name)); return MeterFilter.maximumAllowableTags(name, "uri", clientProperties.getMaxUriTags(), denyFilter); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java index f2fcfda66c..050613f1fc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java @@ -246,8 +246,10 @@ public final class EndpointRequest { } private String toString(List endpoints, String emptyValue) { - return (!endpoints.isEmpty()) ? endpoints.stream().map(this::getEndpointId).map(Object::toString) - .collect(Collectors.joining(", ", "[", "]")) : emptyValue; + return (!endpoints.isEmpty()) ? endpoints.stream() + .map(this::getEndpointId) + .map(Object::toString) + .collect(Collectors.joining(", ", "[", "]")) : emptyValue; } private EndpointId getEndpointId(Object source) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java index 6a100f925d..2317c4269b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java @@ -250,8 +250,9 @@ public final class EndpointRequest { private List getDelegateMatchers(RequestMatcherFactory requestMatcherFactory, RequestMatcherProvider matcherProvider, Set paths) { - return paths.stream().map((path) -> requestMatcherFactory.antPath(matcherProvider, path, "/**")) - .collect(Collectors.toCollection(ArrayList::new)); + return paths.stream() + .map((path) -> requestMatcherFactory.antPath(matcherProvider, path, "/**")) + .collect(Collectors.toCollection(ArrayList::new)); } @Override @@ -261,8 +262,10 @@ public final class EndpointRequest { } private String toString(List endpoints, String emptyValue) { - return (!endpoints.isEmpty()) ? endpoints.stream().map(this::getEndpointId).map(Object::toString) - .collect(Collectors.joining(", ", "[", "]")) : emptyValue; + return (!endpoints.isEmpty()) ? endpoints.stream() + .map(this::getEndpointId) + .map(Object::toString) + .collect(Collectors.joining(", ", "[", "]")) : emptyValue; } private EndpointId getEndpointId(Object source) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java index 5f91740a9e..4871ee6d9f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,8 +62,8 @@ public class StartupEndpointAutoConfiguration { ConditionMessage.Builder message = ConditionMessage.forCondition("ApplicationStartup"); ApplicationStartup applicationStartup = context.getBeanFactory().getApplicationStartup(); if (applicationStartup instanceof BufferingApplicationStartup) { - return ConditionOutcome.match( - message.because("configured applicationStartup is of type BufferingApplicationStartup.")); + return ConditionOutcome + .match(message.because("configured applicationStartup is of type BufferingApplicationStartup.")); } return ConditionOutcome.noMatch(message.because("configured applicationStartup is of type " + applicationStartup.getClass() + ", expected BufferingApplicationStartup.")); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfiguration.java index d02b040d8f..8deaf835ff 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -101,9 +101,13 @@ public class BraveAutoConfiguration { List tracingCustomizers, CurrentTraceContext currentTraceContext, Factory propagationFactory, Sampler sampler) { String applicationName = environment.getProperty("spring.application.name", DEFAULT_APPLICATION_NAME); - Builder builder = Tracing.newBuilder().currentTraceContext(currentTraceContext).traceId128Bit(true) - .supportsJoin(false).propagationFactory(propagationFactory).sampler(sampler) - .localServiceName(applicationName); + Builder builder = Tracing.newBuilder() + .currentTraceContext(currentTraceContext) + .traceId128Bit(true) + .supportsJoin(false) + .propagationFactory(propagationFactory) + .sampler(sampler) + .localServiceName(applicationName); spanHandlers.forEach(builder::addSpanHandler); for (TracingCustomizer tracingCustomizer : tracingCustomizers) { tracingCustomizer.customize(builder); @@ -234,7 +238,8 @@ public class BraveAutoConfiguration { List correlationFields = this.tracingProperties.getBaggage().getCorrelation().getFields(); for (String field : correlationFields) { builder.add(CorrelationScopeConfig.SingleCorrelationField.newBuilder(BaggageField.create(field)) - .flushOnUpdate().build()); + .flushOnUpdate() + .build()); } }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfiguration.java index 2c5a8b85c8..6c2ba9cc6b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -88,8 +88,10 @@ public class OpenTelemetryAutoConfiguration { @Bean @ConditionalOnMissingBean OpenTelemetry openTelemetry(SdkTracerProvider sdkTracerProvider, ContextPropagators contextPropagators) { - return OpenTelemetrySdk.builder().setTracerProvider(sdkTracerProvider).setPropagators(contextPropagators) - .build(); + return OpenTelemetrySdk.builder() + .setTracerProvider(sdkTracerProvider) + .setPropagators(contextPropagators) + .build(); } @Bean @@ -97,8 +99,9 @@ public class OpenTelemetryAutoConfiguration { SdkTracerProvider otelSdkTracerProvider(Environment environment, ObjectProvider spanProcessors, Sampler sampler) { String applicationName = environment.getProperty("spring.application.name", DEFAULT_APPLICATION_NAME); - SdkTracerProviderBuilder builder = SdkTracerProvider.builder().setSampler(sampler) - .setResource(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, applicationName))); + SdkTracerProviderBuilder builder = SdkTracerProvider.builder() + .setSampler(sampler) + .setResource(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, applicationName))); spanProcessors.orderedStream().forEach(builder::addSpanProcessor); return builder.build(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurations.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurations.java index b3ba5d2d3e..f61d4ce2d9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurations.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,7 +79,8 @@ class ZipkinConfigurations { ZipkinRestTemplateSender restTemplateSender(ZipkinProperties properties, ObjectProvider customizers) { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder() - .setConnectTimeout(properties.getConnectTimeout()).setReadTimeout(properties.getReadTimeout()); + .setConnectTimeout(properties.getConnectTimeout()) + .setReadTimeout(properties.getReadTimeout()); restTemplateBuilder = applyCustomizers(restTemplateBuilder, customizers); return new ZipkinRestTemplateSender(properties.getEndpoint(), restTemplateBuilder.build()); } @@ -87,7 +88,7 @@ class ZipkinConfigurations { private RestTemplateBuilder applyCustomizers(RestTemplateBuilder restTemplateBuilder, ObjectProvider customizers) { Iterable orderedCustomizers = () -> customizers.orderedStream() - .iterator(); + .iterator(); RestTemplateBuilder currentBuilder = restTemplateBuilder; for (ZipkinRestTemplateBuilderCustomizer customizer : orderedCustomizers) { currentBuilder = customizer.customize(currentBuilder); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSender.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSender.java index 31ab6f5f75..b9992bd575 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSender.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSender.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -74,8 +74,12 @@ class ZipkinWebClientSender extends HttpSender { } private Mono> sendRequest() { - return this.webClient.post().uri(this.endpoint).headers(this::addDefaultHeaders).bodyValue(getBody()) - .retrieve().toBodilessEntity(); + return this.webClient.post() + .uri(this.endpoint) + .headers(this::addDefaultHeaders) + .bodyValue(getBody()) + .retrieve() + .toBodilessEntity(); } private void addDefaultHeaders(HttpHeaders headers) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java index bbefe35b7b..0871218563 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,12 +59,12 @@ public final class ManagementContextFactory { public ConfigurableApplicationContext createManagementContext(ApplicationContext parentContext) { Environment parentEnvironment = parentContext.getEnvironment(); ConfigurableEnvironment childEnvironment = ApplicationContextFactory.DEFAULT - .createEnvironment(this.webApplicationType); + .createEnvironment(this.webApplicationType); if (parentEnvironment instanceof ConfigurableEnvironment) { childEnvironment.setConversionService(((ConfigurableEnvironment) parentEnvironment).getConversionService()); } ConfigurableApplicationContext managementContext = ApplicationContextFactory.DEFAULT - .create(this.webApplicationType); + .create(this.webApplicationType); managementContext.setEnvironment(childEnvironment); managementContext.setParent(parentContext); return managementContext; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java index f560a145d8..a4d423dfce 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -121,7 +121,7 @@ class ChildManagementContextInitializer protected final ConfigurableApplicationContext createManagementContext() { ConfigurableApplicationContext managementContext = this.managementContextFactory - .createManagementContext(this.parentContext); + .createManagementContext(this.parentContext); managementContext.setId(this.parentContext.getId() + ":management"); if (managementContext instanceof ConfigurableWebServerApplicationContext webServerApplicationContext) { webServerApplicationContext.setServerNamespace("management"); @@ -162,9 +162,10 @@ class ChildManagementContextInitializer public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { GenerationContext managementGenerationContext = generationContext.withName("Management"); ClassName generatedInitializerClassName = new ApplicationContextAotGenerator() - .processAheadOfTime(this.managementContext, managementGenerationContext); - GeneratedMethod postProcessorMethod = beanRegistrationCode.getMethods().add("addManagementInitializer", - (method) -> method.addJavadoc("Use AOT management context initialization") + .processAheadOfTime(this.managementContext, managementGenerationContext); + GeneratedMethod postProcessorMethod = beanRegistrationCode.getMethods() + .add("addManagementInitializer", + (method) -> method.addJavadoc("Use AOT management context initialization") .addModifiers(Modifier.PRIVATE, Modifier.STATIC) .addParameter(RegisteredBean.class, "registeredBean") .addParameter(ChildManagementContextInitializer.class, "instance") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java index 107a5b71b5..87434fe6f3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,8 @@ class ManagementContextConfigurationImportSelector implements DeferredImportSele @Override public String[] selectImports(AnnotationMetadata metadata) { ManagementContextType contextType = (ManagementContextType) metadata - .getAnnotationAttributes(EnableManagementContext.class.getName()).get("value"); + .getAnnotationAttributes(EnableManagementContext.class.getName()) + .get("value"); // Find all management context configuration classes, filtering duplicates List configurations = getConfigurations(); OrderComparator.sort(configurations); @@ -118,7 +119,7 @@ class ManagementContextConfigurationImportSelector implements DeferredImportSele private ManagementContextType readContextType(AnnotationMetadata annotationMetadata) { Map annotationAttributes = annotationMetadata - .getAnnotationAttributes(ManagementContextConfiguration.class.getName()); + .getAnnotationAttributes(ManagementContextConfiguration.class.getName()); return (annotationAttributes != null) ? (ManagementContextType) annotationAttributes.get("value") : ManagementContextType.ANY; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java index 3f3817f6cf..0e1746e3e6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,7 +62,7 @@ public abstract class ManagementWebServerFactoryCustomizer> customizers) { LambdaSafe.callbacks(WebServerFactoryCustomizer.class, customizers, factory) - .invoke((customizer) -> customizer.customize(factory)); + .invoke((customizer) -> customizer.customize(factory)); } protected void customize(T factory, ManagementServerProperties managementServerProperties, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java index 077a6b9ee6..4cdee48ddc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/OnManagementPortCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -49,10 +49,10 @@ class OnManagementPortCondition extends SpringBootCondition { ManagementPortType actualType = ManagementPortType.get(context.getEnvironment()); if (actualType == requiredType) { return ConditionOutcome - .match(message.because("actual port type (" + actualType + ") matched required type")); + .match(message.because("actual port type (" + actualType + ") matched required type")); } return ConditionOutcome.noMatch(message - .because("actual port type (" + actualType + ") did not match required type (" + requiredType + ")")); + .because("actual port type (" + actualType + ") did not match required type (" + requiredType + ")")); } private boolean isWebApplicationContext(ConditionContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java index c8be2de457..44de3225ef 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/servlet/ServletManagementChildContextConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -111,8 +111,8 @@ class ServletManagementChildContextConfiguration { @Bean @ConditionalOnBean(name = "securityFilterChainRegistration", search = SearchStrategy.ANCESTORS) DelegatingFilterProxyRegistrationBean securityFilterChainRegistration(HierarchicalBeanFactory beanFactory) { - return beanFactory.getParentBeanFactory().getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); + return beanFactory.getParentBeanFactory() + .getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java index e642c1015f..fc77d4c095 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/amqp/RabbitHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,8 +34,8 @@ import static org.assertj.core.api.Assertions.assertThat; class RabbitHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, - RabbitHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, + RabbitHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -45,7 +45,7 @@ class RabbitHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.rabbit.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RabbitHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java index 3a805235f8..91a2ef449b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AuditAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class)); @Test void autoConfigurationIsDisabledByDefault() { @@ -66,34 +66,34 @@ class AuditAutoConfigurationTests { @Test void ownAuthenticationAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class) - .run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class)) - .isInstanceOf(TestAuthenticationAuditListener.class)); + .withUserConfiguration(CustomAuthenticationAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuthenticationAuditListener.class)) + .isInstanceOf(TestAuthenticationAuditListener.class)); } @Test void ownAuthorizationAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class) - .run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class)) - .isInstanceOf(TestAuthorizationAuditListener.class)); + .withUserConfiguration(CustomAuthorizationAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuthorizationAuditListener.class)) + .isInstanceOf(TestAuthorizationAuditListener.class)); } @Test void ownAuditListener() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withUserConfiguration(CustomAuditListenerConfiguration.class) - .run((context) -> assertThat(context.getBean(AbstractAuditListener.class)) - .isInstanceOf(TestAuditListener.class)); + .withUserConfiguration(CustomAuditListenerConfiguration.class) + .run((context) -> assertThat(context.getBean(AbstractAuditListener.class)) + .isInstanceOf(TestAuditListener.class)); } @Test void backsOffWhenDisabled() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withPropertyValues("management.auditevents.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class) - .doesNotHaveBean(AuthenticationAuditListener.class) - .doesNotHaveBean(AuthorizationAuditListener.class)); + .withPropertyValues("management.auditevents.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AuditListener.class) + .doesNotHaveBean(AuthenticationAuditListener.class) + .doesNotHaveBean(AuthorizationAuditListener.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java index cefd0f6e10..8e1e14712a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/audit/AuditEventsEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,14 +42,14 @@ class AuditEventsEndpointAutoConfigurationTests { @Test void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=auditevents") - .run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=auditevents") + .run((context) -> assertThat(context).hasSingleBean(AuditEventsEndpoint.class)); } @Test void endpointBacksOffWhenRepositoryNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=auditevents") - .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Test @@ -60,9 +60,9 @@ class AuditEventsEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpoint() { this.contextRunner.withUserConfiguration(CustomAuditEventRepositoryConfiguration.class) - .withPropertyValues("management.endpoint.auditevents.enabled:false") - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); + .withPropertyValues("management.endpoint.auditevents.enabled:false") + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> assertThat(context).doesNotHaveBean(AuditEventsEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java index dce124c765..8b65242246 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -35,30 +35,30 @@ import static org.assertj.core.api.Assertions.assertThat; class AvailabilityHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, - AvailabilityHealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, + AvailabilityHealthContributorAutoConfiguration.class)); @Test void probesWhenNotKubernetesAddsNoBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class)); + .doesNotHaveBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class)); } @Test void livenessIndicatorWhenPropertyEnabledAddsBeans() { this.contextRunner.withPropertyValues("management.health.livenessState.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class)); } @Test void readinessIndicatorWhenPropertyEnabledAddsBeans() { this.contextRunner.withPropertyValues("management.health.readinessState.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(ReadinessStateHealthIndicator.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(ReadinessStateHealthIndicator.class) + .doesNotHaveBean(LivenessStateHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java index e5d82ef0c7..7c42682d95 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,44 +35,48 @@ import static org.assertj.core.api.Assertions.assertThat; class AvailabilityProbesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, - AvailabilityHealthContributorAutoConfiguration.class, AvailabilityProbesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class, + AvailabilityHealthContributorAutoConfiguration.class, AvailabilityProbesAutoConfiguration.class)); @Test void probesWhenNotKubernetesAddsNoBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class) - .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .doesNotHaveBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class) + .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } @Test void probesWhenKubernetesAddsBeans() { this.contextRunner.withPropertyValues("spring.main.cloud-platform=kubernetes") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(LivenessStateHealthIndicator.class).hasBean("livenessStateHealthIndicator") - .hasSingleBean(ReadinessStateHealthIndicator.class).hasBean("readinessStateHealthIndicator") - .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(LivenessStateHealthIndicator.class) + .hasBean("livenessStateHealthIndicator") + .hasSingleBean(ReadinessStateHealthIndicator.class) + .hasBean("readinessStateHealthIndicator") + .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } @Test void probesWhenPropertyEnabledAddsBeans() { this.contextRunner.withPropertyValues("management.endpoint.health.probes.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .hasSingleBean(LivenessStateHealthIndicator.class).hasBean("livenessStateHealthIndicator") - .hasSingleBean(ReadinessStateHealthIndicator.class).hasBean("readinessStateHealthIndicator") - .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .hasSingleBean(LivenessStateHealthIndicator.class) + .hasBean("livenessStateHealthIndicator") + .hasSingleBean(ReadinessStateHealthIndicator.class) + .hasBean("readinessStateHealthIndicator") + .hasSingleBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } @Test void probesWhenKubernetesAndPropertyDisabledAddsNotBeans() { this.contextRunner - .withPropertyValues("spring.main.cloud-platform=kubernetes", - "management.endpoint.health.probes.enabled=false") - .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) - .doesNotHaveBean(LivenessStateHealthIndicator.class) - .doesNotHaveBean(ReadinessStateHealthIndicator.class) - .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); + .withPropertyValues("spring.main.cloud-platform=kubernetes", + "management.endpoint.health.probes.enabled=false") + .run((context) -> assertThat(context).hasSingleBean(ApplicationAvailability.class) + .doesNotHaveBean(LivenessStateHealthIndicator.class) + .doesNotHaveBean(ReadinessStateHealthIndicator.class) + .doesNotHaveBean(AvailabilityProbesHealthEndpointGroupsPostProcessor.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java index d5c5a8b563..b522bec972 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsPostProcessorTests.java @@ -49,7 +49,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessorTests { names.add("liveness"); given(groups.getNames()).willReturn(names); assertThat(this.postProcessor.postProcessHealthEndpointGroups(groups)) - .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); + .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); } @Test @@ -60,7 +60,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessorTests { names.add("readiness"); given(groups.getNames()).willReturn(names); assertThat(this.postProcessor.postProcessHealthEndpointGroups(groups)) - .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); + .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); } @Test @@ -72,7 +72,7 @@ class AvailabilityProbesHealthEndpointGroupsPostProcessorTests { names.add("boot"); given(groups.getNames()).willReturn(names); assertThat(this.postProcessor.postProcessHealthEndpointGroups(groups)) - .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); + .isInstanceOf(AvailabilityProbesHealthEndpointGroups.class); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java index 78e711125d..ae5dfc5384 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/availability/AvailabilityProbesHealthEndpointGroupsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,7 @@ class AvailabilityProbesHealthEndpointGroupsTests { @Test void createWhenGroupsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new AvailabilityProbesHealthEndpointGroups(null, false)) - .withMessage("Groups must not be null"); + .withMessage("Groups must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java index 3f1186b275..e1918e4505 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/beans/BeansEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThat; class BeansEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BeansEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=beans") - .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(BeansEndpoint.class)); } @Test @@ -48,8 +48,8 @@ class BeansEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.beans.enabled:false") - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> assertThat(context).doesNotHaveBean(BeansEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java index 4c02aae4e2..77766f4c3b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cache/CachesEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -36,42 +36,42 @@ import static org.mockito.Mockito.mock; class CachesEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) - .withPropertyValues("management.endpoints.web.exposure.include=caches") - .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=caches") + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test void runWithoutCacheManagerShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=caches") - .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.caches.enabled:false") - .withPropertyValues("management.endpoints.web.exposure.include=*") - .withBean(CacheManager.class, () -> mock(CacheManager.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .withBean(CacheManager.class, () -> mock(CacheManager.class)) + .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=caches") - .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class) - .doesNotHaveBean(CachesEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=caches") + .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class) + .doesNotHaveBean(CachesEndpointWebExtension.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java index fb61aead66..a76c786630 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -38,35 +38,35 @@ import static org.mockito.Mockito.mock; class CassandraHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CassandraHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runWithoutCqlSessionOrCassandraOperationsShouldNotCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") - .doesNotHaveBean(CassandraDriverHealthIndicator.class)); + .doesNotHaveBean(CassandraDriverHealthIndicator.class)); } @Test void runWithCqlSessionOnlyShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); } @Test void runWithCqlSessionAndSpringDataAbsentShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.data")) - .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.data")) + .run((context) -> assertThat(context).hasSingleBean(CassandraDriverHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) - .withPropertyValues("management.health.cassandra.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") - .doesNotHaveBean(CassandraDriverHealthIndicator.class)); + .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) + .withPropertyValues("management.health.cassandra.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") + .doesNotHaveBean(CassandraDriverHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java index e2485c0789..0f85369b4b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cassandra/CassandraReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -40,45 +40,46 @@ import static org.mockito.Mockito.mock; class CassandraReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraReactiveHealthContributorAutoConfiguration.class, - CassandraHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CassandraReactiveHealthContributorAutoConfiguration.class, + CassandraHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runWithoutCqlSessionOrReactiveCassandraOperationsShouldNotCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor") - .doesNotHaveBean(CassandraDriverReactiveHealthIndicator.class)); + .doesNotHaveBean(CassandraDriverReactiveHealthIndicator.class)); } @Test void runWithCqlSessionOnlyShouldCreateDriverIndicator() { - this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)).run((context) -> assertThat(context) - .hasBean("cassandraHealthContributor").hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); + this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) + .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") + .hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); } @Test void runWithCqlSessionAndReactiveCassandraOperationsShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) - .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) - .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") - .hasSingleBean(CassandraDriverReactiveHealthIndicator.class) - .doesNotHaveBean(CassandraDriverHealthIndicator.class)); + .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) + .withBean(CassandraOperations.class, () -> mock(CassandraOperations.class)) + .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") + .hasSingleBean(CassandraDriverReactiveHealthIndicator.class) + .doesNotHaveBean(CassandraDriverHealthIndicator.class)); } @Test void runWithCqlSessionAndSpringDataAbsentShouldCreateDriverIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.data")) - .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") - .hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.data")) + .run((context) -> assertThat(context).hasBean("cassandraHealthContributor") + .hasSingleBean(CassandraDriverReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withBean(CqlSession.class, () -> mock(CqlSession.class)) - .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) - .withPropertyValues("management.health.cassandra.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor")); + .withBean(ReactiveCassandraOperations.class, () -> mock(ReactiveCassandraOperations.class)) + .withPropertyValues("management.health.cassandra.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean("cassandraHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java index 7ac36ae23e..800ec2246b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryAuthorizationExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class CloudFoundryAuthorizationExceptionTests { @Test void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() { assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM).getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED); + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test @@ -74,7 +74,7 @@ class CloudFoundryAuthorizationExceptionTests { @Test void statusCodeForServiceUnavailableReasonShouldBe503() { assertThat(createException(Reason.SERVICE_UNAVAILABLE).getStatusCode()) - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } private CloudFoundryAuthorizationException createException(Reason reason) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java index 698cadbe77..38b984a501 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/CloudFoundryWebEndpointDiscovererTests.java @@ -67,8 +67,8 @@ class CloudFoundryWebEndpointDiscovererTests { if (endpoint.getEndpointId().equals(EndpointId.of("health"))) { WebOperation operation = findMainReadOperation(endpoint); assertThat(operation - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.emptyMap()))) - .isEqualTo("cf"); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.emptyMap()))) + .isEqualTo("cf"); } } }); @@ -78,8 +78,9 @@ class CloudFoundryWebEndpointDiscovererTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new CloudFoundryWebEndpointDiscovererRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(CloudFoundryEndpointFilter.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(CloudFoundryEndpointFilter.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); } private WebOperation findMainReadOperation(ExposableWebEndpoint endpoint) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java index 4810699151..e4fb31997c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class TokenTests { @Test void invalidJwtShouldThrowException() { assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token("invalid-token")) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -44,9 +44,9 @@ class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "invalid-claims"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token(Base64.getEncoder().encodeToString(header.getBytes()) + "." - + Base64.getEncoder().encodeToString(claims.getBytes()))) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .isThrownBy(() -> new Token(Base64.getEncoder().encodeToString(header.getBytes()) + "." + + Base64.getEncoder().encodeToString(claims.getBytes()))) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -54,9 +54,9 @@ class TokenTests { String header = "invalid-header"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> new Token(Base64.getEncoder().encodeToString(header.getBytes()) + "." - + Base64.getEncoder().encodeToString(claims.getBytes()))) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .isThrownBy(() -> new Token(Base64.getEncoder().encodeToString(header.getBytes()) + "." + + Base64.getEncoder().encodeToString(claims.getBytes()))) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -64,7 +64,7 @@ class TokenTests { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(() -> new Token(token)) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -89,7 +89,7 @@ class TokenTests { String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getSignatureAlgorithm) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -98,7 +98,7 @@ class TokenTests { String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getIssuer) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -107,7 +107,7 @@ class TokenTests { String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getKeyId) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -116,7 +116,7 @@ class TokenTests { String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy(token::getExpiry) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } private Token createToken(String header, String claims) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java index 79e977a7aa..e4eeaedbd9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryReactiveHealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -50,23 +50,23 @@ import static org.assertj.core.api.Assertions.assertThat; class CloudFoundryReactiveHealthEndpointWebExtensionTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, - ReactiveCloudFoundryActuatorAutoConfigurationTests.WebClientCustomizerConfig.class, - WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, - ReactiveCloudFoundryActuatorAutoConfiguration.class)) - .withUserConfiguration(TestHealthIndicator.class); + .withPropertyValues("VCAP_APPLICATION={}") + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, + ReactiveCloudFoundryActuatorAutoConfigurationTests.WebClientCustomizerConfig.class, + WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + ReactiveCloudFoundryActuatorAutoConfiguration.class)) + .withUserConfiguration(TestHealthIndicator.class); @Test void healthComponentsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryReactiveHealthEndpointWebExtension extension = context - .getBean(CloudFoundryReactiveHealthEndpointWebExtension.class); + .getBean(CloudFoundryReactiveHealthEndpointWebExtension.class); HealthComponent body = extension.health(ApiVersion.V3).block(Duration.ofSeconds(30)).getBody(); HealthComponent health = ((CompositeHealth) body).getComponents().entrySet().iterator().next().getValue(); assertThat(((Health) health).getDetails()).containsEntry("spring", "boot"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMappingTests.java index f97d71db90..f6a8d1cff8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class CloudFoundryWebFluxEndpointHandlerMappingTests { new CloudFoundryWebFluxEndpointHandlerMappingRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onMethod(CloudFoundryLinksHandler.class, "links")) - .accepts(runtimeHints); + .accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(Link.class)).accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java index d8d20c95f1..ca2c9fd94f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,50 +78,87 @@ class CloudFoundryWebFluxEndpointIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(TestEndpointConfiguration.class).withPropertyValues("server.port=0"); + .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(TestEndpointConfiguration.class) + .withPropertyValues("server.port=0"); @Test void operationWithSecurityInterceptorForbidden() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); - this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isEqualTo(HttpStatus.FORBIDDEN))); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.FORBIDDEN))); } @Test void operationWithSecurityInterceptorSuccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); - this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isEqualTo(HttpStatus.OK))); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.OK))); } @Test void responseToOptionsRequestIncludesCorsHeaders() { - this.contextRunner.run(withWebTestClient((client) -> client.options().uri("/cfApplication/test") - .accept(MediaType.APPLICATION_JSON).header("Access-Control-Request-Method", "POST") - .header("Origin", "https://example.com").exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST"))); + this.contextRunner.run(withWebTestClient((client) -> client.options() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST"))); } @Test void linksToOtherEndpointsWithFullAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.FULL)); - this.contextRunner - .run(withWebTestClient((client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env.href").isNotEmpty() - .jsonPath("_links.env.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") - .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true))); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(5) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env.href") + .isNotEmpty() + .jsonPath("_links.env.templated") + .isEqualTo(false) + .jsonPath("_links.test.href") + .isNotEmpty() + .jsonPath("_links.test.templated") + .isEqualTo(false) + .jsonPath("_links.test-part.href") + .isNotEmpty() + .jsonPath("_links.test-part.templated") + .isEqualTo(true))); } @Test @@ -129,31 +166,55 @@ class CloudFoundryWebFluxEndpointIntegrationTests { CloudFoundryAuthorizationException exception = new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); - this.contextRunner.run(withWebTestClient((client) -> client.get().uri("/cfApplication") - .accept(MediaType.APPLICATION_JSON).header("Authorization", "bearer " + mockAccessToken()).exchange() - .expectStatus().isUnauthorized())); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isUnauthorized())); } @Test void linksToOtherEndpointsWithRestrictedAccess() { given(tokenValidator.validate(any())).willReturn(Mono.empty()); given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(Mono.just(AccessLevel.RESTRICTED)); - this.contextRunner - .run(withWebTestClient((client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env").doesNotExist() - .jsonPath("_links.test").doesNotExist().jsonPath("_links.test-part").doesNotExist())); + this.contextRunner.run(withWebTestClient((client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(2) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env") + .doesNotExist() + .jsonPath("_links.test") + .doesNotExist() + .jsonPath("_links.test-part") + .doesNotExist())); } private ContextConsumer withWebTestClient( Consumer clientConsumer) { return (context) -> { int port = ((AnnotationConfigReactiveWebServerApplicationContext) context.getSourceApplicationContext()) - .getWebServer().getPort(); - clientConsumer.accept(WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build()); + .getWebServer() + .getPort(); + clientConsumer.accept(WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build()); }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java index a3d7181344..715f15c934 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,15 +84,15 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { private static final String V3_JSON = ApiVersion.V3.getProducedMimeType().toString(); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, WebClientCustomizerConfig.class, - WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, - InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, - ProjectInfoAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class, WebFluxAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, WebClientCustomizerConfig.class, + WebClientAutoConfiguration.class, ManagementContextAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + ProjectInfoAutoConfiguration.class, ReactiveCloudFoundryActuatorAutoConfiguration.class)); @AfterEach void close() { @@ -101,149 +101,161 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test void cloudFoundryPlatformActive() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, - "endpointMapping"); - assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); - CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils - .getField(handlerMapping, "corsConfiguration"); - assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); - assertThat(corsConfiguration.getAllowedMethods()) - .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - assertThat(corsConfiguration.getAllowedHeaders()) - .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, + "endpointMapping"); + assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); + CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils.getField(handlerMapping, + "corsConfiguration"); + assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); + assertThat(corsConfiguration.getAllowedMethods()) + .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + assertThat(corsConfiguration.getAllowedHeaders()) + .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + }); } @Test void cloudfoundryapplicationProducesActuatorMediaType() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); - webTestClient.get().uri("/cloudfoundryapplication").header("Content-Type", - V2_JSON + ";charset=UTF-8"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + WebTestClient webTestClient = WebTestClient.bindToApplicationContext(context).build(); + webTestClient.get().uri("/cloudfoundryapplication").header("Content-Type", V2_JSON + ";charset=UTF-8"); + }); } @Test void cloudFoundryPlatformActiveSetsApplicationId() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); - assertThat(applicationId).isEqualTo("my-app-id"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); + assertThat(applicationId).isEqualTo("my-app-id"); + }); } @Test void cloudFoundryPlatformActiveSetsCloudControllerUrl() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, - "cloudControllerUrl"); - assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, + "cloudControllerUrl"); + assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); + }); } @Test void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean( - "cloudFoundryWebFluxEndpointHandlerMapping", - CloudFoundryWebFluxEndpointHandlerMapping.class); - Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, - "cloudFoundrySecurityService"); - assertThat(interceptorSecurityService).isNull(); - }); + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = context.getBean( + "cloudFoundryWebFluxEndpointHandlerMapping", CloudFoundryWebFluxEndpointHandlerMapping.class); + Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, + "cloudFoundrySecurityService"); + assertThat(interceptorSecurityService).isNull(); + }); } @Test @SuppressWarnings("unchecked") void cloudFoundryPathsIgnoredBySpringSecurity() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class); - List filters = (List) ReflectionTestUtils - .getField(chainProxy, "filters"); - Boolean cfRequestMatches = filters.get(0) - .matches(MockServerWebExchange - .from(MockServerHttpRequest.get("/cloudfoundryapplication/my-path").build())) - .block(Duration.ofSeconds(30)); - Boolean otherRequestMatches = filters.get(0) - .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) - .block(Duration.ofSeconds(30)); - assertThat(cfRequestMatches).isTrue(); - assertThat(otherRequestMatches).isFalse(); - otherRequestMatches = filters.get(1) - .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) - .block(Duration.ofSeconds(30)); - assertThat(otherRequestMatches).isTrue(); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + WebFilterChainProxy chainProxy = context.getBean(WebFilterChainProxy.class); + List filters = (List) ReflectionTestUtils + .getField(chainProxy, "filters"); + Boolean cfRequestMatches = filters.get(0) + .matches(MockServerWebExchange + .from(MockServerHttpRequest.get("/cloudfoundryapplication/my-path").build())) + .block(Duration.ofSeconds(30)); + Boolean otherRequestMatches = filters.get(0) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) + .block(Duration.ofSeconds(30)); + assertThat(cfRequestMatches).isTrue(); + assertThat(otherRequestMatches).isFalse(); + otherRequestMatches = filters.get(1) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) + .block(Duration.ofSeconds(30)); + assertThat(otherRequestMatches).isTrue(); + }); } @Test void cloudFoundryPlatformInactive() { - this.contextRunner.run( - (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); + this.contextRunner + .run((context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test void cloudFoundryManagementEndpointsDisabled() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false").run( - (context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); + this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false") + .run((context) -> assertThat(context.containsBean("cloudFoundryWebFluxEndpointHandlerMapping")).isFalse()); } @Test void allEndpointsAvailableUnderCloudFoundryWithoutEnablingWebIncludes() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - List endpointIds = endpoints.stream().map(ExposableWebEndpoint::getEndpointId).toList(); - assertThat(endpointIds).contains(EndpointId.of("test")); - }); + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + List endpointIds = endpoints.stream().map(ExposableWebEndpoint::getEndpointId).toList(); + assertThat(endpointIds).contains(EndpointId.of("test")); + }); } @Test void endpointPathCustomizationIsNotApplied() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.stream() - .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst() - .get(); - assertThat(endpoint.getOperations()).hasSize(1); - WebOperation operation = endpoint.getOperations().iterator().next(); - assertThat(operation.getRequestPredicate().getPath()).isEqualTo("test"); - }); + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.stream() + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst() + .get(); + assertThat(endpoint.getOperations()).hasSize(1); + WebOperation operation = endpoint.getOperations().iterator().next(); + assertThat(operation.getRequestPredicate().getPath()).isEqualTo("test"); + }); } @Test void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - Collection endpoints = getHandlerMapping(context).getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getOperations()).hasSize(2); - WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); - assertThat(webOperation).extracting("invoker").extracting("target") - .isInstanceOf(CloudFoundryReactiveHealthEndpointWebExtension.class); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + Collection endpoints = getHandlerMapping(context).getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getOperations()).hasSize(2); + WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); + assertThat(webOperation).extracting("invoker") + .extracting("target") + .isInstanceOf(CloudFoundryReactiveHealthEndpointWebExtension.class); + }); } @Test @@ -251,7 +263,7 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { void gitFullDetailsAlwaysPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run((context) -> { CloudFoundryInfoEndpointWebExtension extension = context - .getBean(CloudFoundryInfoEndpointWebExtension.class); + .getBean(CloudFoundryInfoEndpointWebExtension.class); Map git = (Map) extension.info().get("git"); Map commit = (Map) git.get("commit"); assertThat(commit).hasSize(4); @@ -261,38 +273,42 @@ class ReactiveCloudFoundryActuatorAutoConfigurationTests { @Test void skipSslValidation() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com", - "management.cloudfoundry.skip-ssl-validation:true") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, - "webClient"); - webClient.get().uri("https://self-signed.badssl.com/").retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com", + "management.cloudfoundry.skip-ssl-validation:true") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, "webClient"); + webClient.get() + .uri("https://self-signed.badssl.com/") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); + }); } @Test void sslValidationNotSkippedByDefault() { this.contextRunner.withConfiguration(AutoConfigurations.of(HealthEndpointAutoConfiguration.class)) - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, - "webClient"); - assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> webClient.get().uri("https://self-signed.badssl.com/").retrieve() - .toBodilessEntity().block(Duration.ofSeconds(30))) - .withCauseInstanceOf(SSLException.class); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebFluxEndpointHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + WebClient webClient = (WebClient) ReflectionTestUtils.getField(interceptorSecurityService, "webClient"); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> webClient.get() + .uri("https://self-signed.badssl.com/") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30))) + .withCauseInstanceOf(SSLException.class); + }); } private CloudFoundryWebFluxEndpointHandlerMapping getHandlerMapping(ApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java index f7b9bf5eda..808e7a2abb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -61,64 +61,68 @@ class ReactiveCloudFoundrySecurityInterceptorTests { @Test void preHandleWhenRequestIsPreFlightShouldBeOk() { - MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.options("/a").header(HttpHeaders.ORIGIN, "https://example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").build()); + MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.options("/a") + .header(HttpHeaders.ORIGIN, "https://example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeNextWith((response) -> assertThat(response.getStatus()).isEqualTo(HttpStatus.OK)) - .verifyComplete(); + .consumeNextWith((response) -> assertThat(response.getStatus()).isEqualTo(HttpStatus.OK)) + .verifyComplete(); } @Test void preHandleWhenTokenIsMissingShouldReturnMissingAuthorization() { MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a").build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( - (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) - .verifyComplete(); + StepVerifier.create(this.interceptor.preHandle(request, "/a")) + .consumeNextWith( + (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) + .verifyComplete(); } @Test void preHandleWhenTokenIsNotBearerShouldReturnMissingAuthorization() { MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); - StepVerifier.create(this.interceptor.preHandle(request, "/a")).consumeNextWith( - (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) - .verifyComplete(); + .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); + StepVerifier.create(this.interceptor.preHandle(request, "/a")) + .consumeNextWith( + (response) -> assertThat(response.getStatus()).isEqualTo(Reason.MISSING_AUTHORIZATION.getStatus())) + .verifyComplete(); } @Test void preHandleWhenApplicationIdIsNullShouldReturnError() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, this.securityService, null); MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE)) - .verify(); + .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE)) + .verify(); } @Test void preHandleWhenCloudFoundrySecurityServiceIsNullShouldReturnError() { this.interceptor = new CloudFoundrySecurityInterceptor(this.tokenValidator, null, "my-app-id"); MockServerWebExchange request = MockServerWebExchange - .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); + .from(MockServerHttpRequest.get("/a").header(HttpHeaders.AUTHORIZATION, mockAccessToken()).build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE)) - .verify(); + .consumeErrorWith((ex) -> assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE)) + .verify(); } @Test void preHandleWhenAccessIsNotAllowedShouldReturnAccessDenied() { given(this.securityService.getAccessLevel(mockAccessToken(), "my-app-id")) - .willReturn(Mono.just(AccessLevel.RESTRICTED)); + .willReturn(Mono.just(AccessLevel.RESTRICTED)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(request, "/a")) - .consumeNextWith( - (response) -> assertThat(response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus())) - .verifyComplete(); + .consumeNextWith((response) -> assertThat(response.getStatus()).isEqualTo(Reason.ACCESS_DENIED.getStatus())) + .verifyComplete(); } @Test @@ -127,7 +131,8 @@ class ReactiveCloudFoundrySecurityInterceptorTests { given(this.securityService.getAccessLevel(accessToken, "my-app-id")).willReturn(Mono.just(AccessLevel.FULL)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/a") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(exchange, "/a")).consumeNextWith((response) -> { assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); assertThat((AccessLevel) exchange.getAttribute("cloudFoundryAccessLevel")).isEqualTo(AccessLevel.FULL); @@ -138,14 +143,15 @@ class ReactiveCloudFoundrySecurityInterceptorTests { void preHandleSuccessfulWithRestrictedAccess() { String accessToken = mockAccessToken(); given(this.securityService.getAccessLevel(accessToken, "my-app-id")) - .willReturn(Mono.just(AccessLevel.RESTRICTED)); + .willReturn(Mono.just(AccessLevel.RESTRICTED)); given(this.tokenValidator.validate(any())).willReturn(Mono.empty()); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/info") - .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()).build()); + .header(HttpHeaders.AUTHORIZATION, "bearer " + mockAccessToken()) + .build()); StepVerifier.create(this.interceptor.preHandle(exchange, "info")).consumeNextWith((response) -> { assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); assertThat((AccessLevel) exchange.getAttribute("cloudFoundryAccessLevel")) - .isEqualTo(AccessLevel.RESTRICTED); + .isEqualTo(AccessLevel.RESTRICTED); }).verifyComplete(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java index f0bf605ff9..29258b9f20 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityServiceTests.java @@ -70,8 +70,9 @@ class ReactiveCloudFoundrySecurityServiceTests { String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.FULL)).expectComplete() - .verify(); + .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.FULL)) + .expectComplete() + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -83,8 +84,9 @@ class ReactiveCloudFoundrySecurityServiceTests { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; prepareResponse((response) -> response.setBody(responseBody).setHeader("Content-Type", "application/json")); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED)) - .expectComplete().verify(); + .consumeNextWith((accessLevel) -> assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED)) + .expectComplete() + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -95,11 +97,12 @@ class ReactiveCloudFoundrySecurityServiceTests { void getAccessLevelWhenTokenIsNotValidShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(401)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeErrorWith((throwable) -> { - assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.INVALID_TOKEN); - }).verify(); + .consumeErrorWith((throwable) -> { + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.INVALID_TOKEN); + }) + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -110,11 +113,12 @@ class ReactiveCloudFoundrySecurityServiceTests { void getAccessLevelWhenForbiddenShouldThrowException() throws Exception { prepareResponse((response) -> response.setResponseCode(403)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeErrorWith((throwable) -> { - assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.ACCESS_DENIED); - }).verify(); + .consumeErrorWith((throwable) -> { + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.ACCESS_DENIED); + }) + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -125,11 +129,12 @@ class ReactiveCloudFoundrySecurityServiceTests { void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() throws Exception { prepareResponse((response) -> response.setResponseCode(500)); StepVerifier.create(this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .consumeErrorWith((throwable) -> { - assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE); - }).verify(); + .consumeErrorWith((throwable) -> { + assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE); + }) + .verify(); expectRequest((request) -> { assertThat(request.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("bearer my-access-token"); assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER_PERMISSIONS); @@ -159,8 +164,9 @@ class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeNextWith((tokenKeys) -> assertThat(tokenKeys.get("test-key")).isEqualTo(tokenKeyValue)) - .expectComplete().verify(); + .consumeNextWith((tokenKeys) -> assertThat(tokenKeys.get("test-key")).isEqualTo(tokenKeyValue)) + .expectComplete() + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @@ -177,7 +183,9 @@ class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeNextWith((tokenKeys) -> assertThat(tokenKeys).hasSize(0)).expectComplete().verify(); + .consumeNextWith((tokenKeys) -> assertThat(tokenKeys).hasSize(0)) + .expectComplete() + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @@ -190,10 +198,9 @@ class ReactiveCloudFoundrySecurityServiceTests { }); prepareResponse((response) -> response.setResponseCode(500)); StepVerifier.create(this.securityService.fetchTokenKeys()) - .consumeErrorWith( - (throwable) -> assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE)) - .verify(); + .consumeErrorWith((throwable) -> assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) + .isEqualTo(Reason.SERVICE_UNAVAILABLE)) + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-cloud-controller.com/info")); expectRequest((request) -> assertThat(request.getPath()).isEqualTo("/my-uaa.com/token_keys")); } @@ -205,7 +212,9 @@ class ReactiveCloudFoundrySecurityServiceTests { response.setHeader("Content-Type", "application/json"); }); StepVerifier.create(this.securityService.getUaaUrl()) - .consumeNextWith((uaaUrl) -> assertThat(uaaUrl).isEqualTo(UAA_URL)).expectComplete().verify(); + .consumeNextWith((uaaUrl) -> assertThat(uaaUrl).isEqualTo(UAA_URL)) + .expectComplete() + .verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER + "/info")); expectRequestCount(1); } @@ -216,7 +225,7 @@ class ReactiveCloudFoundrySecurityServiceTests { StepVerifier.create(this.securityService.getUaaUrl()).consumeErrorWith((throwable) -> { assertThat(throwable).isInstanceOf(CloudFoundryAuthorizationException.class); assertThat(((CloudFoundryAuthorizationException) throwable).getReason()) - .isEqualTo(Reason.SERVICE_UNAVAILABLE); + .isEqualTo(Reason.SERVICE_UNAVAILABLE); }).verify(); expectRequest((request) -> assertThat(request.getPath()).isEqualTo(CLOUD_CONTROLLER + "/info")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java index bb0ccb6100..7af4f3fd6a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveTokenValidatorTests.java @@ -105,11 +105,12 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"invalid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); + }) + .verify(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -123,8 +124,8 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .verifyComplete(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .verifyComplete(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -137,8 +138,8 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .verifyComplete(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .verifyComplete(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -151,11 +152,12 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"invalid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_KEY_ID); + }) + .verify(); assertThat(this.tokenValidator).hasFieldOrPropertyWithValue("cachedTokenKeys", VALID_KEYS); fetchTokenKeys.assertWasSubscribed(); } @@ -168,8 +170,8 @@ class ReactiveTokenValidatorTests { String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .verifyComplete(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .verifyComplete(); fetchTokenKeys.assertWasNotSubscribed(); } @@ -181,12 +183,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.INVALID_SIGNATURE); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_SIGNATURE); + }) + .verify(); } @Test @@ -196,12 +198,13 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"HS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()) + .isEqualTo(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM); + }) + .verify(); } @Test @@ -211,11 +214,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.TOKEN_EXPIRED); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.TOKEN_EXPIRED); + }) + .verify(); } @Test @@ -225,11 +229,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_ISSUER); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_ISSUER); + }) + .verify(); } @Test @@ -239,12 +244,12 @@ class ReactiveTokenValidatorTests { String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; StepVerifier - .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .consumeErrorWith((ex) -> { - assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); - assertThat(((CloudFoundryAuthorizationException) ex).getReason()) - .isEqualTo(Reason.INVALID_AUDIENCE); - }).verify(); + .create(this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .consumeErrorWith((ex) -> { + assertThat(ex).isExactlyInstanceOf(CloudFoundryAuthorizationException.class); + assertThat(((CloudFoundryAuthorizationException) ex).getReason()).isEqualTo(Reason.INVALID_AUDIENCE); + }) + .verify(); } private String getSignedToken(byte[] header, byte[] claims) throws Exception { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java index 04f261b6cd..5314b4e6b8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryActuatorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -70,172 +70,183 @@ class CloudFoundryActuatorAutoConfigurationTests { private static final String V3_JSON = ApiVersion.V3.getProducedMimeType().toString(); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test void cloudFoundryPlatformActive() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, - "endpointMapping"); - assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); - CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils - .getField(handlerMapping, "corsConfiguration"); - assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); - assertThat(corsConfiguration.getAllowedMethods()) - .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); - assertThat(corsConfiguration.getAllowedHeaders()) - .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + EndpointMapping endpointMapping = (EndpointMapping) ReflectionTestUtils.getField(handlerMapping, + "endpointMapping"); + assertThat(endpointMapping.getPath()).isEqualTo("/cloudfoundryapplication"); + CorsConfiguration corsConfiguration = (CorsConfiguration) ReflectionTestUtils.getField(handlerMapping, + "corsConfiguration"); + assertThat(corsConfiguration.getAllowedOrigins()).contains("*"); + assertThat(corsConfiguration.getAllowedMethods()) + .containsAll(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); + assertThat(corsConfiguration.getAllowedHeaders()) + .containsAll(Arrays.asList("Authorization", "X-Cf-App-Instance", "Content-Type")); + }); } @Test void cloudfoundryapplicationProducesActuatorMediaType() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); - mockMvc.perform(get("/cloudfoundryapplication")) - .andExpect(header().string("Content-Type", V3_JSON)); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); + mockMvc.perform(get("/cloudfoundryapplication")).andExpect(header().string("Content-Type", V3_JSON)); + }); } @Test void cloudFoundryPlatformActiveSetsApplicationId() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); - assertThat(applicationId).isEqualTo("my-app-id"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + String applicationId = (String) ReflectionTestUtils.getField(interceptor, "applicationId"); + assertThat(applicationId).isEqualTo("my-app-id"); + }); } @Test void cloudFoundryPlatformActiveSetsCloudControllerUrl() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, - "cloudControllerUrl"); - assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + String cloudControllerUrl = (String) ReflectionTestUtils.getField(interceptorSecurityService, + "cloudControllerUrl"); + assertThat(cloudControllerUrl).isEqualTo("https://my-cloud-controller.com"); + }); } @Test void skipSslValidation() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com", - "management.cloudfoundry.skip-ssl-validation:true").run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, - "cloudFoundrySecurityService"); - RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(interceptorSecurityService, - "restTemplate"); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(SkipSslVerificationHttpRequestFactory.class); - }); + this.contextRunner + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com", + "management.cloudfoundry.skip-ssl-validation:true") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object interceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(interceptor, + "cloudFoundrySecurityService"); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(interceptorSecurityService, + "restTemplate"); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(SkipSslVerificationHttpRequestFactory.class); + }); } @Test void cloudFoundryPlatformActiveAndCloudControllerUrlNotPresent() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); - Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, - "cloudFoundrySecurityService"); - assertThat(interceptorSecurityService).isNull(); - }); + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Object securityInterceptor = ReflectionTestUtils.getField(handlerMapping, "securityInterceptor"); + Object interceptorSecurityService = ReflectionTestUtils.getField(securityInterceptor, + "cloudFoundrySecurityService"); + assertThat(interceptorSecurityService).isNull(); + }); } @Test void cloudFoundryPathsIgnoredBySpringSecurity() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") - .run((context) -> { - FilterChainProxy securityFilterChain = (FilterChainProxy) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); - SecurityFilterChain chain = securityFilterChain.getFilterChains().get(0); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setServletPath("/cloudfoundryapplication/my-path"); - assertThat(chain.getFilters()).isEmpty(); - assertThat(chain.matches(request)).isTrue(); - request.setServletPath("/some-other-path"); - assertThat(chain.matches(request)).isFalse(); - }); + .run((context) -> { + FilterChainProxy securityFilterChain = (FilterChainProxy) context + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + SecurityFilterChain chain = securityFilterChain.getFilterChains().get(0); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("/cloudfoundryapplication/my-path"); + assertThat(chain.getFilters()).isEmpty(); + assertThat(chain.matches(request)).isTrue(); + request.setServletPath("/some-other-path"); + assertThat(chain.matches(request)).isFalse(); + }); } @Test void cloudFoundryPlatformInactive() { this.contextRunner.withPropertyValues() - .run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping")) - .isFalse()); + .run((context) -> assertThat(context.containsBean("cloudFoundryWebEndpointServletHandlerMapping")) + .isFalse()); } @Test void cloudFoundryManagementEndpointsDisabled() { this.contextRunner.withPropertyValues("VCAP_APPLICATION=---", "management.cloudfoundry.enabled:false") - .run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse()); + .run((context) -> assertThat(context.containsBean("cloudFoundryEndpointHandlerMapping")).isFalse()); } @Test void allEndpointsAvailableUnderCloudFoundryWithoutExposeAllOnWeb() { - this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new).withPropertyValues("VCAP_APPLICATION:---", - "vcap.application.application_id:my-app-id", "vcap.application.cf_api:https://my-cloud-controller.com") - .run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - assertThat(endpoints.stream() - .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst()) - .isNotEmpty(); - }); + this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + assertThat(endpoints.stream() + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst()).isNotEmpty(); + }); } @Test void endpointPathCustomizationIsNotApplied() { this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com", - "management.endpoints.web.path-mapping.test=custom") - .withBean(TestEndpoint.class, TestEndpoint::new).run((context) -> { - CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); - Collection endpoints = handlerMapping.getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.stream() - .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())).findFirst() - .get(); - Collection operations = endpoint.getOperations(); - assertThat(operations).hasSize(1); - assertThat(operations.iterator().next().getRequestPredicate().getPath()).isEqualTo("test"); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com", + "management.endpoints.web.path-mapping.test=custom") + .withBean(TestEndpoint.class, TestEndpoint::new) + .run((context) -> { + CloudFoundryWebEndpointServletHandlerMapping handlerMapping = getHandlerMapping(context); + Collection endpoints = handlerMapping.getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.stream() + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst() + .get(); + Collection operations = endpoint.getOperations(); + assertThat(operations).hasSize(1); + assertThat(operations.iterator().next().getRequestPredicate().getPath()).isEqualTo("test"); + }); } @Test void healthEndpointInvokerShouldBeCloudFoundryWebExtension() { this.contextRunner - .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", - "vcap.application.cf_api:https://my-cloud-controller.com") - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class)) - .run((context) -> { - Collection endpoints = context - .getBean("cloudFoundryWebEndpointServletHandlerMapping", - CloudFoundryWebEndpointServletHandlerMapping.class) - .getEndpoints(); - ExposableWebEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getOperations()).hasSize(2); - WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); - assertThat(webOperation).extracting("invoker.target") - .isInstanceOf(CloudFoundryHealthEndpointWebExtension.class); - }); + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class)) + .run((context) -> { + Collection endpoints = context + .getBean("cloudFoundryWebEndpointServletHandlerMapping", + CloudFoundryWebEndpointServletHandlerMapping.class) + .getEndpoints(); + ExposableWebEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getOperations()).hasSize(2); + WebOperation webOperation = findOperationWithRequestPath(endpoint, "health"); + assertThat(webOperation).extracting("invoker.target") + .isInstanceOf(CloudFoundryHealthEndpointWebExtension.class); + }); } private CloudFoundryWebEndpointServletHandlerMapping getHandlerMapping(ApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java index 024c7b107f..f113a01ccf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryHealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -49,21 +49,21 @@ import static org.assertj.core.api.Assertions.assertThat; class CloudFoundryHealthEndpointWebExtensionTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)) - .withUserConfiguration(TestHealthIndicator.class); + .withPropertyValues("VCAP_APPLICATION={}") + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)) + .withUserConfiguration(TestHealthIndicator.class); @Test void healthComponentsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryHealthEndpointWebExtension extension = context - .getBean(CloudFoundryHealthEndpointWebExtension.class); + .getBean(CloudFoundryHealthEndpointWebExtension.class); HealthComponent body = extension.health(ApiVersion.V3).getBody(); HealthComponent health = ((CompositeHealth) body).getComponents().entrySet().iterator().next().getValue(); assertThat(((Health) health).getDetails()).containsEntry("spring", "boot"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java index 042e7988c6..e8cebbf1dd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryInfoEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -48,22 +48,22 @@ import static org.assertj.core.api.Assertions.assertThat; class CloudFoundryInfoEndpointWebExtensionTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withPropertyValues("VCAP_APPLICATION={}") - .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, - JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ProjectInfoAutoConfiguration.class, - InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); + .withPropertyValues("VCAP_APPLICATION={}") + .withConfiguration(AutoConfigurations.of(SecurityAutoConfiguration.class, WebMvcAutoConfiguration.class, + JacksonAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + RestTemplateAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ProjectInfoAutoConfiguration.class, + InfoContributorAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, CloudFoundryActuatorAutoConfiguration.class)); @Test @SuppressWarnings("unchecked") void gitFullDetailsAlwaysPresent() { this.contextRunner.run((context) -> { CloudFoundryInfoEndpointWebExtension extension = context - .getBean(CloudFoundryInfoEndpointWebExtension.class); + .getBean(CloudFoundryInfoEndpointWebExtension.class); Map git = (Map) extension.info().get("git"); Map commit = (Map) git.get("commit"); assertThat(commit).hasSize(4); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java index 0a556e1c3b..6663f31739 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryMvcWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -74,42 +74,79 @@ class CloudFoundryMvcWebEndpointIntegrationTests { void operationWithSecurityInterceptorForbidden() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() - .isEqualTo(HttpStatus.FORBIDDEN)); + (client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.FORBIDDEN)); } @Test void operationWithSecurityInterceptorSuccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() - .isEqualTo(HttpStatus.OK)); + (client) -> client.get() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.OK)); } @Test void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, - (client) -> client.options().uri("/cfApplication/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") - .exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST")); + (client) -> client.options() + .uri("/cfApplication/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test void linksToOtherEndpointsWithFullAccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.FULL); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(5).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env.href").isNotEmpty() - .jsonPath("_links.env.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") - .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true)); + (client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(5) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env.href") + .isNotEmpty() + .jsonPath("_links.env.templated") + .isEqualTo(false) + .jsonPath("_links.test.href") + .isNotEmpty() + .jsonPath("_links.test.templated") + .isEqualTo(false) + .jsonPath("_links.test-part.href") + .isNotEmpty() + .jsonPath("_links.test-part.templated") + .isEqualTo(true)); } @Test @@ -118,21 +155,43 @@ class CloudFoundryMvcWebEndpointIntegrationTests { "invalid-token"); willThrow(exception).given(tokenValidator).validate(any()); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus() - .isUnauthorized()); + (client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isUnauthorized()); } @Test void linksToOtherEndpointsWithRestrictedAccess() { given(securityService.getAccessLevel(any(), eq("app-id"))).willReturn(AccessLevel.RESTRICTED); load(TestEndpointConfiguration.class, - (client) -> client.get().uri("/cfApplication").accept(MediaType.APPLICATION_JSON) - .header("Authorization", "bearer " + mockAccessToken()).exchange().expectStatus().isOk() - .expectBody().jsonPath("_links.length()").isEqualTo(2).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.info.href").isNotEmpty() - .jsonPath("_links.info.templated").isEqualTo(false).jsonPath("_links.env").doesNotExist() - .jsonPath("_links.test").doesNotExist().jsonPath("_links.test-part").doesNotExist()); + (client) -> client.get() + .uri("/cfApplication") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(2) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.info.href") + .isNotEmpty() + .jsonPath("_links.info.templated") + .isEqualTo(false) + .jsonPath("_links.env") + .doesNotExist() + .jsonPath("_links.test") + .doesNotExist() + .jsonPath("_links.test-part") + .doesNotExist()); } private AnnotationConfigServletWebServerApplicationContext createApplicationContext(Class... config) { @@ -147,8 +206,11 @@ class CloudFoundryMvcWebEndpointIntegrationTests { BiConsumer consumer = (context, client) -> clientConsumer.accept(client); try (AnnotationConfigServletWebServerApplicationContext context = createApplicationContext(configuration, CloudFoundryMvcConfiguration.class)) { - consumer.accept(context, WebTestClient.bindToServer().baseUrl("http://localhost:" + getPort(context)) - .responseTimeout(Duration.ofMinutes(5)).build()); + consumer.accept(context, + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + getPort(context)) + .responseTimeout(Duration.ofMinutes(5)) + .build()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java index 1ddf01f29b..0ef8b8436b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java @@ -87,8 +87,8 @@ class CloudFoundrySecurityServiceTests { void getAccessLevelWhenSpaceDeveloperShouldReturnFull() { String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}"; this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.FULL); @@ -98,8 +98,8 @@ class CloudFoundrySecurityServiceTests { void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() { String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}"; this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id"); this.server.verify(); assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED); @@ -108,35 +108,37 @@ class CloudFoundrySecurityServiceTests { @Test void getAccessLevelWhenTokenIsNotValidShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withUnauthorizedRequest()); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withUnauthorizedRequest()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test void getAccessLevelWhenForbiddenShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")) - .andRespond(withStatus(HttpStatus.FORBIDDEN)); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withStatus(HttpStatus.FORBIDDEN)); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .satisfies(reasonRequirement(Reason.ACCESS_DENIED)); + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.ACCESS_DENIED)); } @Test void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) - .andExpect(header("Authorization", "bearer my-access-token")).andRespond(withServerError()); + .andExpect(header("Authorization", "bearer my-access-token")) + .andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) - .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); + .isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } @Test void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON)); String tokenKeyValue = """ -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO @@ -150,7 +152,7 @@ class CloudFoundrySecurityServiceTests { String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" + tokenKeyValue.replace("\n", "\\n") + "\"} ]}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); Map tokenKeys = this.securityService.fetchTokenKeys(); this.server.verify(); assertThat(tokenKeys).containsEntry("test-key", tokenKeyValue); @@ -159,10 +161,10 @@ class CloudFoundrySecurityServiceTests { @Test void fetchTokenKeysWhenNoKeysReturnedFromUAA() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String responseBody = "{\"keys\": []}"; this.server.expect(requestTo(UAA_URL + "/token_keys")) - .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); + .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON)); Map tokenKeys = this.securityService.fetchTokenKeys(); this.server.verify(); assertThat(tokenKeys).isEmpty(); @@ -171,17 +173,17 @@ class CloudFoundrySecurityServiceTests { @Test void fetchTokenKeysWhenUnsuccessfulShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.fetchTokenKeys()) - .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); + .isThrownBy(() -> this.securityService.fetchTokenKeys()) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } @Test void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) - .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); + .andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); String uaaUrl = this.securityService.getUaaUrl(); this.server.verify(); assertThat(uaaUrl).isEqualTo(UAA_URL); @@ -194,8 +196,8 @@ class CloudFoundrySecurityServiceTests { void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError()); assertThatExceptionOfType(CloudFoundryAuthorizationException.class) - .isThrownBy(() -> this.securityService.getUaaUrl()) - .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); + .isThrownBy(() -> this.securityService.getUaaUrl()) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } private Consumer reasonRequirement(Reason reason) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMappingTests.java index 100504cd45..a7446f11e4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundryWebEndpointServletHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class CloudFoundryWebEndpointServletHandlerMappingTests { new CloudFoundryWebEndpointServletHandlerMappingRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onMethod(CloudFoundryLinksHandler.class, "links")) - .accepts(runtimeHints); + .accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(Link.class)).accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java index 7bd6619f4e..6d7f0cf019 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,8 @@ class SkipSslVerificationHttpRequestFactoryTests { ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThatExceptionOfType(ResourceAccessException.class) - .isThrownBy(() -> otherRestTemplate.getForEntity(httpsUrl, String.class)) - .withCauseInstanceOf(SSLHandshakeException.class); + .isThrownBy(() -> otherRestTemplate.getForEntity(httpsUrl, String.class)) + .withCauseInstanceOf(SSLHandshakeException.class); } private String getHttpsUrl() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java index 977874620f..457299c5df 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java @@ -100,9 +100,10 @@ class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_KEY_ID)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_KEY_ID)); } @Test @@ -142,18 +143,20 @@ class TokenValidatorTests { Collections.singletonMap("valid-key", INVALID_KEY)); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_SIGNATURE)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_SIGNATURE)); } @Test void validateTokenWhenTokenAlgorithmIsNotRS256ShouldThrowException() { String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); } @Test @@ -162,9 +165,10 @@ class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.TOKEN_EXPIRED)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.TOKEN_EXPIRED)); } @Test @@ -173,9 +177,10 @@ class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("https://other-uaa.com"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_ISSUER)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_ISSUER)); } @Test @@ -184,9 +189,10 @@ class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; - assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( - () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) - .satisfies(reasonRequirement(Reason.INVALID_AUDIENCE)); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy( + () -> this.tokenValidator.validate(new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_AUDIENCE)); } private String getSignedToken(byte[] header, byte[] claims) throws Exception { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java index df2e9fdc62..0685e50cac 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -31,12 +31,12 @@ import static org.assertj.core.api.Assertions.assertThat; class ConditionsReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConditionsReportEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=conditions") - .run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(ConditionsReportEndpoint.class)); } @Test @@ -47,7 +47,7 @@ class ConditionsReportEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.conditions.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConditionsReportEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java index d9f77cc59f..ed8d60780d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,8 +47,10 @@ class ConditionsReportEndpointTests { @Test void invoke() { new ApplicationContextRunner().withUserConfiguration(Config.class).run((context) -> { - ContextConditionsDescriptor report = context.getBean(ConditionsReportEndpoint.class).conditions() - .getContexts().get(context.getId()); + ContextConditionsDescriptor report = context.getBean(ConditionsReportEndpoint.class) + .conditions() + .getContexts() + .get(context.getId()); assertThat(report.getPositiveMatches()).isEmpty(); assertThat(report.getNegativeMatches()).containsKey("a"); assertThat(report.getUnconditionalClasses()).contains("b"); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java index 2c6d14f4aa..1652a72dc8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/ShutdownEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,31 +36,32 @@ import static org.assertj.core.api.Assertions.assertThat; class ShutdownEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ShutdownEndpointAutoConfiguration.class)); @Test @SuppressWarnings("unchecked") void runShouldHaveEndpointBeanThatIsNotDisposable() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") - .withPropertyValues("management.endpoints.web.exposure.include=shutdown").run((context) -> { - assertThat(context).hasSingleBean(ShutdownEndpoint.class); - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - Map disposableBeans = (Map) ReflectionTestUtils - .getField(beanFactory, "disposableBeans"); - assertThat(disposableBeans).isEmpty(); - }); + .withPropertyValues("management.endpoints.web.exposure.include=shutdown") + .run((context) -> { + assertThat(context).hasSingleBean(ShutdownEndpoint.class); + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + Map disposableBeans = (Map) ReflectionTestUtils.getField(beanFactory, + "disposableBeans"); + assertThat(disposableBeans).isEmpty(); + }); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") - .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ShutdownEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java index 892c8e6a60..5458d68615 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/context/properties/ConfigurationPropertiesReportEndpointAutoConfigurationTests.java @@ -47,66 +47,67 @@ import static org.assertj.core.api.Assertions.assertThat; class ConfigurationPropertiesReportEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConfigurationPropertiesReportEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("management.endpoints.web.exposure.include=configprops") - .run(validateTestProperties("******", "******")); + .withPropertyValues("management.endpoints.web.exposure.include=configprops") + .run(validateTestProperties("******", "******")); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.configprops.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } @Test @SuppressWarnings("unchecked") void rolesCanBeConfiguredViaTheEnvironment() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("management.endpoint.configprops.roles: test") - .withPropertyValues("management.endpoints.web.exposure.include=configprops").run((context) -> { - assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpointWebExtension.class); - ConfigurationPropertiesReportEndpointWebExtension endpoint = context - .getBean(ConfigurationPropertiesReportEndpointWebExtension.class); - Set roles = (Set) ReflectionTestUtils.getField(endpoint, "roles"); - assertThat(roles).contains("test"); - }); + .withPropertyValues("management.endpoint.configprops.roles: test") + .withPropertyValues("management.endpoints.web.exposure.include=configprops") + .run((context) -> { + assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpointWebExtension.class); + ConfigurationPropertiesReportEndpointWebExtension endpoint = context + .getBean(ConfigurationPropertiesReportEndpointWebExtension.class); + Set roles = (Set) ReflectionTestUtils.getField(endpoint, "roles"); + assertThat(roles).contains("test"); + }); } @Test void showValuesCanBeConfiguredViaTheEnvironment() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("management.endpoint.configprops.show-values: WHEN_AUTHORIZED") - .withPropertyValues("management.endpoints.web.exposure.include=configprops").run((context) -> { - assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class); - assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpointWebExtension.class); - ConfigurationPropertiesReportEndpointWebExtension webExtension = context - .getBean(ConfigurationPropertiesReportEndpointWebExtension.class); - ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); - Show showValuesWebExtension = (Show) ReflectionTestUtils.getField(webExtension, "showValues"); - assertThat(showValuesWebExtension).isEqualTo(Show.WHEN_AUTHORIZED); - Show showValues = (Show) ReflectionTestUtils.getField(endpoint, "showValues"); - assertThat(showValues).isEqualTo(Show.WHEN_AUTHORIZED); - }); + .withPropertyValues("management.endpoint.configprops.show-values: WHEN_AUTHORIZED") + .withPropertyValues("management.endpoints.web.exposure.include=configprops") + .run((context) -> { + assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class); + assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpointWebExtension.class); + ConfigurationPropertiesReportEndpointWebExtension webExtension = context + .getBean(ConfigurationPropertiesReportEndpointWebExtension.class); + ConfigurationPropertiesReportEndpoint endpoint = context + .getBean(ConfigurationPropertiesReportEndpoint.class); + Show showValuesWebExtension = (Show) ReflectionTestUtils.getField(webExtension, "showValues"); + assertThat(showValuesWebExtension).isEqualTo(Show.WHEN_AUTHORIZED); + Show showValues = (Show) ReflectionTestUtils.getField(endpoint, "showValues"); + assertThat(showValues).isEqualTo(Show.WHEN_AUTHORIZED); + }); } @Test void customSanitizingFunctionsAreAppliedInOrder() { this.contextRunner.withPropertyValues("management.endpoint.configprops.show-values: ALWAYS") - .withUserConfiguration(Config.class, SanitizingFunctionConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=configprops", - "test.my-test-property=abc") - .run(validateTestProperties("$$$111$$$", "$$$222$$$")); + .withUserConfiguration(Config.class, SanitizingFunctionConfiguration.class) + .withPropertyValues("management.endpoints.web.exposure.include=configprops", "test.my-test-property=abc") + .run(validateTestProperties("$$$111$$$", "$$$222$$$")); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConfigurationPropertiesReportEndpoint.class)); } private ContextConsumer validateTestProperties(String dbPassword, @@ -114,10 +115,13 @@ class ConfigurationPropertiesReportEndpointAutoConfigurationTests { return (context) -> { assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor properties = endpoint.configurationProperties(); - Map nestedProperties = properties.getContexts().get(context.getId()).getBeans() - .get("testProperties").getProperties(); + Map nestedProperties = properties.getContexts() + .get(context.getId()) + .getBeans() + .get("testProperties") + .getProperties(); assertThat(nestedProperties).isNotNull(); assertThat(nestedProperties).containsEntry("dbPassword", dbPassword); assertThat(nestedProperties).containsEntry("myTestProperty", myTestProperty); @@ -127,10 +131,10 @@ class ConfigurationPropertiesReportEndpointAutoConfigurationTests { @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=configprops") - .run((context) -> assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class) - .doesNotHaveBean(ConfigurationPropertiesReportEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=configprops") + .run((context) -> assertThat(context).hasSingleBean(ConfigurationPropertiesReportEndpoint.class) + .doesNotHaveBean(ConfigurationPropertiesReportEndpointWebExtension.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java index 4d8860877e..6e171325da 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -37,19 +37,20 @@ import static org.mockito.Mockito.mock; class CouchbaseHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(Cluster.class, () -> mock(Cluster.class)).withConfiguration(AutoConfigurations - .of(CouchbaseHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withBean(Cluster.class, () -> mock(Cluster.class)) + .withConfiguration(AutoConfigurations.of(CouchbaseHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseHealthIndicator.class) - .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class)); + .doesNotHaveBean(CouchbaseReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java index d4474a9bd6..a99dfa423d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/couchbase/CouchbaseReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -36,28 +36,29 @@ import static org.mockito.Mockito.mock; class CouchbaseReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(Cluster.class, () -> mock(Cluster.class)) - .withConfiguration(AutoConfigurations.of(CouchbaseReactiveHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withBean(Cluster.class, () -> mock(Cluster.class)) + .withConfiguration(AutoConfigurations.of(CouchbaseReactiveHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) - .hasBean("couchbaseHealthContributor")); + .hasBean("couchbaseHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(CouchbaseHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) - .hasBean("couchbaseHealthContributor").doesNotHaveBean(CouchbaseHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(CouchbaseReactiveHealthIndicator.class) + .hasBean("couchbaseHealthContributor") + .doesNotHaveBean(CouchbaseHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.couchbase.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) - .doesNotHaveBean("couchbaseHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(CouchbaseReactiveHealthIndicator.class) + .doesNotHaveBean("couchbaseHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java index 789bbb6bf9..19f3f91fab 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/elasticsearch/ElasticsearchReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,31 +38,32 @@ import static org.assertj.core.api.Assertions.assertThat; class ElasticsearchReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchDataAutoConfiguration.class, - ReactiveElasticsearchClientAutoConfiguration.class, ElasticsearchRestClientAutoConfiguration.class, - ElasticsearchReactiveHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchDataAutoConfiguration.class, + ReactiveElasticsearchClientAutoConfiguration.class, ElasticsearchRestClientAutoConfiguration.class, + ElasticsearchReactiveHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchReactiveHealthIndicator.class).hasBean("elasticsearchHealthContributor")); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchReactiveHealthIndicator.class) + .hasBean("elasticsearchHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner - .withConfiguration(AutoConfigurations.of(ElasticsearchRestHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(ElasticsearchReactiveHealthIndicator.class) - .hasBean("elasticsearchHealthContributor") - .doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestHealthContributorAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchReactiveHealthIndicator.class) + .hasBean("elasticsearchHealthContributor") + .doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchReactiveHealthIndicator.class) - .doesNotHaveBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchReactiveHealthIndicator.class) + .doesNotHaveBean("elasticsearchHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoHealthContributorAutoConfigurationTests.java index c455c8e7ba..5febd132d6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,7 +46,7 @@ class MongoHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(MongoHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(MongoHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java index f8f690295b..9cb9ab07c5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/mongo/MongoReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,28 +38,29 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, - MongoReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + MongoReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) - .hasBean("mongoHealthContributor")); + .hasBean("mongoHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(MongoHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) - .hasBean("mongoHealthContributor").doesNotHaveBean(MongoHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) + .hasBean("mongoHealthContributor") + .doesNotHaveBean(MongoHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongo.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveHealthIndicator.class) - .doesNotHaveBean("mongoHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveHealthIndicator.class) + .doesNotHaveBean("mongoHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisHealthContributorAutoConfigurationTests.java index 806fdb1104..eda99dd58f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,20 +37,20 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, + RedisHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RedisHealthIndicator.class) - .doesNotHaveBean(RedisReactiveHealthIndicator.class)); + .doesNotHaveBean(RedisReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(RedisHealthIndicator.class) - .doesNotHaveBean(RedisReactiveHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RedisHealthIndicator.class) + .doesNotHaveBean(RedisReactiveHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisReactiveHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisReactiveHealthContributorAutoConfigurationTests.java index 082253d7d2..59c121f0b0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisReactiveHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/data/redis/RedisReactiveHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,27 +35,28 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisReactiveHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, - RedisReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, + RedisReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicator.class) - .hasBean("redisHealthContributor")); + .hasBean("redisHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisHealthContributorAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicator.class) - .hasBean("redisHealthContributor").doesNotHaveBean(RedisHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(RedisReactiveHealthIndicator.class) + .hasBean("redisHealthContributor") + .doesNotHaveBean(RedisHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.redis.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(RedisReactiveHealthIndicator.class) - .doesNotHaveBean("redisHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(RedisReactiveHealthIndicator.class) + .doesNotHaveBean("redisHealthContributor")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchRestHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchRestHealthContributorAutoConfigurationTests.java index a1294a97f7..9ccd4c7ef5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchRestHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchRestHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,35 +40,35 @@ import static org.assertj.core.api.Assertions.assertThat; class ElasticsearchRestHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, - ElasticsearchRestHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, + ElasticsearchRestHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { - this.contextRunner.run((context) -> assertThat(context) - .hasSingleBean(ElasticsearchRestClientHealthIndicator.class).hasBean("elasticsearchHealthContributor")); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) + .hasBean("elasticsearchHealthContributor")); } @Test void runWithoutRestClientShouldNotCreateIndicator() { this.contextRunner.withClassLoader(new FilteredClassLoader(RestClient.class)) - .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) - .doesNotHaveBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) + .doesNotHaveBean("elasticsearchHealthContributor")); } @Test void runWithRestClientShouldCreateIndicator() { this.contextRunner.withUserConfiguration(CustomRestClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) - .hasBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchRestClientHealthIndicator.class) + .hasBean("elasticsearchHealthContributor")); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.elasticsearch.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) - .doesNotHaveBean("elasticsearchHealthContributor")); + .run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchRestClientHealthIndicator.class) + .doesNotHaveBean("elasticsearchHealthContributor")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java index f4262b605a..4d1e4c6a4a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfigurationTests.java @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class EndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class)); @Test void mapShouldUseConfigurationConverter() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java index a0c61d295f..c19c434dae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,172 +37,219 @@ import static org.assertj.core.api.Assertions.assertThat; class ConditionalOnAvailableEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(AllEndpointsConfiguration.class); + .withUserConfiguration(AllEndpointsConfiguration.class); @Test void outcomeShouldMatchDefaults() { - this.contextRunner.run((context) -> assertThat(context).hasBean("health").doesNotHaveBean("spring") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + this.contextRunner.run((context) -> assertThat(context).hasBean("health") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWithEnabledByDefaultSetToFalseShouldNotMatchAnything() { this.contextRunner.withPropertyValues("management.endpoints.enabled-by-default=false") - .run((context) -> assertThat(context).doesNotHaveBean("info").doesNotHaveBean("health") - .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).doesNotHaveBean("info") + .doesNotHaveBean("health") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllWebShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") - .hasBean("spring").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("info") + .hasBean("health") + .hasBean("test") + .hasBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllWebAndDisablingEndpointShouldMatchEnabledEndpoints() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoint.test.enabled=false", "management.endpoint.health.enabled=false") - .run((context) -> assertThat(context).hasBean("info").doesNotHaveBean("health").doesNotHaveBean("test") - .hasBean("spring").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=*", "management.endpoint.test.enabled=false", + "management.endpoint.health.enabled=false") + .run((context) -> assertThat(context).hasBean("info") + .doesNotHaveBean("health") + .doesNotHaveBean("test") + .hasBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllWebAndEnablingEndpointDisabledByDefaultShouldMatchAll() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") - .hasBean("spring").hasBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=*", + "management.endpoint.shutdown.enabled=true") + .run((context) -> assertThat(context).hasBean("info") + .hasBean("health") + .hasBean("test") + .hasBean("spring") + .hasBean("shutdown")); } @Test void outcomeWhenIncludeAllJmxButJmxDisabledShouldMatchDefaults() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*") - .run((context) -> assertThat(context).hasBean("health").doesNotHaveBean("spring") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("health") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllJmxAndJmxEnabledShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true") - .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("test") - .hasBean("spring").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("info") + .hasBean("health") + .hasBean("test") + .hasBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeAllJmxAndJmxEnabledAndEnablingEndpointDisabledByDefaultShouldMatchAll() { this.contextRunner - .withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true", - "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).hasBean("health").hasBean("test").hasBean("spring") - .hasBean("shutdown")); + .withPropertyValues("management.endpoints.jmx.exposure.include=*", "spring.jmx.enabled=true", + "management.endpoint.shutdown.enabled=true") + .run((context) -> assertThat(context).hasBean("health") + .hasBean("test") + .hasBean("spring") + .hasBean("shutdown")); } @Test void outcomeWhenIncludeAllWebAndExcludeMatchesShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoints.web.exposure.exclude=spring,info") - .run((context) -> assertThat(context).hasBean("health").hasBean("test").doesNotHaveBean("info") - .doesNotHaveBean("spring").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=*", + "management.endpoints.web.exposure.exclude=spring,info") + .run((context) -> assertThat(context).hasBean("health") + .hasBean("test") + .doesNotHaveBean("info") + .doesNotHaveBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesAndExcludeMatchesShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", - "management.endpoints.web.exposure.exclude=spring,info") - .run((context) -> assertThat(context).hasBean("health").hasBean("test").doesNotHaveBean("info") - .doesNotHaveBean("spring").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", + "management.endpoints.web.exposure.exclude=spring,info") + .run((context) -> assertThat(context).hasBean("health") + .hasBean("test") + .doesNotHaveBean("info") + .doesNotHaveBean("spring") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesShouldMatchEnabledEndpoints() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=spring") - .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchOnDisabledEndpointShouldNotMatch() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=shutdown") - .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).doesNotHaveBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchOnEnabledEndpointShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=shutdown", - "management.endpoint.shutdown.enabled=true") - .run((context) -> assertThat(context).doesNotHaveBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").hasBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=shutdown", + "management.endpoint.shutdown.enabled=true") + .run((context) -> assertThat(context).doesNotHaveBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .hasBean("shutdown")); } @Test void outcomeWhenIncludeMatchesWithCaseShouldMatch() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sPRing") - .run((context) -> assertThat(context).hasBean("spring").doesNotHaveBean("health") - .doesNotHaveBean("info").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .run((context) -> assertThat(context).hasBean("spring") + .doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesAndExcludeAllShouldNotMatch() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", - "management.endpoints.web.exposure.exclude=*") - .run((context) -> assertThat(context).doesNotHaveBean("health").doesNotHaveBean("info") - .doesNotHaveBean("spring").doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=info,health,spring,test", + "management.endpoints.web.exposure.exclude=*") + .run((context) -> assertThat(context).doesNotHaveBean("health") + .doesNotHaveBean("info") + .doesNotHaveBean("spring") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWhenIncludeMatchesShouldMatchWithExtensionsAndComponents() { this.contextRunner.withUserConfiguration(ComponentEnabledIfEndpointIsExposedConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=spring") - .run((context) -> assertThat(context).hasBean("spring").hasBean("springComponent") - .hasBean("springExtension").doesNotHaveBean("info").doesNotHaveBean("health") - .doesNotHaveBean("test").doesNotHaveBean("shutdown")); + .withPropertyValues("management.endpoints.web.exposure.include=spring") + .run((context) -> assertThat(context).hasBean("spring") + .hasBean("springComponent") + .hasBean("springExtension") + .doesNotHaveBean("info") + .doesNotHaveBean("health") + .doesNotHaveBean("test") + .doesNotHaveBean("shutdown")); } @Test void outcomeWithNoEndpointReferenceShouldFail() { this.contextRunner.withUserConfiguration(ComponentWithNoEndpointReferenceConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=*").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getCause().getMessage()) - .contains("No endpoint is specified and the return type of the @Bean method " - + "is neither an @Endpoint, nor an @EndpointExtension"); - }); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure().getCause().getMessage()) + .contains("No endpoint is specified and the return type of the @Bean method " + + "is neither an @Endpoint, nor an @EndpointExtension"); + }); } @Test void outcomeOnCloudFoundryShouldMatchAll() { - this.contextRunner.withPropertyValues("VCAP_APPLICATION:---").run( - (context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); + this.contextRunner.withPropertyValues("VCAP_APPLICATION:---") + .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); } @Test // gh-21044 void outcomeWhenIncludeAllShouldMatchDashedEndpoint() { this.contextRunner.withUserConfiguration(DashedEndpointConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=*") + .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); } @Test // gh-21044 void outcomeWhenIncludeDashedShouldMatchDashedEndpoint() { this.contextRunner.withUserConfiguration(DashedEndpointConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=test-dashed") - .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=test-dashed") + .run((context) -> assertThat(context).hasSingleBean(DashedEndpoint.class)); } @Test void outcomeWhenEndpointNotExposedOnSpecifiedTechnology() { this.contextRunner.withUserConfiguration(ExposureEndpointConfiguration.class) - .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test", - "management.endpoints.web.exposure.exclude=test") - .run((context) -> assertThat(context).doesNotHaveBean("unexposed")); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test", + "management.endpoints.web.exposure.exclude=test") + .run((context) -> assertThat(context).doesNotHaveBean("unexposed")); } @Endpoint(id = "health") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java index aefe8aae5a..75737180e4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,31 +44,29 @@ class IncludeExcludeEndpointFilterTests { @Test void createWhenEndpointTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(null, new MockEnvironment(), "foo")) - .withMessageContaining("EndpointType must not be null"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(null, new MockEnvironment(), "foo")) + .withMessageContaining("EndpointType must not be null"); } @Test void createWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, null, "foo")) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, null, "foo")) + .withMessageContaining("Environment must not be null"); } @Test void createWhenPrefixIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null)) - .withMessageContaining("Prefix must not be empty"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), null)) + .withMessageContaining("Prefix must not be empty"); } @Test void createWhenPrefixIsEmptyShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), "")) - .withMessageContaining("Prefix must not be empty"); + .isThrownBy(() -> new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, new MockEnvironment(), "")) + .withMessageContaining("Prefix must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfigurationTests.java index 3288b28d46..950ea035e0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jackson/JacksonEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JacksonEndpointAutoConfigurationTests { private final ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JacksonEndpointAutoConfiguration.class)); @Test void endpointObjectMapperWhenNoProperty() { @@ -51,13 +51,13 @@ class JacksonEndpointAutoConfigurationTests { @Test void endpointObjectMapperWhenPropertyTrue() { this.runner.withPropertyValues("management.endpoints.jackson.isolated-object-mapper=true") - .run((context) -> assertThat(context).hasSingleBean(EndpointObjectMapper.class)); + .run((context) -> assertThat(context).hasSingleBean(EndpointObjectMapper.class)); } @Test void endpointObjectMapperWhenPropertyFalse() { this.runner.withPropertyValues("management.endpoints.jackson.isolated-object-mapper=false") - .run((context) -> assertThat(context).doesNotHaveBean(EndpointObjectMapper.class)); + .run((context) -> assertThat(context).doesNotHaveBean(EndpointObjectMapper.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java index 042780ac1d..491ebd0b76 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java @@ -94,7 +94,7 @@ class DefaultEndpointObjectNameFactoryTests { void generateObjectNameWithDuplicate() throws MalformedObjectNameException { this.contextId = "testContext"; given(this.mBeanServer.queryNames(new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), null)) - .willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test"))); + .willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test"))); ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test"))); assertThat(objectName).hasToString("org.springframework.boot:type=Endpoint,name=Test,context=testContext"); @@ -103,7 +103,8 @@ class DefaultEndpointObjectNameFactoryTests { private ObjectName generateObjectName(ExposableJmxEndpoint endpoint) { try { return new DefaultEndpointObjectNameFactory(this.properties, this.jmxProperties, this.mBeanServer, - this.contextId).getObjectName(endpoint); + this.contextId) + .getObjectName(endpoint); } catch (MalformedObjectNameException ex) { throw new AssertionError("Invalid object name", ex); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java index 68421710a4..a9ce553d31 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,46 +58,50 @@ class JmxEndpointAutoConfigurationTests { }; private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class, JmxAutoConfiguration.class, - JmxEndpointAutoConfiguration.class)) - .withUserConfiguration(TestEndpoint.class); + .withConfiguration(AutoConfigurations.of(EndpointAutoConfiguration.class, JmxAutoConfiguration.class, + JmxEndpointAutoConfiguration.class)) + .withUserConfiguration(TestEndpoint.class); private final MBeanServer mBeanServer = mock(MBeanServer.class); @Test void jmxEndpointWithoutJmxSupportNotAutoConfigured() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(MBeanServer.class) - .doesNotHaveBean(JmxEndpointDiscoverer.class).doesNotHaveBean(JmxEndpointExporter.class)); + .doesNotHaveBean(JmxEndpointDiscoverer.class) + .doesNotHaveBean(JmxEndpointExporter.class)); } @Test void jmxEndpointWithJmxSupportAutoConfigured() { - this.contextRunner.withPropertyValues("spring.jmx.enabled=true").with(mockMBeanServer()) - .run((context) -> assertThat(context).hasSingleBean(JmxEndpointDiscoverer.class) - .hasSingleBean(JmxEndpointExporter.class)); + this.contextRunner.withPropertyValues("spring.jmx.enabled=true") + .with(mockMBeanServer()) + .run((context) -> assertThat(context).hasSingleBean(JmxEndpointDiscoverer.class) + .hasSingleBean(JmxEndpointExporter.class)); } @Test void jmxEndpointWithCustomEndpointObjectNameFactory() { EndpointObjectNameFactory factory = mock(EndpointObjectNameFactory.class); this.contextRunner - .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test") - .with(mockMBeanServer()).withBean(EndpointObjectNameFactory.class, () -> factory).run((context) -> { - ArgumentCaptor argumentCaptor = ArgumentCaptor - .forClass(ExposableJmxEndpoint.class); - then(factory).should().getObjectName(argumentCaptor.capture()); - ExposableJmxEndpoint jmxEndpoint = argumentCaptor.getValue(); - assertThat(jmxEndpoint.getEndpointId().toLowerCaseString()).isEqualTo("test"); - }); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test") + .with(mockMBeanServer()) + .withBean(EndpointObjectNameFactory.class, () -> factory) + .run((context) -> { + ArgumentCaptor argumentCaptor = ArgumentCaptor + .forClass(ExposableJmxEndpoint.class); + then(factory).should().getObjectName(argumentCaptor.capture()); + ExposableJmxEndpoint jmxEndpoint = argumentCaptor.getValue(); + assertThat(jmxEndpoint.getEndpointId().toLowerCaseString()).isEqualTo("test"); + }); } @Test void jmxEndpointWithContextHierarchyGeneratesUniqueNamesForEachEndpoint() throws Exception { given(this.mBeanServer.queryNames(any(), any())) - .willReturn(new HashSet<>(Arrays.asList(new ObjectName("test:test=test")))); + .willReturn(new HashSet<>(Arrays.asList(new ObjectName("test:test=test")))); ArgumentCaptor objectName = ArgumentCaptor.forClass(ObjectName.class); ApplicationContextRunner jmxEnabledContextRunner = this.contextRunner - .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test"); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=test"); jmxEnabledContextRunner.with(mockMBeanServer()).run((parent) -> { jmxEnabledContextRunner.withParent(parent).run(NO_OPERATION); jmxEnabledContextRunner.withParent(parent).run(NO_OPERATION); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java index 32b7541323..577c7fbb2d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/MappingWebEndpointPathMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -43,14 +43,14 @@ class MappingWebEndpointPathMapperTests { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test", "custom")); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("test"))) - .isEqualTo("custom"); + .isEqualTo("custom"); } @Test void mixedCaseDefaultConfiguration() { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper(Collections.emptyMap()); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) - .isEqualTo("testEndpoint"); + .isEqualTo("testEndpoint"); } @Test @@ -58,7 +58,7 @@ class MappingWebEndpointPathMapperTests { MappingWebEndpointPathMapper mapper = new MappingWebEndpointPathMapper( Collections.singletonMap("test-endpoint", "custom")); assertThat(PathMapper.getRootPath(Collections.singletonList(mapper), EndpointId.of("testEndpoint"))) - .isEqualTo("custom"); + .isEqualTo("custom"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java index c29492d83d..0df0cf10d0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ServletEndpointManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(TestConfig.class); + .withUserConfiguration(TestConfig.class); @Test void contextShouldContainServletEndpointRegistrar() { @@ -70,7 +70,7 @@ class ServletEndpointManagementContextConfigurationTests { @Test void contextWhenNoServletBasedShouldNotContainServletEndpointRegistrar() { new ApplicationContextRunner().withUserConfiguration(TestConfig.class) - .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointRegistrar.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java index 6ed5a86179..941a132b4e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class WebEndpointAutoConfigurationTests { WebEndpointAutoConfiguration.class); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(CONFIGURATIONS); + .withConfiguration(CONFIGURATIONS); @Test void webApplicationConfiguresEndpointMediaTypes() { @@ -71,27 +71,27 @@ class WebEndpointAutoConfigurationTests { @Test void webApplicationConfiguresPathMapper() { this.contextRunner.withPropertyValues("management.endpoints.web.path-mapping.health=healthcheck") - .run((context) -> { - assertThat(context).hasSingleBean(PathMapper.class); - String pathMapping = context.getBean(PathMapper.class).getRootPath(EndpointId.of("health")); - assertThat(pathMapping).isEqualTo("healthcheck"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(PathMapper.class); + String pathMapping = context.getBean(PathMapper.class).getRootPath(EndpointId.of("health")); + assertThat(pathMapping).isEqualTo("healthcheck"); + }); } @Test void webApplicationSupportCustomPathMatcher() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoints.web.path-mapping.testanotherone=foo") - .withUserConfiguration(TestPathMatcher.class, TestOneEndpoint.class, TestAnotherOneEndpoint.class, - TestTwoEndpoint.class) - .run((context) -> { - WebEndpointDiscoverer discoverer = context.getBean(WebEndpointDiscoverer.class); - Collection endpoints = discoverer.getEndpoints(); - ExposableWebEndpoint[] webEndpoints = endpoints.toArray(new ExposableWebEndpoint[0]); - List paths = Arrays.stream(webEndpoints).map(PathMappedEndpoint::getRootPath).toList(); - assertThat(paths).containsOnly("1/testone", "foo", "testtwo"); - }); + .withPropertyValues("management.endpoints.web.exposure.include=*", + "management.endpoints.web.path-mapping.testanotherone=foo") + .withUserConfiguration(TestPathMatcher.class, TestOneEndpoint.class, TestAnotherOneEndpoint.class, + TestTwoEndpoint.class) + .run((context) -> { + WebEndpointDiscoverer discoverer = context.getBean(WebEndpointDiscoverer.class); + Collection endpoints = discoverer.getEndpoints(); + ExposableWebEndpoint[] webEndpoints = endpoints.toArray(new ExposableWebEndpoint[0]); + List paths = Arrays.stream(webEndpoints).map(PathMappedEndpoint::getRootPath).toList(); + assertThat(paths).containsOnly("1/testone", "foo", "testtwo"); + }); } @Test @@ -104,9 +104,8 @@ class WebEndpointAutoConfigurationTests { @Test void webApplicationConfiguresExposeExcludePropertyEndpointFilter() { - this.contextRunner - .run((context) -> assertThat(context).getBeans(IncludeExcludeEndpointFilter.class).containsKeys( - "webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter")); + this.contextRunner.run((context) -> assertThat(context).getBeans(IncludeExcludeEndpointFilter.class) + .containsKeys("webExposeExcludePropertyEndpointFilter", "controllerExposeExcludePropertyEndpointFilter")); } @Test @@ -117,7 +116,7 @@ class WebEndpointAutoConfigurationTests { @Test void contextWhenNotServletShouldNotConfigureServletEndpointDiscoverer() { new ApplicationContextRunner().withConfiguration(CONFIGURATIONS) - .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServletEndpointDiscoverer.class)); } @Component diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java index 34a4661521..441d15bf66 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java @@ -47,7 +47,7 @@ class WebEndpointPropertiesTests { void basePathMustStartWithSlash() { WebEndpointProperties properties = new WebEndpointProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setBasePath("admin")) - .withMessageContaining("Base path must start with '/' or be empty"); + .withMessageContaining("Base path must start with '/' or be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java index e3eebbf8c4..d8f93a6dcf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AbstractEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -102,14 +102,18 @@ public abstract class AbstractEndpointDocumentationTests { protected FieldDescriptor parentIdField() { return fieldWithPath("contexts.*.parentId").description("Id of the parent application context, if any.") - .optional().type(JsonFieldType.STRING); + .optional() + .type(JsonFieldType.STRING); } @SuppressWarnings("unchecked") private Map select(Map candidates, Predicate filter) { Map selected = new HashMap<>(); - candidates.entrySet().stream().filter((candidate) -> filter.test((T) candidate)).limit(3) - .forEach((entry) -> selected.put(entry.getKey(), entry.getValue())); + candidates.entrySet() + .stream() + .filter((candidate) -> filter.test((T) candidate)) + .limit(3) + .forEach((entry) -> selected.put(entry.getKey(), entry.getValue())); return selected; } @@ -135,7 +139,7 @@ public abstract class AbstractEndpointDocumentationTests { public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof EndpointObjectMapper) { return (EndpointObjectMapper) () -> ((EndpointObjectMapper) bean).get() - .enable(SerializationFeature.INDENT_OUTPUT); + .enable(SerializationFeature.INDENT_OUTPUT); } return bean; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java index 9319578d51..99d2b44528 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/AuditEventsEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,13 +56,15 @@ class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentation void allAuditEvents() throws Exception { String queryTimestamp = "2017-11-07T09:37Z"; given(this.repository.find(any(), any(), any())) - .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); - this.mockMvc.perform(get("/actuator/auditevents").param("after", queryTimestamp)).andExpect(status().isOk()) - .andDo(document("auditevents/all", responseFields( - fieldWithPath("events").description("An array of audit events."), - fieldWithPath("events.[].timestamp").description("The timestamp of when the event occurred."), - fieldWithPath("events.[].principal").description("The principal that triggered the event."), - fieldWithPath("events.[].type").description("The type of the event.")))); + .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); + this.mockMvc.perform(get("/actuator/auditevents").param("after", queryTimestamp)) + .andExpect(status().isOk()) + .andDo(document("auditevents/all", + responseFields(fieldWithPath("events").description("An array of audit events."), + fieldWithPath("events.[].timestamp") + .description("The timestamp of when the event occurred."), + fieldWithPath("events.[].principal").description("The principal that triggered the event."), + fieldWithPath("events.[].type").description("The type of the event.")))); } @Test @@ -70,19 +72,20 @@ class AuditEventsEndpointDocumentationTests extends MockMvcEndpointDocumentation OffsetDateTime now = OffsetDateTime.now(); String queryTimestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(now); given(this.repository.find("alice", now.toInstant(), "logout")) - .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); + .willReturn(Arrays.asList(new AuditEvent("alice", "logout", Collections.emptyMap()))); this.mockMvc - .perform(get("/actuator/auditevents") - .param("principal", "alice").param("after", queryTimestamp).param("type", "logout")) - .andExpect(status().isOk()) - .andDo(document("auditevents/filtered", - queryParameters( - parameterWithName("after").description( - "Restricts the events to those that occurred after the given time. Optional."), - parameterWithName("principal").description( - "Restricts the events to those with the given principal. Optional."), - parameterWithName("type") - .description("Restricts the events to those with the given type. Optional.")))); + .perform(get("/actuator/auditevents").param("principal", "alice") + .param("after", queryTimestamp) + .param("type", "logout")) + .andExpect(status().isOk()) + .andDo(document("auditevents/filtered", + queryParameters( + parameterWithName("after").description( + "Restricts the events to those that occurred after the given time. Optional."), + parameterWithName("principal") + .description("Restricts the events to those with the given principal. Optional."), + parameterWithName("type") + .description("Restricts the events to those with the given type. Optional.")))); then(this.repository).should().find("alice", now.toInstant(), "logout"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java index 41a4ae8563..282eb162f1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/BeansEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -53,18 +53,20 @@ class BeansEndpointDocumentationTests extends MockMvcEndpointDocumentationTests List beanFields = Arrays.asList(fieldWithPath("aliases").description("Names of any aliases."), fieldWithPath("scope").description("Scope of the bean."), fieldWithPath("type").description("Fully qualified type of the bean."), - fieldWithPath("resource").description("Resource in which the bean was defined, if any.").optional() - .type(JsonFieldType.STRING), + fieldWithPath("resource").description("Resource in which the bean was defined, if any.") + .optional() + .type(JsonFieldType.STRING), fieldWithPath("dependencies").description("Names of any dependencies.")); ResponseFieldsSnippet responseFields = responseFields( fieldWithPath("contexts").description("Application contexts keyed by id."), parentIdField(), fieldWithPath("contexts.*.beans").description("Beans in the application context keyed by name.")) - .andWithPrefix("contexts.*.beans.*.", beanFields); - this.mockMvc.perform(get("/actuator/beans")).andExpect(status().isOk()) - .andDo(document("beans", - preprocessResponse( - limit(this::isIndependentBean, "contexts", getApplicationContext().getId(), "beans")), - responseFields)); + .andWithPrefix("contexts.*.beans.*.", beanFields); + this.mockMvc.perform(get("/actuator/beans")) + .andExpect(status().isOk()) + .andDo(document("beans", + preprocessResponse( + limit(this::isIndependentBean, "contexts", getApplicationContext().getId(), "beans")), + responseFields)); } private boolean isIndependentBean(Entry> bean) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java index fe6f374d88..ba1fc9346e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/CachesEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,38 +56,42 @@ class CachesEndpointDocumentationTests extends MockMvcEndpointDocumentationTests fieldWithPath("target").description("Fully qualified name of the native cache.")); private static final List queryParameters = Collections - .singletonList(parameterWithName("cacheManager").description( - "Name of the cacheManager to qualify the cache. May be omitted if the cache name is unique.") - .optional()); + .singletonList(parameterWithName("cacheManager") + .description("Name of the cacheManager to qualify the cache. May be omitted if the cache name is unique.") + .optional()); @Test void allCaches() throws Exception { - this.mockMvc.perform(get("/actuator/caches")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("caches/all", - responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."), - fieldWithPath("cacheManagers.*.caches") - .description("Caches in the application context keyed by name.")) - .andWithPrefix("cacheManagers.*.caches.*.", fieldWithPath("target") - .description("Fully qualified name of the native cache.")))); + this.mockMvc.perform(get("/actuator/caches")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("caches/all", + responseFields(fieldWithPath("cacheManagers").description("Cache managers keyed by id."), + fieldWithPath("cacheManagers.*.caches") + .description("Caches in the application context keyed by name.")) + .andWithPrefix("cacheManagers.*.caches.*.", + fieldWithPath("target").description("Fully qualified name of the native cache.")))); } @Test void namedCache() throws Exception { - this.mockMvc.perform(get("/actuator/caches/cities")).andExpect(status().isOk()).andDo(MockMvcRestDocumentation - .document("caches/named", queryParameters(queryParameters), responseFields(levelFields))); + this.mockMvc.perform(get("/actuator/caches/cities")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("caches/named", queryParameters(queryParameters), + responseFields(levelFields))); } @Test void evictAllCaches() throws Exception { - this.mockMvc.perform(delete("/actuator/caches")).andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("caches/evict-all")); + this.mockMvc.perform(delete("/actuator/caches")) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("caches/evict-all")); } @Test void evictNamedCache() throws Exception { this.mockMvc.perform(delete("/actuator/caches/countries?cacheManager=anotherCacheManager")) - .andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("caches/evict-named", queryParameters(queryParameters))); + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("caches/evict-named", queryParameters(queryParameters))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java index 40c2e1194d..3e36dff8ad 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConditionsReportEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -60,7 +60,8 @@ class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocument @BeforeEach void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()).build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()) + .build(); } @Test @@ -76,19 +77,22 @@ class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocument fieldWithPath(".*.notMatched.[].message").description("Details of why the condition was not matched."), fieldWithPath(".*.matched").description("Conditions that were matched."), fieldWithPath(".*.matched.[].condition").description("Name of the condition.") - .type(JsonFieldType.STRING).optional(), + .type(JsonFieldType.STRING) + .optional(), fieldWithPath(".*.matched.[].message").description("Details of why the condition was matched.") - .type(JsonFieldType.STRING).optional()); + .type(JsonFieldType.STRING) + .optional()); FieldDescriptor unconditionalClassesField = fieldWithPath("contexts.*.unconditionalClasses") - .description("Names of unconditional auto-configuration classes if any."); - this.mockMvc.perform(get("/actuator/conditions")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("conditions", - preprocessResponse(limit("contexts", getApplicationContext().getId(), "positiveMatches"), - limit("contexts", getApplicationContext().getId(), "negativeMatches")), - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id.")) - .andWithPrefix("contexts.*.positiveMatches", positiveMatchFields) - .andWithPrefix("contexts.*.negativeMatches", negativeMatchFields) - .and(unconditionalClassesField, parentIdField()))); + .description("Names of unconditional auto-configuration classes if any."); + this.mockMvc.perform(get("/actuator/conditions")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("conditions", + preprocessResponse(limit("contexts", getApplicationContext().getId(), "positiveMatches"), + limit("contexts", getApplicationContext().getId(), "negativeMatches")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id.")) + .andWithPrefix("contexts.*.positiveMatches", positiveMatchFields) + .andWithPrefix("contexts.*.negativeMatches", negativeMatchFields) + .and(unconditionalClassesField, parentIdField()))); } @Configuration(proxyBeanMethods = false) @@ -98,9 +102,9 @@ class ConditionsReportEndpointDocumentationTests extends MockMvcEndpointDocument @Bean ConditionsReportEndpoint autoConfigurationReportEndpoint(ConfigurableApplicationContext context) { ConditionEvaluationReport conditionEvaluationReport = ConditionEvaluationReport - .get(context.getBeanFactory()); + .get(context.getBeanFactory()); conditionEvaluationReport - .recordEvaluationCandidates(Arrays.asList(PropertyPlaceholderAutoConfiguration.class.getName())); + .recordEvaluationCandidates(Arrays.asList(PropertyPlaceholderAutoConfiguration.class.getName())); return new ConditionsReportEndpoint(context); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java index 598476ad24..d29a789351 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ConfigurationPropertiesReportEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,36 +45,38 @@ class ConfigurationPropertiesReportEndpointDocumentationTests extends MockMvcEnd @Test void configProps() throws Exception { - this.mockMvc.perform(get("/actuator/configprops")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("configprops/all", - preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), - fieldWithPath("contexts.*.beans.*") - .description("`@ConfigurationProperties` beans keyed by bean name."), - fieldWithPath("contexts.*.beans.*.prefix") - .description("Prefix applied to the names of the bean's properties."), - subsectionWithPath("contexts.*.beans.*.properties") - .description("Properties of the bean as name-value pairs."), - subsectionWithPath("contexts.*.beans.*.inputs").description( - "Origin and value of the configuration property used when binding to this bean."), - parentIdField()))); + this.mockMvc.perform(get("/actuator/configprops")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("configprops/all", + preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), + fieldWithPath("contexts.*.beans.*") + .description("`@ConfigurationProperties` beans keyed by bean name."), + fieldWithPath("contexts.*.beans.*.prefix") + .description("Prefix applied to the names of the bean's properties."), + subsectionWithPath("contexts.*.beans.*.properties") + .description("Properties of the bean as name-value pairs."), + subsectionWithPath("contexts.*.beans.*.inputs").description( + "Origin and value of the configuration property used when binding to this bean."), + parentIdField()))); } @Test void configPropsFilterByPrefix() throws Exception { - this.mockMvc.perform(get("/actuator/configprops/spring.jackson")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("configprops/prefixed", - preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), - fieldWithPath("contexts.*.beans.*") - .description("`@ConfigurationProperties` beans keyed by bean name."), - fieldWithPath("contexts.*.beans.*.prefix") - .description("Prefix applied to the names of the bean's properties."), - subsectionWithPath("contexts.*.beans.*.properties") - .description("Properties of the bean as name-value pairs."), - subsectionWithPath("contexts.*.beans.*.inputs").description( - "Origin and value of the configuration property used when binding to this bean."), - parentIdField()))); + this.mockMvc.perform(get("/actuator/configprops/spring.jackson")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("configprops/prefixed", + preprocessResponse(limit("contexts", getApplicationContext().getId(), "beans")), + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id."), + fieldWithPath("contexts.*.beans.*") + .description("`@ConfigurationProperties` beans keyed by bean name."), + fieldWithPath("contexts.*.beans.*.prefix") + .description("Prefix applied to the names of the bean's properties."), + subsectionWithPath("contexts.*.beans.*.properties") + .description("Properties of the bean as name-value pairs."), + subsectionWithPath("contexts.*.beans.*.inputs").description( + "Origin and value of the configuration property used when binding to this bean."), + parentIdField()))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java index 7de7b7e380..061f6e8eaf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/EnvironmentEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,46 +62,53 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { private static final FieldDescriptor activeProfiles = fieldWithPath("activeProfiles") - .description("Names of the active profiles, if any."); + .description("Names of the active profiles, if any."); private static final FieldDescriptor propertySources = fieldWithPath("propertySources") - .description("Property sources in order of precedence."); + .description("Property sources in order of precedence."); private static final FieldDescriptor propertySourceName = fieldWithPath("propertySources.[].name") - .description("Name of the property source."); + .description("Name of the property source."); @Test void env() throws Exception { - this.mockMvc.perform(get("/actuator/env")).andExpect(status().isOk()) - .andDo(document("env/all", preprocessResponse(replacePattern( - Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), - ""), filterProperties()), - responseFields(activeProfiles, propertySources, propertySourceName, - fieldWithPath("propertySources.[].properties") - .description("Properties in the property source keyed by property name."), - fieldWithPath("propertySources.[].properties.*.value") - .description("Value of the property."), - fieldWithPath("propertySources.[].properties.*.origin") - .description("Origin of the property, if any.").optional()))); + this.mockMvc.perform(get("/actuator/env")) + .andExpect(status().isOk()) + .andDo(document("env/all", + preprocessResponse( + replacePattern(Pattern.compile( + "org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), ""), + filterProperties()), + responseFields(activeProfiles, propertySources, propertySourceName, + fieldWithPath("propertySources.[].properties") + .description("Properties in the property source keyed by property name."), + fieldWithPath("propertySources.[].properties.*.value") + .description("Value of the property."), + fieldWithPath("propertySources.[].properties.*.origin") + .description("Origin of the property, if any.") + .optional()))); } @Test void singlePropertyFromEnv() throws Exception { - this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")).andExpect(status().isOk()).andDo(document( - "env/single", - preprocessResponse(replacePattern( - Pattern.compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), - "")), - responseFields( - fieldWithPath("property").description("Property from the environment, if found.").optional(), - fieldWithPath("property.source").description("Name of the source of the property."), - fieldWithPath("property.value").description("Value of the property."), activeProfiles, - propertySources, propertySourceName, - fieldWithPath("propertySources.[].property") - .description("Property in the property source, if any.").optional(), - fieldWithPath("propertySources.[].property.value").description("Value of the property."), - fieldWithPath("propertySources.[].property.origin") - .description("Origin of the property, if any.").optional()))); + this.mockMvc.perform(get("/actuator/env/com.example.cache.max-size")) + .andExpect(status().isOk()) + .andDo(document("env/single", + preprocessResponse(replacePattern(Pattern + .compile("org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/"), "")), + responseFields( + fieldWithPath("property").description("Property from the environment, if found.") + .optional(), + fieldWithPath("property.source").description("Name of the source of the property."), + fieldWithPath("property.value").description("Value of the property."), activeProfiles, + propertySources, propertySourceName, + fieldWithPath("propertySources.[].property") + .description("Property in the property source, if any.") + .optional(), + fieldWithPath("propertySources.[].property.value").description("Value of the property."), + fieldWithPath("propertySources.[].property.origin") + .description("Origin of the property, if any.") + .optional()))); } private OperationPreprocessor filterProperties() { @@ -116,8 +123,11 @@ class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentation List> propertySources = (List>) payload.get("propertySources"); for (Map propertySource : propertySources) { Map properties = (Map) propertySource.get("properties"); - Set filteredKeys = properties.keySet().stream().filter(this::retainKey).limit(3) - .collect(Collectors.toSet()); + Set filteredKeys = properties.keySet() + .stream() + .filter(this::retainKey) + .limit(3) + .collect(Collectors.toSet()); properties.keySet().retainAll(filteredKeys); } return objectMapper.writeValueAsBytes(payload); @@ -141,8 +151,10 @@ class EnvironmentEndpointDocumentationTests extends MockMvcEndpointDocumentation @Override protected void customizePropertySources(MutablePropertySources propertySources) { - environment.getPropertySources().stream().filter(this::includedPropertySource) - .forEach(propertySources::addLast); + environment.getPropertySources() + .stream() + .filter(this::includedPropertySource) + .forEach(propertySources::addLast); } private boolean includedPropertySource(PropertySource propertySource) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java index d4bd0c2335..154f0f217a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/FlywayEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,34 +50,36 @@ class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests @Test void flyway() throws Exception { - this.mockMvc.perform(get("/actuator/flyway")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("flyway", - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), - fieldWithPath("contexts.*.flywayBeans.*.migrations").description( - "Migrations performed by the Flyway instance, keyed by Flyway bean name.")) - .andWithPrefix("contexts.*.flywayBeans.*.migrations.[].", - migrationFieldDescriptors()) - .and(parentIdField()))); + this.mockMvc.perform(get("/actuator/flyway")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("flyway", + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), + fieldWithPath("contexts.*.flywayBeans.*.migrations") + .description("Migrations performed by the Flyway instance, keyed by Flyway bean name.")) + .andWithPrefix("contexts.*.flywayBeans.*.migrations.[].", migrationFieldDescriptors()) + .and(parentIdField()))); } private List migrationFieldDescriptors() { return Arrays.asList(fieldWithPath("checksum").description("Checksum of the migration, if any.").optional(), fieldWithPath("description").description("Description of the migration, if any.").optional(), fieldWithPath("executionTime").description("Execution time in milliseconds of an applied migration.") - .optional(), + .optional(), fieldWithPath("installedBy").description("User that installed the applied migration, if any.") - .optional(), + .optional(), fieldWithPath("installedOn") - .description("Timestamp of when the applied migration was installed, if any.").optional(), + .description("Timestamp of when the applied migration was installed, if any.") + .optional(), fieldWithPath("installedRank") - .description("Rank of the applied migration, if any. Later migrations have higher ranks.") - .optional(), + .description("Rank of the applied migration, if any. Later migrations have higher ranks.") + .optional(), fieldWithPath("script").description("Name of the script used to execute the migration, if any.") - .optional(), + .optional(), fieldWithPath("state") - .description("State of the migration. (" + describeEnumValues(MigrationState.class) + ")"), - fieldWithPath("type").description("Type of the migration."), fieldWithPath("version") - .description("Version of the database after applying the migration, if any.").optional()); + .description("State of the migration. (" + describeEnumValues(MigrationState.class) + ")"), + fieldWithPath("type").description("Type of the migration."), + fieldWithPath("version").description("Version of the database after applying the migration, if any.") + .optional()); } @Configuration(proxyBeanMethods = false) @@ -88,7 +90,8 @@ class FlywayEndpointDocumentationTests extends MockMvcEndpointDocumentationTests @Bean DataSource dataSource() { return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()).build(); + .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()) + .build(); } @Bean diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java index a512ca7a1b..8d47a690cb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HealthEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -77,28 +77,32 @@ class HealthEndpointDocumentationTests extends MockMvcEndpointDocumentationTests FieldDescriptor status = fieldWithPath("status").description("Overall status of the application."); FieldDescriptor components = fieldWithPath("components").description("The components that make up the health."); FieldDescriptor componentStatus = fieldWithPath("components.*.status") - .description("Status of a specific part of the application."); + .description("Status of a specific part of the application."); FieldDescriptor nestedComponents = subsectionWithPath("components.*.components") - .description("The nested components that make up the health.").optional(); + .description("The nested components that make up the health.") + .optional(); FieldDescriptor componentDetails = subsectionWithPath("components.*.details") - .description("Details of the health of a specific part of the application. " - + "Presence is controlled by `management.endpoint.health.show-details`.") - .optional(); - this.mockMvc.perform(get("/actuator/health").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("health", - responseFields(status, components, componentStatus, nestedComponents, componentDetails))); + .description("Details of the health of a specific part of the application. " + + "Presence is controlled by `management.endpoint.health.show-details`.") + .optional(); + this.mockMvc.perform(get("/actuator/health").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("health", + responseFields(status, components, componentStatus, nestedComponents, componentDetails))); } @Test void healthComponent() throws Exception { - this.mockMvc.perform(get("/actuator/health/db").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andDo(document("health/component", responseFields(componentFields))); + this.mockMvc.perform(get("/actuator/health/db").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(document("health/component", responseFields(componentFields))); } @Test void healthComponentInstance() throws Exception { this.mockMvc.perform(get("/actuator/health/broker/us1").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()).andDo(document("health/instance", responseFields(componentFields))); + .andExpect(status().isOk()) + .andDo(document("health/instance", responseFields(componentFields))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java index 21a44aab9b..fc0f19fc1b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HeapDumpWebEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,17 +45,18 @@ class HeapDumpWebEndpointDocumentationTests extends MockMvcEndpointDocumentation @Test void heapDump() throws Exception { - this.mockMvc.perform(get("/actuator/heapdump")).andExpect(status().isOk()) - .andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { + this.mockMvc.perform(get("/actuator/heapdump")) + .andExpect(status().isOk()) + .andDo(document("heapdump", new CurlRequestSnippet(CliDocumentation.multiLineFormat()) { - @Override - protected Map createModel(Operation operation) { - Map model = super.createModel(operation); - model.put("options", "-O"); - return model; - } + @Override + protected Map createModel(Operation operation) { + Map model = super.createModel(operation); + model.put("options", "-O"); + return model; + } - })); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpExchangesEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpExchangesEndpointDocumentationTests.java index 02de9f4403..9f757f2af5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpExchangesEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/HttpExchangesEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,41 +66,44 @@ class HttpExchangesEndpointDocumentationTests extends MockMvcEndpointDocumentati given(request.getUri()).willReturn(URI.create("https://api.example.com")); given(request.getMethod()).willReturn("GET"); given(request.getHeaders()) - .willReturn(Collections.singletonMap(HttpHeaders.ACCEPT, Arrays.asList("application/json"))); + .willReturn(Collections.singletonMap(HttpHeaders.ACCEPT, Arrays.asList("application/json"))); RecordableHttpResponse response = mock(RecordableHttpResponse.class); given(response.getStatus()).willReturn(200); given(response.getHeaders()) - .willReturn(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json"))); + .willReturn(Collections.singletonMap(HttpHeaders.CONTENT_TYPE, Arrays.asList("application/json"))); Principal principal = mock(Principal.class); given(principal.getName()).willReturn("alice"); Instant instant = Instant.parse("2022-12-22T13:43:41.00Z"); Clock start = Clock.fixed(instant, ZoneId.systemDefault()); Clock end = Clock.offset(start, Duration.ofMillis(23)); - HttpExchange exchange = HttpExchange.start(start, request).finish(end, response, () -> principal, - () -> UUID.randomUUID().toString(), EnumSet.allOf(Include.class)); + HttpExchange exchange = HttpExchange.start(start, request) + .finish(end, response, () -> principal, () -> UUID.randomUUID().toString(), EnumSet.allOf(Include.class)); given(this.repository.findAll()).willReturn(Arrays.asList(exchange)); - this.mockMvc.perform(get("/actuator/httpexchanges")).andExpect(status().isOk()).andDo(document("httpexchanges", - responseFields(fieldWithPath("exchanges").description("An array of HTTP request-response exchanges."), - fieldWithPath("exchanges.[].timestamp").description("Timestamp of when the exchange occurred."), - fieldWithPath("exchanges.[].principal").description("Principal of the exchange, if any.") - .optional(), - fieldWithPath("exchanges.[].principal.name").description("Name of the principal.").optional(), - fieldWithPath("exchanges.[].request.method").description("HTTP method of the request."), - fieldWithPath("exchanges.[].request.remoteAddress") - .description("Remote address from which the request was received, if known.").optional() - .type(JsonFieldType.STRING), - fieldWithPath("exchanges.[].request.uri").description("URI of the request."), - fieldWithPath("exchanges.[].request.headers") - .description("Headers of the request, keyed by header name."), - fieldWithPath("exchanges.[].request.headers.*.[]").description("Values of the header"), - fieldWithPath("exchanges.[].response.status").description("Status of the response"), - fieldWithPath("exchanges.[].response.headers") - .description("Headers of the response, keyed by header name."), - fieldWithPath("exchanges.[].response.headers.*.[]").description("Values of the header"), - fieldWithPath("exchanges.[].session") - .description("Session associated with the exchange, if any.").optional(), - fieldWithPath("exchanges.[].session.id").description("ID of the session."), - fieldWithPath("exchanges.[].timeTaken").description("Time taken to handle the exchange.")))); + this.mockMvc.perform(get("/actuator/httpexchanges")) + .andExpect(status().isOk()) + .andDo(document("httpexchanges", responseFields( + fieldWithPath("exchanges").description("An array of HTTP request-response exchanges."), + fieldWithPath("exchanges.[].timestamp").description("Timestamp of when the exchange occurred."), + fieldWithPath("exchanges.[].principal").description("Principal of the exchange, if any.") + .optional(), + fieldWithPath("exchanges.[].principal.name").description("Name of the principal.").optional(), + fieldWithPath("exchanges.[].request.method").description("HTTP method of the request."), + fieldWithPath("exchanges.[].request.remoteAddress") + .description("Remote address from which the request was received, if known.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("exchanges.[].request.uri").description("URI of the request."), + fieldWithPath("exchanges.[].request.headers") + .description("Headers of the request, keyed by header name."), + fieldWithPath("exchanges.[].request.headers.*.[]").description("Values of the header"), + fieldWithPath("exchanges.[].response.status").description("Status of the response"), + fieldWithPath("exchanges.[].response.headers") + .description("Headers of the response, keyed by header name."), + fieldWithPath("exchanges.[].response.headers.*.[]").description("Values of the header"), + fieldWithPath("exchanges.[].session").description("Session associated with the exchange, if any.") + .optional(), + fieldWithPath("exchanges.[].session.id").description("ID of the session."), + fieldWithPath("exchanges.[].timeTaken").description("Time taken to handle the exchange.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java index 900e43fea7..39987ab5c5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/InfoEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,24 +49,25 @@ class InfoEndpointDocumentationTests extends MockMvcEndpointDocumentationTests { @Test void info() throws Exception { - this.mockMvc.perform(get("/actuator/info")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("info", - responseFields(beneathPath("git"), - fieldWithPath("branch").description("Name of the Git branch, if any."), - fieldWithPath("commit").description("Details of the Git commit, if any."), - fieldWithPath("commit.time").description("Timestamp of the commit, if any.") - .type(JsonFieldType.VARIES), - fieldWithPath("commit.id").description("ID of the commit, if any.")), - responseFields(beneathPath("build"), - fieldWithPath("artifact").description("Artifact ID of the application, if any.") - .optional(), - fieldWithPath("group").description("Group ID of the application, if any.").optional(), - fieldWithPath("name").description("Name of the application, if any.") - .type(JsonFieldType.STRING).optional(), - fieldWithPath("version").description("Version of the application, if any.").optional(), - fieldWithPath("time") - .description("Timestamp of when the application was built, if any.") - .type(JsonFieldType.VARIES).optional()))); + this.mockMvc.perform(get("/actuator/info")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("info", + responseFields(beneathPath("git"), + fieldWithPath("branch").description("Name of the Git branch, if any."), + fieldWithPath("commit").description("Details of the Git commit, if any."), + fieldWithPath("commit.time").description("Timestamp of the commit, if any.") + .type(JsonFieldType.VARIES), + fieldWithPath("commit.id").description("ID of the commit, if any.")), + responseFields(beneathPath("build"), + fieldWithPath("artifact").description("Artifact ID of the application, if any.").optional(), + fieldWithPath("group").description("Group ID of the application, if any.").optional(), + fieldWithPath("name").description("Name of the application, if any.") + .type(JsonFieldType.STRING) + .optional(), + fieldWithPath("version").description("Version of the application, if any.").optional(), + fieldWithPath("time").description("Timestamp of when the application was built, if any.") + .type(JsonFieldType.VARIES) + .optional()))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java index ed3509172b..36e7fb1e65 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/IntegrationGraphEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -39,14 +39,16 @@ class IntegrationGraphEndpointDocumentationTests extends MockMvcEndpointDocument @Test void graph() throws Exception { - this.mockMvc.perform(get("/actuator/integrationgraph")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("integrationgraph/graph")); + this.mockMvc.perform(get("/actuator/integrationgraph")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("integrationgraph/graph")); } @Test void rebuild() throws Exception { - this.mockMvc.perform(post("/actuator/integrationgraph")).andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild")); + this.mockMvc.perform(post("/actuator/integrationgraph")) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("integrationgraph/rebuild")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java index e72a660e50..50329c8f86 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LiquibaseEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -48,14 +48,14 @@ class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTe @Test void liquibase() throws Exception { FieldDescriptor changeSetsField = fieldWithPath("contexts.*.liquibaseBeans.*.changeSets") - .description("Change sets made by the Liquibase beans, keyed by bean name."); - this.mockMvc.perform(get("/actuator/liquibase")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("liquibase", - responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), - changeSetsField) - .andWithPrefix("contexts.*.liquibaseBeans.*.changeSets[].", - getChangeSetFieldDescriptors()) - .and(parentIdField()))); + .description("Change sets made by the Liquibase beans, keyed by bean name."); + this.mockMvc.perform(get("/actuator/liquibase")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("liquibase", + responseFields(fieldWithPath("contexts").description("Application contexts keyed by id"), + changeSetsField) + .andWithPrefix("contexts.*.liquibaseBeans.*.changeSets[].", getChangeSetFieldDescriptors()) + .and(parentIdField()))); } private List getChangeSetFieldDescriptors() { @@ -67,13 +67,14 @@ class LiquibaseEndpointDocumentationTests extends MockMvcEndpointDocumentationTe fieldWithPath("deploymentId").description("ID of the deployment that ran the change set."), fieldWithPath("description").description("Description of the change set."), fieldWithPath("execType") - .description("Execution type of the change set (" + describeEnumValues(ExecType.class) + ")."), + .description("Execution type of the change set (" + describeEnumValues(ExecType.class) + ")."), fieldWithPath("id").description("ID of the change set."), fieldWithPath("labels").description("Labels associated with the change set."), fieldWithPath("checksum").description("Checksum of the change set."), fieldWithPath("orderExecuted").description("Order of the execution of the change set."), - fieldWithPath("tag").description("Tag associated with the change set, if any.").optional() - .type(JsonFieldType.STRING)); + fieldWithPath("tag").description("Tag associated with the change set, if any.") + .optional() + .type(JsonFieldType.STRING)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java index 668c702e84..cb80ee01f2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LogFileWebEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -38,14 +38,16 @@ class LogFileWebEndpointDocumentationTests extends MockMvcEndpointDocumentationT @Test void logFile() throws Exception { - this.mockMvc.perform(get("/actuator/logfile")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("logfile/entire")); + this.mockMvc.perform(get("/actuator/logfile")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("logfile/entire")); } @Test void logFileRange() throws Exception { this.mockMvc.perform(get("/actuator/logfile").header("Range", "bytes=0-1023")) - .andExpect(status().isPartialContent()).andDo(MockMvcRestDocumentation.document("logfile/range")); + .andExpect(status().isPartialContent()) + .andDo(MockMvcRestDocumentation.document("logfile/range")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java index ff01109eb1..33f90fbe75 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/LoggersEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,10 +62,10 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest private static final List groupLevelFields; static { - groupLevelFields = Arrays.asList( - fieldWithPath("configuredLevel").description("Configured level of the logger group, if any.") - .type(JsonFieldType.STRING).optional(), - fieldWithPath("members").description("Loggers that are part of this group")); + groupLevelFields = Arrays + .asList(fieldWithPath("configuredLevel").description("Configured level of the logger group, if any.") + .type(JsonFieldType.STRING) + .optional(), fieldWithPath("members").description("Loggers that are part of this group")); } @MockBean @@ -78,55 +78,60 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest void allLoggers() throws Exception { given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), - new LoggerConfiguration("com.example", LogLevel.DEBUG, LogLevel.DEBUG))); - this.mockMvc.perform(get("/actuator/loggers")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("loggers/all", - responseFields(fieldWithPath("levels").description("Levels support by the logging system."), - fieldWithPath("loggers").description("Loggers keyed by name."), - fieldWithPath("groups").description("Logger groups keyed by name")) - .andWithPrefix("loggers.*.", levelFields) - .andWithPrefix("groups.*.", groupLevelFields))); + .willReturn(Arrays.asList(new LoggerConfiguration("ROOT", LogLevel.INFO, LogLevel.INFO), + new LoggerConfiguration("com.example", LogLevel.DEBUG, LogLevel.DEBUG))); + this.mockMvc.perform(get("/actuator/loggers")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("loggers/all", + responseFields(fieldWithPath("levels").description("Levels support by the logging system."), + fieldWithPath("loggers").description("Loggers keyed by name."), + fieldWithPath("groups").description("Logger groups keyed by name")) + .andWithPrefix("loggers.*.", levelFields) + .andWithPrefix("groups.*.", groupLevelFields))); } @Test void logger() throws Exception { given(this.loggingSystem.getLoggerConfiguration("com.example")) - .willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); - this.mockMvc.perform(get("/actuator/loggers/com.example")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("loggers/single", responseFields(levelFields))); + .willReturn(new LoggerConfiguration("com.example", LogLevel.INFO, LogLevel.INFO)); + this.mockMvc.perform(get("/actuator/loggers/com.example")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("loggers/single", responseFields(levelFields))); } @Test void loggerGroups() throws Exception { this.loggerGroups.get("test").configureLogLevel(LogLevel.INFO, (member, level) -> { }); - this.mockMvc.perform(get("/actuator/loggers/test")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("loggers/group", responseFields(groupLevelFields))); + this.mockMvc.perform(get("/actuator/loggers/test")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("loggers/group", responseFields(groupLevelFields))); resetLogger(); } @Test void setLogLevel() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()) - .andDo(MockMvcRestDocumentation.document("loggers/set", requestFields(fieldWithPath("configuredLevel") - .description("Level for the logger. May be omitted to clear the level.").optional()))); + .perform(post("/actuator/loggers/com.example").content("{\"configuredLevel\":\"debug\"}") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("loggers/set", + requestFields(fieldWithPath("configuredLevel") + .description("Level for the logger. May be omitted to clear the level.") + .optional()))); then(this.loggingSystem).should().setLogLevel("com.example", LogLevel.DEBUG); } @Test void setLogLevelOfLoggerGroup() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/test") - .content("{\"configuredLevel\":\"debug\"}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()).andDo( - MockMvcRestDocumentation.document("loggers/setGroup", - requestFields(fieldWithPath("configuredLevel").description( - "Level for the logger group. May be omitted to clear the level of the loggers.") - .optional()))); + .perform(post("/actuator/loggers/test").content("{\"configuredLevel\":\"debug\"}") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("loggers/setGroup", + requestFields(fieldWithPath("configuredLevel") + .description("Level for the logger group. May be omitted to clear the level of the loggers.") + .optional()))); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG); resetLogger(); @@ -140,8 +145,9 @@ class LoggersEndpointDocumentationTests extends MockMvcEndpointDocumentationTest @Test void clearLogLevel() throws Exception { this.mockMvc - .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()).andDo(MockMvcRestDocumentation.document("loggers/clear")); + .perform(post("/actuator/loggers/com.example").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(MockMvcRestDocumentation.document("loggers/clear")); then(this.loggingSystem).should().setLogLevel("com.example", null); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java index 6ecd2863f7..79c673e812 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointReactiveDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,8 +73,10 @@ class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumen @BeforeEach void webTestClient(RestDocumentationContextProvider restDocumentation) { this.client = WebTestClient.bindToServer() - .filter(documentationConfiguration(restDocumentation).snippets().withDefaults()) - .baseUrl("http://localhost:" + this.port).responseTimeout(Duration.ofMinutes(5)).build(); + .filter(documentationConfiguration(restDocumentation).snippets().withDefaults()) + .baseUrl("http://localhost:" + this.port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Test @@ -92,41 +94,49 @@ class MappingsEndpointReactiveDocumentationTests extends AbstractEndpointDocumen requestMappingConditionField(".params").description("Details of the params condition."), requestMappingConditionField(".params.[].name").description("Name of the parameter."), requestMappingConditionField(".params.[].value") - .description("Required value of the parameter, if any."), + .description("Required value of the parameter, if any."), requestMappingConditionField(".params.[].negated").description("Whether the value is negated."), requestMappingConditionField(".patterns") - .description("Patterns identifying the paths handled by the mapping."), + .description("Patterns identifying the paths handled by the mapping."), requestMappingConditionField(".produces").description("Details of the produces condition."), requestMappingConditionField(".produces.[].mediaType").description("Produced media type."), requestMappingConditionField(".produces.[].negated").description("Whether the media type is negated.")); List handlerMethod = Arrays.asList( - fieldWithPath("*.[].details.handlerMethod").optional().type(JsonFieldType.OBJECT) - .description("Details of the method, if any, that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerMethod").optional() + .type(JsonFieldType.OBJECT) + .description("Details of the method, if any, that will handle requests to this mapping."), fieldWithPath("*.[].details.handlerMethod.className").type(JsonFieldType.STRING) - .description("Fully qualified name of the class of the method."), + .description("Fully qualified name of the class of the method."), fieldWithPath("*.[].details.handlerMethod.name").type(JsonFieldType.STRING) - .description("Name of the method."), + .description("Name of the method."), fieldWithPath("*.[].details.handlerMethod.descriptor").type(JsonFieldType.STRING) - .description("Descriptor of the method as specified in the Java Language Specification.")); + .description("Descriptor of the method as specified in the Java Language Specification.")); List handlerFunction = Arrays.asList( - fieldWithPath("*.[].details.handlerFunction").optional().type(JsonFieldType.OBJECT) - .description("Details of the function, if any, that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerFunction").optional() + .type(JsonFieldType.OBJECT) + .description("Details of the function, if any, that will handle requests to this mapping."), fieldWithPath("*.[].details.handlerFunction.className").type(JsonFieldType.STRING) - .description("Fully qualified name of the class of the function.")); + .description("Fully qualified name of the class of the function.")); List dispatcherHandlerFields = new ArrayList<>(Arrays.asList( fieldWithPath("*") - .description("Dispatcher handler mappings, if any, keyed by dispatcher handler bean name."), - fieldWithPath("*.[].details").optional().type(JsonFieldType.OBJECT) - .description("Additional implementation-specific details about the mapping. Optional."), + .description("Dispatcher handler mappings, if any, keyed by dispatcher handler bean name."), + fieldWithPath("*.[].details").optional() + .type(JsonFieldType.OBJECT) + .description("Additional implementation-specific details about the mapping. Optional."), fieldWithPath("*.[].handler").description("Handler for the mapping."), fieldWithPath("*.[].predicate").description("Predicate for the mapping."))); dispatcherHandlerFields.addAll(requestMappingConditions); dispatcherHandlerFields.addAll(handlerMethod); dispatcherHandlerFields.addAll(handlerFunction); - this.client.get().uri("/actuator/mappings").exchange().expectStatus().isOk().expectBody() - .consumeWith(document("mappings", responseFields( - beneathPath("contexts.*.mappings.dispatcherHandlers").withSubsectionId("dispatcher-handlers"), - dispatcherHandlerFields))); + this.client.get() + .uri("/actuator/mappings") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(document("mappings", responseFields( + beneathPath("contexts.*.mappings.dispatcherHandlers").withSubsectionId("dispatcher-handlers"), + dispatcherHandlerFields))); } private FieldDescriptor requestMappingConditionField(String path) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java index b45f0ea735..b6399c7c3d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MappingsEndpointServletDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -72,8 +72,11 @@ class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocument @BeforeEach void webTestClient(RestDocumentationContextProvider restDocumentation) { - this.client = WebTestClient.bindToServer().filter(documentationConfiguration(restDocumentation)) - .baseUrl("http://localhost:" + this.port).responseTimeout(Duration.ofMinutes(5)).build(); + this.client = WebTestClient.bindToServer() + .filter(documentationConfiguration(restDocumentation)) + .baseUrl("http://localhost:" + this.port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Test @@ -82,18 +85,21 @@ class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocument fieldWithPath("contexts").description("Application contexts keyed by id."), fieldWithPath("contexts.*.mappings").description("Mappings in the context, keyed by mapping type."), subsectionWithPath("contexts.*.mappings.dispatcherServlets") - .description("Dispatcher servlet mappings, if any."), + .description("Dispatcher servlet mappings, if any."), subsectionWithPath("contexts.*.mappings.servletFilters") - .description("Servlet filter mappings, if any."), + .description("Servlet filter mappings, if any."), subsectionWithPath("contexts.*.mappings.servlets").description("Servlet mappings, if any."), subsectionWithPath("contexts.*.mappings.dispatcherHandlers") - .description("Dispatcher handler mappings, if any.").optional().type(JsonFieldType.OBJECT), + .description("Dispatcher handler mappings, if any.") + .optional() + .type(JsonFieldType.OBJECT), parentIdField()); List dispatcherServletFields = new ArrayList<>(Arrays.asList( fieldWithPath("*") - .description("Dispatcher servlet mappings, if any, keyed by dispatcher servlet bean name."), - fieldWithPath("*.[].details").optional().type(JsonFieldType.OBJECT) - .description("Additional implementation-specific details about the mapping. Optional."), + .description("Dispatcher servlet mappings, if any, keyed by dispatcher servlet bean name."), + fieldWithPath("*.[].details").optional() + .type(JsonFieldType.OBJECT) + .description("Additional implementation-specific details about the mapping. Optional."), fieldWithPath("*.[].handler").description("Handler for the mapping."), fieldWithPath("*.[].predicate").description("Predicate for the mapping."))); List requestMappingConditions = Arrays.asList( @@ -109,39 +115,43 @@ class MappingsEndpointServletDocumentationTests extends AbstractEndpointDocument requestMappingConditionField(".params").description("Details of the params condition."), requestMappingConditionField(".params.[].name").description("Name of the parameter."), requestMappingConditionField(".params.[].value") - .description("Required value of the parameter, if any."), + .description("Required value of the parameter, if any."), requestMappingConditionField(".params.[].negated").description("Whether the value is negated."), requestMappingConditionField(".patterns") - .description("Patterns identifying the paths handled by the mapping."), + .description("Patterns identifying the paths handled by the mapping."), requestMappingConditionField(".produces").description("Details of the produces condition."), requestMappingConditionField(".produces.[].mediaType").description("Produced media type."), requestMappingConditionField(".produces.[].negated").description("Whether the media type is negated.")); List handlerMethod = Arrays.asList( - fieldWithPath("*.[].details.handlerMethod").optional().type(JsonFieldType.OBJECT) - .description("Details of the method, if any, that will handle requests to this mapping."), + fieldWithPath("*.[].details.handlerMethod").optional() + .type(JsonFieldType.OBJECT) + .description("Details of the method, if any, that will handle requests to this mapping."), fieldWithPath("*.[].details.handlerMethod.className") - .description("Fully qualified name of the class of the method."), + .description("Fully qualified name of the class of the method."), fieldWithPath("*.[].details.handlerMethod.name").description("Name of the method."), fieldWithPath("*.[].details.handlerMethod.descriptor") - .description("Descriptor of the method as specified in the Java Language Specification.")); + .description("Descriptor of the method as specified in the Java Language Specification.")); dispatcherServletFields.addAll(handlerMethod); dispatcherServletFields.addAll(requestMappingConditions); - this.client.get().uri("/actuator/mappings").exchange().expectBody() - .consumeWith(document("mappings", commonResponseFields, - responseFields(beneathPath("contexts.*.mappings.dispatcherServlets") - .withSubsectionId("dispatcher-servlets"), dispatcherServletFields), - responseFields( - beneathPath("contexts.*.mappings.servletFilters").withSubsectionId("servlet-filters"), - fieldWithPath("[].servletNameMappings") - .description("Names of the servlets to which the filter is mapped."), - fieldWithPath("[].urlPatternMappings") - .description("URL pattern to which the filter is mapped."), - fieldWithPath("[].name").description("Name of the filter."), - fieldWithPath("[].className").description("Class name of the filter")), - responseFields(beneathPath("contexts.*.mappings.servlets").withSubsectionId("servlets"), - fieldWithPath("[].mappings").description("Mappings of the servlet."), - fieldWithPath("[].name").description("Name of the servlet."), - fieldWithPath("[].className").description("Class name of the servlet")))); + this.client.get() + .uri("/actuator/mappings") + .exchange() + .expectBody() + .consumeWith(document("mappings", commonResponseFields, + responseFields(beneathPath("contexts.*.mappings.dispatcherServlets") + .withSubsectionId("dispatcher-servlets"), dispatcherServletFields), + responseFields( + beneathPath("contexts.*.mappings.servletFilters").withSubsectionId("servlet-filters"), + fieldWithPath("[].servletNameMappings") + .description("Names of the servlets to which the filter is mapped."), + fieldWithPath("[].urlPatternMappings") + .description("URL pattern to which the filter is mapped."), + fieldWithPath("[].name").description("Name of the filter."), + fieldWithPath("[].className").description("Class name of the filter")), + responseFields(beneathPath("contexts.*.mappings.servlets").withSubsectionId("servlets"), + fieldWithPath("[].mappings").description("Mappings of the servlet."), + fieldWithPath("[].name").description("Name of the servlet."), + fieldWithPath("[].className").description("Class name of the servlet")))); } private FieldDescriptor requestMappingConditionField(String path) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java index d0da4d4d23..3faa23d9ab 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MetricsEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,34 +43,37 @@ class MetricsEndpointDocumentationTests extends MockMvcEndpointDocumentationTest @Test void metricNames() throws Exception { - this.mockMvc.perform(get("/actuator/metrics")).andExpect(status().isOk()).andDo(document("metrics/names", - responseFields(fieldWithPath("names").description("Names of the known metrics.")))); + this.mockMvc.perform(get("/actuator/metrics")) + .andExpect(status().isOk()) + .andDo(document("metrics/names", + responseFields(fieldWithPath("names").description("Names of the known metrics.")))); } @Test void metric() throws Exception { - this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")).andExpect(status().isOk()) - .andDo(document("metrics/metric", - responseFields(fieldWithPath("name").description("Name of the metric"), - fieldWithPath("description").description("Description of the metric"), - fieldWithPath("baseUnit").description("Base unit of the metric"), - fieldWithPath("measurements").description("Measurements of the metric"), - fieldWithPath("measurements[].statistic").description( - "Statistic of the measurement. (" + describeEnumValues(Statistic.class) + ")."), - fieldWithPath("measurements[].value").description("Value of the measurement."), - fieldWithPath("availableTags").description("Tags that are available for drill-down."), - fieldWithPath("availableTags[].tag").description("Name of the tag."), - fieldWithPath("availableTags[].values").description("Possible values of the tag.")))); + this.mockMvc.perform(get("/actuator/metrics/jvm.memory.max")) + .andExpect(status().isOk()) + .andDo(document("metrics/metric", + responseFields(fieldWithPath("name").description("Name of the metric"), + fieldWithPath("description").description("Description of the metric"), + fieldWithPath("baseUnit").description("Base unit of the metric"), + fieldWithPath("measurements").description("Measurements of the metric"), + fieldWithPath("measurements[].statistic").description( + "Statistic of the measurement. (" + describeEnumValues(Statistic.class) + ")."), + fieldWithPath("measurements[].value").description("Value of the measurement."), + fieldWithPath("availableTags").description("Tags that are available for drill-down."), + fieldWithPath("availableTags[].tag").description("Name of the tag."), + fieldWithPath("availableTags[].values").description("Possible values of the tag.")))); } @Test void metricWithTags() throws Exception { this.mockMvc - .perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap").param("tag", - "id:Compressed Class Space")) - .andExpect(status().isOk()) - .andDo(document("metrics/metric-with-tags", queryParameters(parameterWithName("tag") - .description("A tag to use for drill-down in the form `name:value`.")))); + .perform(get("/actuator/metrics/jvm.memory.max").param("tag", "area:nonheap") + .param("tag", "id:Compressed Class Space")) + .andExpect(status().isOk()) + .andDo(document("metrics/metric-with-tags", queryParameters( + parameterWithName("tag").description("A tag to use for drill-down in the form `name:value`.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java index 3c2399f5fd..fbfabbc3f4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/MockMvcEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,8 @@ public abstract class MockMvcEndpointDocumentationTests extends AbstractEndpoint @BeforeEach void setup(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.applicationContext) - .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()).build(); + .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation).uris()) + .build(); } protected WebApplicationContext getApplicationContext() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java index 3fa70f93db..5976155a27 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/PrometheusScrapeEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,19 +51,21 @@ class PrometheusScrapeEndpointDocumentationTests extends MockMvcEndpointDocument @Test void prometheusOpenmetrics() throws Exception { this.mockMvc.perform(get("/actuator/prometheus").accept(TextFormat.CONTENT_TYPE_OPENMETRICS_100)) - .andExpect(status().isOk()) - .andExpect(header().string("Content-Type", "application/openmetrics-text;version=1.0.0;charset=utf-8")) - .andDo(document("prometheus/openmetrics")); + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", "application/openmetrics-text;version=1.0.0;charset=utf-8")) + .andDo(document("prometheus/openmetrics")); } @Test void filteredPrometheus() throws Exception { this.mockMvc - .perform(get("/actuator/prometheus").param("includedNames", - "jvm_memory_used_bytes,jvm_memory_committed_bytes")) - .andExpect(status().isOk()) - .andDo(document("prometheus/names", queryParameters(parameterWithName("includedNames") - .description("Restricts the samples to those that match the names. Optional.").optional()))); + .perform(get("/actuator/prometheus").param("includedNames", + "jvm_memory_used_bytes,jvm_memory_committed_bytes")) + .andExpect(status().isOk()) + .andDo(document("prometheus/names", + queryParameters(parameterWithName("includedNames") + .description("Restricts the samples to those that match the names. Optional.") + .optional()))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java index bdf77aff6d..63093af47b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/QuartzEndpointDocumentationTests.java @@ -84,63 +84,78 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests private static final TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - private static final JobDetail jobOne = JobBuilder.newJob(DelegatingJob.class).withIdentity("jobOne", "samples") - .withDescription("A sample job").usingJobData("user", "admin").usingJobData("password", "secret").build(); + private static final JobDetail jobOne = JobBuilder.newJob(DelegatingJob.class) + .withIdentity("jobOne", "samples") + .withDescription("A sample job") + .usingJobData("user", "admin") + .usingJobData("password", "secret") + .build(); private static final JobDetail jobTwo = JobBuilder.newJob(Job.class).withIdentity("jobTwo", "samples").build(); private static final JobDetail jobThree = JobBuilder.newJob(Job.class).withIdentity("jobThree", "tests").build(); - private static final CronTrigger cronTrigger = TriggerBuilder.newTrigger().forJob(jobOne).withPriority(3) - .withDescription("3AM on weekdays").withIdentity("3am-weekdays", "samples") - .withSchedule( - CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5).inTimeZone(timeZone)) - .build(); - - private static final SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().forJob(jobOne).withPriority(7) - .withDescription("Once a day").withIdentity("every-day", "samples") - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)).build(); - - private static final CalendarIntervalTrigger calendarIntervalTrigger = TriggerBuilder.newTrigger().forJob(jobTwo) - .withDescription("Once a week").withIdentity("once-a-week", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1) - .inTimeZone(timeZone)) - .build(); + private static final CronTrigger cronTrigger = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withPriority(3) + .withDescription("3AM on weekdays") + .withIdentity("3am-weekdays", "samples") + .withSchedule(CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5).inTimeZone(timeZone)) + .build(); + + private static final SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withPriority(7) + .withDescription("Once a day") + .withIdentity("every-day", "samples") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)) + .build(); + + private static final CalendarIntervalTrigger calendarIntervalTrigger = TriggerBuilder.newTrigger() + .forJob(jobTwo) + .withDescription("Once a week") + .withIdentity("once-a-week", "samples") + .withSchedule( + CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1).inTimeZone(timeZone)) + .build(); private static final DailyTimeIntervalTrigger dailyTimeIntervalTrigger = TriggerBuilder.newTrigger() - .forJob(jobThree).withDescription("Every hour between 9AM and 6PM on Tuesday and Thursday") - .withIdentity("every-hour-tue-thu") - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + .forJob(jobThree) + .withDescription("Every hour between 9AM and 6PM on Tuesday and Thursday") + .withIdentity("every-hour-tue-thu") + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); private static final List triggerSummary = Arrays.asList(previousFireTime(""), nextFireTime(""), priority("")); private static final List cronTriggerSummary = Arrays.asList( fieldWithPath("expression").description("Cron expression to use."), - fieldWithPath("timeZone").type(JsonFieldType.STRING).optional() - .description("Time zone for which the expression will be resolved, if any.")); + fieldWithPath("timeZone").type(JsonFieldType.STRING) + .optional() + .description("Time zone for which the expression will be resolved, if any.")); private static final List simpleTriggerSummary = Collections - .singletonList(fieldWithPath("interval").description("Interval, in milliseconds, between two executions.")); + .singletonList(fieldWithPath("interval").description("Interval, in milliseconds, between two executions.")); - private static final List dailyTimeIntervalTriggerSummary = Arrays.asList( - fieldWithPath("interval").description( - "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), - fieldWithPath("daysOfWeek").type(JsonFieldType.ARRAY) + private static final List dailyTimeIntervalTriggerSummary = Arrays + .asList(fieldWithPath("interval").description( + "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), + fieldWithPath("daysOfWeek").type(JsonFieldType.ARRAY) .description("An array of days of the week upon which to fire."), - fieldWithPath("startTimeOfDay").type(JsonFieldType.STRING) + fieldWithPath("startTimeOfDay").type(JsonFieldType.STRING) .description("Time of day to start firing at the given interval, if any."), - fieldWithPath("endTimeOfDay").type(JsonFieldType.STRING) + fieldWithPath("endTimeOfDay").type(JsonFieldType.STRING) .description("Time of day to complete firing at the given interval, if any.")); - private static final List calendarIntervalTriggerSummary = Arrays.asList( - fieldWithPath("interval").description( - "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), - fieldWithPath("timeZone").type(JsonFieldType.STRING) + private static final List calendarIntervalTriggerSummary = Arrays + .asList(fieldWithPath("interval").description( + "Interval, in milliseconds, added to the fire time in order to calculate the time of the next trigger repeat."), + fieldWithPath("timeZone").type(JsonFieldType.STRING) .description("Time zone within which time calculations will be performed, if any.")); private static final List customTriggerSummary = Collections.singletonList( @@ -151,16 +166,18 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests fieldWithPath("name").description("Name of the trigger."), fieldWithPath("description").description("Description of the trigger, if any."), fieldWithPath("state") - .description("State of the trigger (" + describeEnumValues(TriggerState.class) + ")."), + .description("State of the trigger (" + describeEnumValues(TriggerState.class) + ")."), fieldWithPath("type").description( "Type of the trigger (`calendarInterval`, `cron`, `custom`, `dailyTimeInterval`, `simple`). " + "Determines the key of the object containing type-specific details."), fieldWithPath("calendarName").description("Name of the Calendar associated with this Trigger, if any."), startTime(""), endTime(""), previousFireTime(""), nextFireTime(""), priority(""), - fieldWithPath("finalFireTime").optional().type(JsonFieldType.STRING) - .description("Last time at which the Trigger will fire, if any."), - fieldWithPath("data").optional().type(JsonFieldType.OBJECT) - .description("Job data map keyed by name, if any.") }; + fieldWithPath("finalFireTime").optional() + .type(JsonFieldType.STRING) + .description("Last time at which the Trigger will fire, if any."), + fieldWithPath("data").optional() + .type(JsonFieldType.OBJECT) + .description("Job data map keyed by name, if any.") }; @MockBean private Scheduler scheduler; @@ -169,54 +186,63 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests void quartzReport() throws Exception { mockJobs(jobOne, jobTwo, jobThree); mockTriggers(cronTrigger, simpleTrigger, calendarIntervalTrigger, dailyTimeIntervalTrigger); - this.mockMvc.perform(get("/actuator/quartz")).andExpect(status().isOk()) - .andDo(document("quartz/report", - responseFields(fieldWithPath("jobs.groups").description("An array of job group names."), - fieldWithPath("triggers.groups").description("An array of trigger group names.")))); + this.mockMvc.perform(get("/actuator/quartz")) + .andExpect(status().isOk()) + .andDo(document("quartz/report", + responseFields(fieldWithPath("jobs.groups").description("An array of job group names."), + fieldWithPath("triggers.groups").description("An array of trigger group names.")))); } @Test void quartzJobs() throws Exception { mockJobs(jobOne, jobTwo, jobThree); - this.mockMvc.perform(get("/actuator/quartz/jobs")).andExpect(status().isOk()).andDo( - document("quartz/jobs", responseFields(fieldWithPath("groups").description("Job groups keyed by name."), - fieldWithPath("groups.*.jobs").description("An array of job names.")))); + this.mockMvc.perform(get("/actuator/quartz/jobs")) + .andExpect(status().isOk()) + .andDo(document("quartz/jobs", + responseFields(fieldWithPath("groups").description("Job groups keyed by name."), + fieldWithPath("groups.*.jobs").description("An array of job names.")))); } @Test void quartzTriggers() throws Exception { mockTriggers(cronTrigger, simpleTrigger, calendarIntervalTrigger, dailyTimeIntervalTrigger); - this.mockMvc.perform(get("/actuator/quartz/triggers")).andExpect(status().isOk()) - .andDo(document("quartz/triggers", - responseFields(fieldWithPath("groups").description("Trigger groups keyed by name."), - fieldWithPath("groups.*.paused").description("Whether this trigger group is paused."), - fieldWithPath("groups.*.triggers").description("An array of trigger names.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers")) + .andExpect(status().isOk()) + .andDo(document("quartz/triggers", + responseFields(fieldWithPath("groups").description("Trigger groups keyed by name."), + fieldWithPath("groups.*.paused").description("Whether this trigger group is paused."), + fieldWithPath("groups.*.triggers").description("An array of trigger names.")))); } @Test void quartzJobGroup() throws Exception { mockJobs(jobOne, jobTwo, jobThree); - this.mockMvc.perform(get("/actuator/quartz/jobs/samples")).andExpect(status().isOk()) - .andDo(document("quartz/job-group", - responseFields(fieldWithPath("group").description("Name of the group."), - fieldWithPath("jobs").description("Job details keyed by name."), - fieldWithPath("jobs.*.className") - .description("Fully qualified name of the job implementation.")))); + this.mockMvc.perform(get("/actuator/quartz/jobs/samples")) + .andExpect(status().isOk()) + .andDo(document("quartz/job-group", responseFields(fieldWithPath("group").description("Name of the group."), + fieldWithPath("jobs").description("Job details keyed by name."), + fieldWithPath("jobs.*.className").description("Fully qualified name of the job implementation.")))); } @Test void quartzTriggerGroup() throws Exception { - CronTrigger cron = cronTrigger.getTriggerBuilder().startAt(fromUtc("2020-11-30T17:00:00Z")) - .endAt(fromUtc("2020-12-30T03:00:00Z")).withIdentity("3am-week", "tests").build(); + CronTrigger cron = cronTrigger.getTriggerBuilder() + .startAt(fromUtc("2020-11-30T17:00:00Z")) + .endAt(fromUtc("2020-12-30T03:00:00Z")) + .withIdentity("3am-week", "tests") + .build(); setPreviousNextFireTime(cron, "2020-12-04T03:00:00Z", "2020-12-07T03:00:00Z"); SimpleTrigger simple = simpleTrigger.getTriggerBuilder().withIdentity("every-day", "tests").build(); setPreviousNextFireTime(simple, null, "2020-12-04T12:00:00Z"); CalendarIntervalTrigger calendarInterval = calendarIntervalTrigger.getTriggerBuilder() - .withIdentity("once-a-week", "tests").startAt(fromUtc("2019-07-10T14:00:00Z")) - .endAt(fromUtc("2023-01-01T12:00:00Z")).build(); + .withIdentity("once-a-week", "tests") + .startAt(fromUtc("2019-07-10T14:00:00Z")) + .endAt(fromUtc("2023-01-01T12:00:00Z")) + .build(); setPreviousNextFireTime(calendarInterval, "2020-12-02T14:00:00Z", "2020-12-08T14:00:00Z"); DailyTimeIntervalTrigger tueThuTrigger = dailyTimeIntervalTrigger.getTriggerBuilder() - .withIdentity("tue-thu", "tests").build(); + .withIdentity("tue-thu", "tests") + .build(); Trigger customTrigger = mock(Trigger.class); given(customTrigger.getKey()).willReturn(TriggerKey.triggerKey("once-a-year-custom", "tests")); given(customTrigger.toString()).willReturn("com.example.CustomTrigger@fdsfsd"); @@ -224,24 +250,25 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(customTrigger.getPreviousFireTime()).willReturn(fromUtc("2020-07-14T16:00:00Z")); given(customTrigger.getNextFireTime()).willReturn(fromUtc("2021-07-14T16:00:00Z")); mockTriggers(cron, simple, calendarInterval, tueThuTrigger, customTrigger); - this.mockMvc.perform(get("/actuator/quartz/triggers/tests")).andExpect(status().isOk()).andDo(document( - "quartz/trigger-group", - responseFields(fieldWithPath("group").description("Name of the group."), - fieldWithPath("paused").description("Whether the group is paused."), - fieldWithPath("triggers.cron").description("Cron triggers keyed by name, if any."), - fieldWithPath("triggers.simple").description("Simple triggers keyed by name, if any."), - fieldWithPath("triggers.dailyTimeInterval") + this.mockMvc.perform(get("/actuator/quartz/triggers/tests")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-group", + responseFields(fieldWithPath("group").description("Name of the group."), + fieldWithPath("paused").description("Whether the group is paused."), + fieldWithPath("triggers.cron").description("Cron triggers keyed by name, if any."), + fieldWithPath("triggers.simple").description("Simple triggers keyed by name, if any."), + fieldWithPath("triggers.dailyTimeInterval") .description("Daily time interval triggers keyed by name, if any."), - fieldWithPath("triggers.calendarInterval") + fieldWithPath("triggers.calendarInterval") .description("Calendar interval triggers keyed by name, if any."), - fieldWithPath("triggers.custom").description("Any other triggers keyed by name, if any.")) - .andWithPrefix("triggers.cron.*.", concat(triggerSummary, cronTriggerSummary)) - .andWithPrefix("triggers.simple.*.", concat(triggerSummary, simpleTriggerSummary)) - .andWithPrefix("triggers.dailyTimeInterval.*.", - concat(triggerSummary, dailyTimeIntervalTriggerSummary)) - .andWithPrefix("triggers.calendarInterval.*.", - concat(triggerSummary, calendarIntervalTriggerSummary)) - .andWithPrefix("triggers.custom.*.", concat(triggerSummary, customTriggerSummary)))); + fieldWithPath("triggers.custom").description("Any other triggers keyed by name, if any.")) + .andWithPrefix("triggers.cron.*.", concat(triggerSummary, cronTriggerSummary)) + .andWithPrefix("triggers.simple.*.", concat(triggerSummary, simpleTriggerSummary)) + .andWithPrefix("triggers.dailyTimeInterval.*.", + concat(triggerSummary, dailyTimeIntervalTriggerSummary)) + .andWithPrefix("triggers.calendarInterval.*.", + concat(triggerSummary, calendarIntervalTriggerSummary)) + .andWithPrefix("triggers.custom.*.", concat(triggerSummary, customTriggerSummary)))); } @Test @@ -253,89 +280,101 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests setPreviousNextFireTime(secondTrigger, "2020-12-04T03:00:00Z", "2020-12-04T12:00:00Z"); mockTriggers(firstTrigger, secondTrigger); given(this.scheduler.getTriggersOfJob(jobOne.getKey())) - .willAnswer((invocation) -> Arrays.asList(firstTrigger, secondTrigger)); - this.mockMvc.perform(get("/actuator/quartz/jobs/samples/jobOne")).andExpect(status().isOk()).andDo(document( - "quartz/job-details", - responseFields(fieldWithPath("group").description("Name of the group."), - fieldWithPath("name").description("Name of the job."), - fieldWithPath("description").description("Description of the job, if any."), - fieldWithPath("className").description("Fully qualified name of the job implementation."), - fieldWithPath("durable") - .description("Whether the job should remain stored after it is orphaned."), - fieldWithPath("requestRecovery").description( - "Whether the job should be re-executed if a 'recovery' or 'fail-over' situation is encountered."), - fieldWithPath("data.*").description("Job data map as key/value pairs, if any."), - fieldWithPath("triggers").description("An array of triggers associated to the job, if any."), - fieldWithPath("triggers.[].group").description("Name of the trigger group."), - fieldWithPath("triggers.[].name").description("Name of the trigger."), - previousFireTime("triggers.[]."), nextFireTime("triggers.[]."), priority("triggers.[].")))); + .willAnswer((invocation) -> Arrays.asList(firstTrigger, secondTrigger)); + this.mockMvc.perform(get("/actuator/quartz/jobs/samples/jobOne")) + .andExpect(status().isOk()) + .andDo(document("quartz/job-details", responseFields( + fieldWithPath("group").description("Name of the group."), + fieldWithPath("name").description("Name of the job."), + fieldWithPath("description").description("Description of the job, if any."), + fieldWithPath("className").description("Fully qualified name of the job implementation."), + fieldWithPath("durable").description("Whether the job should remain stored after it is orphaned."), + fieldWithPath("requestRecovery").description( + "Whether the job should be re-executed if a 'recovery' or 'fail-over' situation is encountered."), + fieldWithPath("data.*").description("Job data map as key/value pairs, if any."), + fieldWithPath("triggers").description("An array of triggers associated to the job, if any."), + fieldWithPath("triggers.[].group").description("Name of the trigger group."), + fieldWithPath("triggers.[].name").description("Name of the trigger."), + previousFireTime("triggers.[]."), nextFireTime("triggers.[]."), priority("triggers.[].")))); } @Test void quartzTriggerCommon() throws Exception { setupTriggerDetails(cronTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-common", responseFields(commonCronDetails).and( - subsectionWithPath("calendarInterval").description( - "Calendar time interval trigger details, if any. Present when `type` is `calendarInterval`.") - .optional().type(JsonFieldType.OBJECT), - subsectionWithPath("custom") - .description("Custom trigger details, if any. Present when `type` is `custom`.") - .optional().type(JsonFieldType.OBJECT), - subsectionWithPath("cron") - .description("Cron trigger details, if any. Present when `type` is `cron`.").optional() - .type(JsonFieldType.OBJECT), - subsectionWithPath("dailyTimeInterval").description( - "Daily time interval trigger details, if any. Present when `type` is `dailyTimeInterval`.") - .optional().type(JsonFieldType.OBJECT), - subsectionWithPath("simple") - .description("Simple trigger details, if any. Present when `type` is `simple`.") - .optional().type(JsonFieldType.OBJECT)))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-common", responseFields(commonCronDetails).and(subsectionWithPath( + "calendarInterval") + .description( + "Calendar time interval trigger details, if any. Present when `type` is `calendarInterval`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("custom") + .description("Custom trigger details, if any. Present when `type` is `custom`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("cron") + .description("Cron trigger details, if any. Present when `type` is `cron`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("dailyTimeInterval").description( + "Daily time interval trigger details, if any. Present when `type` is `dailyTimeInterval`.") + .optional() + .type(JsonFieldType.OBJECT), + subsectionWithPath("simple") + .description("Simple trigger details, if any. Present when `type` is `simple`.") + .optional() + .type(JsonFieldType.OBJECT)))); } @Test void quartzTriggerCron() throws Exception { setupTriggerDetails(cronTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-cron", - relaxedResponseFields(fieldWithPath("cron").description("Cron trigger specific details.")) - .andWithPrefix("cron.", cronTriggerSummary))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-cron", + relaxedResponseFields(fieldWithPath("cron").description("Cron trigger specific details.")) + .andWithPrefix("cron.", cronTriggerSummary))); } @Test void quartzTriggerSimple() throws Exception { setupTriggerDetails(simpleTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-simple", - relaxedResponseFields(fieldWithPath("simple").description("Simple trigger specific details.")) - .andWithPrefix("simple.", simpleTriggerSummary) - .and(repeatCount("simple."), timesTriggered("simple.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-simple", + relaxedResponseFields(fieldWithPath("simple").description("Simple trigger specific details.")) + .andWithPrefix("simple.", simpleTriggerSummary) + .and(repeatCount("simple."), timesTriggered("simple.")))); } @Test void quartzTriggerCalendarInterval() throws Exception { setupTriggerDetails(calendarIntervalTrigger.getTriggerBuilder(), TriggerState.NORMAL); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-calendar-interval", relaxedResponseFields( - fieldWithPath("calendarInterval").description("Calendar interval trigger specific details.")) - .andWithPrefix("calendarInterval.", calendarIntervalTriggerSummary) - .and(timesTriggered("calendarInterval."), fieldWithPath( - "calendarInterval.preserveHourOfDayAcrossDaylightSavings").description( - "Whether to fire the trigger at the same time of day, regardless of daylight " - + "saving time transitions."), - fieldWithPath("calendarInterval.skipDayIfHourDoesNotExist").description( - "Whether to skip if the hour of the day does not exist on a given day.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-calendar-interval", + relaxedResponseFields(fieldWithPath("calendarInterval") + .description("Calendar interval trigger specific details.")) + .andWithPrefix("calendarInterval.", calendarIntervalTriggerSummary) + .and(timesTriggered("calendarInterval."), + fieldWithPath("calendarInterval.preserveHourOfDayAcrossDaylightSavings").description( + "Whether to fire the trigger at the same time of day, regardless of daylight " + + "saving time transitions."), + fieldWithPath("calendarInterval.skipDayIfHourDoesNotExist").description( + "Whether to skip if the hour of the day does not exist on a given day.")))); } @Test void quartzTriggerDailyTimeInterval() throws Exception { setupTriggerDetails(dailyTimeIntervalTrigger.getTriggerBuilder(), TriggerState.PAUSED); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-daily-time-interval", - relaxedResponseFields(fieldWithPath("dailyTimeInterval") - .description("Daily time interval trigger specific details.")) - .andWithPrefix("dailyTimeInterval.", dailyTimeIntervalTriggerSummary) - .and(repeatCount("dailyTimeInterval."), timesTriggered("dailyTimeInterval.")))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-daily-time-interval", + relaxedResponseFields(fieldWithPath("dailyTimeInterval") + .description("Daily time interval trigger specific details.")) + .andWithPrefix("dailyTimeInterval.", dailyTimeIntervalTriggerSummary) + .and(repeatCount("dailyTimeInterval."), timesTriggered("dailyTimeInterval.")))); } @Test @@ -352,17 +391,21 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(trigger.getNextFireTime()).willReturn(fromUtc("2020-12-07T03:00:00Z")); given(this.scheduler.getTriggerState(trigger.getKey())).willReturn(TriggerState.NORMAL); mockTriggers(trigger); - this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")).andExpect(status().isOk()) - .andDo(document("quartz/trigger-details-custom", - relaxedResponseFields(fieldWithPath("custom").description("Custom trigger specific details.")) - .andWithPrefix("custom.", customTriggerSummary))); + this.mockMvc.perform(get("/actuator/quartz/triggers/samples/example")) + .andExpect(status().isOk()) + .andDo(document("quartz/trigger-details-custom", + relaxedResponseFields(fieldWithPath("custom").description("Custom trigger specific details.")) + .andWithPrefix("custom.", customTriggerSummary))); } private T setupTriggerDetails(TriggerBuilder builder, TriggerState state) throws SchedulerException { - T trigger = builder.withIdentity("example", "samples").withDescription("Example trigger") - .startAt(fromUtc("2020-11-30T17:00:00Z")).modifiedByCalendar("bankHolidays") - .endAt(fromUtc("2020-12-30T03:00:00Z")).build(); + T trigger = builder.withIdentity("example", "samples") + .withDescription("Example trigger") + .startAt(fromUtc("2020-11-30T17:00:00Z")) + .modifiedByCalendar("bankHolidays") + .endAt(fromUtc("2020-12-30T03:00:00Z")) + .build(); setPreviousNextFireTime(trigger, "2020-12-04T03:00:00Z", "2020-12-07T03:00:00Z"); given(this.scheduler.getTriggerState(trigger.getKey())).willReturn(state); mockTriggers(trigger); @@ -379,23 +422,25 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests } private static FieldDescriptor previousFireTime(String prefix) { - return fieldWithPath(prefix + "previousFireTime").optional().type(JsonFieldType.STRING) - .description("Last time the trigger fired, if any."); + return fieldWithPath(prefix + "previousFireTime").optional() + .type(JsonFieldType.STRING) + .description("Last time the trigger fired, if any."); } private static FieldDescriptor nextFireTime(String prefix) { - return fieldWithPath(prefix + "nextFireTime").optional().type(JsonFieldType.STRING) - .description("Next time at which the Trigger is scheduled to fire, if any."); + return fieldWithPath(prefix + "nextFireTime").optional() + .type(JsonFieldType.STRING) + .description("Next time at which the Trigger is scheduled to fire, if any."); } private static FieldDescriptor priority(String prefix) { return fieldWithPath(prefix + "priority") - .description("Priority to use if two triggers have the same scheduled fire time."); + .description("Priority to use if two triggers have the same scheduled fire time."); } private static FieldDescriptor repeatCount(String prefix) { return fieldWithPath(prefix + "repeatCount") - .description("Number of times the trigger should repeat, or -1 to repeat indefinitely."); + .description("Number of times the trigger should repeat, or -1 to repeat indefinitely."); } private static FieldDescriptor timesTriggered(String prefix) { @@ -418,7 +463,7 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(this.scheduler.getJobGroupNames()).willReturn(new ArrayList<>(jobKeys.keySet())); for (Entry> entry : jobKeys.entrySet()) { given(this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } @@ -432,7 +477,7 @@ class QuartzEndpointDocumentationTests extends MockMvcEndpointDocumentationTests given(this.scheduler.getTriggerGroupNames()).willReturn(new ArrayList<>(triggerKeys.keySet())); for (Entry> entry : triggerKeys.entrySet()) { given(this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java index 953104e4cb..efcc258699 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ScheduledTasksEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,28 +52,29 @@ class ScheduledTasksEndpointDocumentationTests extends MockMvcEndpointDocumentat @Test void scheduledTasks() throws Exception { - this.mockMvc.perform(get("/actuator/scheduledtasks")).andExpect(status().isOk()) - .andDo(document("scheduled-tasks", - preprocessResponse(replacePattern( - Pattern.compile("org.*\\.ScheduledTasksEndpointDocumentationTests\\$TestConfiguration"), - "com.example.Processor")), - responseFields(fieldWithPath("cron").description("Cron tasks, if any."), - targetFieldWithPrefix("cron.[]."), - fieldWithPath("cron.[].expression").description("Cron expression."), - fieldWithPath("fixedDelay").description("Fixed delay tasks, if any."), - targetFieldWithPrefix("fixedDelay.[]."), initialDelayWithPrefix("fixedDelay.[]."), - fieldWithPath("fixedDelay.[].interval") - .description("Interval, in milliseconds, between the end of the last" - + " execution and the start of the next."), - fieldWithPath("fixedRate").description("Fixed rate tasks, if any."), - targetFieldWithPrefix("fixedRate.[]."), - fieldWithPath("fixedRate.[].interval") - .description("Interval, in milliseconds, between the start of each execution."), - initialDelayWithPrefix("fixedRate.[]."), - fieldWithPath("custom").description("Tasks with custom triggers, if any."), - targetFieldWithPrefix("custom.[]."), - fieldWithPath("custom.[].trigger").description("Trigger for the task.")))) - .andDo(MockMvcResultHandlers.print()); + this.mockMvc.perform(get("/actuator/scheduledtasks")) + .andExpect(status().isOk()) + .andDo(document("scheduled-tasks", + preprocessResponse(replacePattern( + Pattern.compile("org.*\\.ScheduledTasksEndpointDocumentationTests\\$TestConfiguration"), + "com.example.Processor")), + responseFields(fieldWithPath("cron").description("Cron tasks, if any."), + targetFieldWithPrefix("cron.[]."), + fieldWithPath("cron.[].expression").description("Cron expression."), + fieldWithPath("fixedDelay").description("Fixed delay tasks, if any."), + targetFieldWithPrefix("fixedDelay.[]."), initialDelayWithPrefix("fixedDelay.[]."), + fieldWithPath("fixedDelay.[].interval") + .description("Interval, in milliseconds, between the end of the last" + + " execution and the start of the next."), + fieldWithPath("fixedRate").description("Fixed rate tasks, if any."), + targetFieldWithPrefix("fixedRate.[]."), + fieldWithPath("fixedRate.[].interval") + .description("Interval, in milliseconds, between the start of each execution."), + initialDelayWithPrefix("fixedRate.[]."), + fieldWithPath("custom").description("Tasks with custom triggers, if any."), + targetFieldWithPrefix("custom.[]."), + fieldWithPath("custom.[].trigger").description("Trigger for the task.")))) + .andDo(MockMvcResultHandlers.print()); } private FieldDescriptor targetFieldWithPrefix(String prefix) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java index 895bf63ccf..0d43d8fa12 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/SessionsEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTes fieldWithPath("creationTime").description("Timestamp of when the session was created."), fieldWithPath("lastAccessedTime").description("Timestamp of when the session was last accessed."), fieldWithPath("maxInactiveInterval") - .description("Maximum permitted period of inactivity, in seconds, before the session will expire."), + .description("Maximum permitted period of inactivity, in seconds, before the session will expire."), fieldWithPath("expired").description("Whether the session has expired.")); @MockBean @@ -84,24 +84,27 @@ class SessionsEndpointDocumentationTests extends MockMvcEndpointDocumentationTes sessions.put(sessionTwo.getId(), sessionTwo); sessions.put(sessionThree.getId(), sessionThree); given(this.sessionRepository.findByPrincipalName("alice")).willReturn(sessions); - this.mockMvc.perform(get("/actuator/sessions").param("username", "alice")).andExpect(status().isOk()) - .andDo(document("sessions/username", - responseFields(fieldWithPath("sessions").description("Sessions for the given username.")) - .andWithPrefix("sessions.[].", sessionFields), - queryParameters(parameterWithName("username").description("Name of the user.")))); + this.mockMvc.perform(get("/actuator/sessions").param("username", "alice")) + .andExpect(status().isOk()) + .andDo(document("sessions/username", + responseFields(fieldWithPath("sessions").description("Sessions for the given username.")) + .andWithPrefix("sessions.[].", sessionFields), + queryParameters(parameterWithName("username").description("Name of the user.")))); } @Test void sessionWithId() throws Exception { given(this.sessionRepository.findById(sessionTwo.getId())).willReturn(sessionTwo); - this.mockMvc.perform(get("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isOk()) - .andDo(document("sessions/id", responseFields(sessionFields))); + this.mockMvc.perform(get("/actuator/sessions/{id}", sessionTwo.getId())) + .andExpect(status().isOk()) + .andDo(document("sessions/id", responseFields(sessionFields))); } @Test void deleteASession() throws Exception { - this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())).andExpect(status().isNoContent()) - .andDo(document("sessions/delete")); + this.mockMvc.perform(delete("/actuator/sessions/{id}", sessionTwo.getId())) + .andExpect(status().isNoContent()) + .andDo(document("sessions/delete")); then(this.sessionRepository).should().deleteById(sessionTwo.getId()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java index 957462f239..033312870b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ShutdownEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -40,9 +40,10 @@ class ShutdownEndpointDocumentationTests extends MockMvcEndpointDocumentationTes @Test void shutdown() throws Exception { - this.mockMvc.perform(post("/actuator/shutdown")).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("shutdown", responseFields( - fieldWithPath("message").description("Message describing the result of the request.")))); + this.mockMvc.perform(post("/actuator/shutdown")) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("shutdown", responseFields( + fieldWithPath("message").description("Message describing the result of the request.")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java index e2651b884f..85e5a6e7a0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/StartupEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -56,36 +56,40 @@ class StartupEndpointDocumentationTests extends MockMvcEndpointDocumentationTest @Test void startupSnapshot() throws Exception { - this.mockMvc.perform(get("/actuator/startup")).andExpect(status().isOk()) - .andDo(document("startup-snapshot", PayloadDocumentation.responseFields(responseFields()))); + this.mockMvc.perform(get("/actuator/startup")) + .andExpect(status().isOk()) + .andDo(document("startup-snapshot", PayloadDocumentation.responseFields(responseFields()))); } @Test void startup() throws Exception { - this.mockMvc.perform(post("/actuator/startup")).andExpect(status().isOk()) - .andDo(document("startup", PayloadDocumentation.responseFields(responseFields()))); + this.mockMvc.perform(post("/actuator/startup")) + .andExpect(status().isOk()) + .andDo(document("startup", PayloadDocumentation.responseFields(responseFields()))); } private FieldDescriptor[] responseFields() { return new FieldDescriptor[] { fieldWithPath("springBootVersion").type(JsonFieldType.STRING) - .description("Spring Boot version for this application.").optional(), + .description("Spring Boot version for this application.") + .optional(), fieldWithPath("timeline.startTime").description("Start time of the application."), fieldWithPath("timeline.events") - .description("An array of steps collected during application startup so far."), + .description("An array of steps collected during application startup so far."), fieldWithPath("timeline.events.[].startTime").description("The timestamp of the start of this event."), fieldWithPath("timeline.events.[].endTime").description("The timestamp of the end of this event."), fieldWithPath("timeline.events.[].duration").description("The precise duration of this event."), fieldWithPath("timeline.events.[].startupStep.name").description("The name of the StartupStep."), fieldWithPath("timeline.events.[].startupStep.id").description("The id of this StartupStep."), fieldWithPath("timeline.events.[].startupStep.parentId") - .description("The parent id for this StartupStep.").optional(), + .description("The parent id for this StartupStep.") + .optional(), fieldWithPath("timeline.events.[].startupStep.tags") - .description("An array of key/value pairs with additional step info."), + .description("An array of key/value pairs with additional step info."), fieldWithPath("timeline.events.[].startupStep.tags[].key") - .description("The key of the StartupStep Tag."), + .description("The key of the StartupStep Tag."), fieldWithPath("timeline.events.[].startupStep.tags[].value") - .description("The value of the StartupStep Tag.") }; + .description("The value of the StartupStep Tag.") }; } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java index 53d85c503d..afed23b877 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/documentation/ThreadDumpEndpointDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,135 +63,132 @@ class ThreadDumpEndpointDocumentationTests extends MockMvcEndpointDocumentationT Thread.currentThread().interrupt(); } }).start(); - this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.APPLICATION_JSON)).andExpect( - status().isOk()).andDo( - MockMvcRestDocumentation - .document("threaddump/json", preprocessResponse(limit("threads")), - responseFields(fieldWithPath("threads").description("JVM's threads."), - fieldWithPath("threads.[].blockedCount").description( - "Total number of times that the thread has been blocked."), - fieldWithPath("threads.[].blockedTime").description( - "Time in milliseconds that the thread has spent " - + "blocked. -1 if thread contention " - + "monitoring is disabled."), - fieldWithPath("threads.[].daemon") - .description("Whether the thread is a daemon " - + "thread. Only available on Java 9 or later.") - .optional().type(JsonFieldType.BOOLEAN), - fieldWithPath("threads.[].inNative") - .description("Whether the thread is executing native code."), - fieldWithPath("threads.[].lockName") - .description("Description of the object on which the " - + "thread is blocked, if any.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockInfo") - .description("Object for which the thread is blocked waiting.") - .optional().type(JsonFieldType.OBJECT), - fieldWithPath("threads.[].lockInfo.className") - .description("Fully qualified class name of the lock object.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockInfo.identityHashCode") - .description("Identity hash code of the lock object.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].lockedMonitors") - .description("Monitors locked by this thread, if any"), - fieldWithPath("threads.[].lockedMonitors.[].className") - .description("Class name of the lock object.").optional() - .type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockedMonitors.[].identityHashCode") - .description("Identity hash code of the lock object.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].lockedMonitors.[].lockedStackDepth") - .description("Stack depth where the monitor was locked.") - .optional().type(JsonFieldType.NUMBER), - subsectionWithPath("threads.[].lockedMonitors.[].lockedStackFrame") - .description("Stack frame that locked the monitor.").optional() - .type(JsonFieldType.OBJECT), - fieldWithPath("threads.[].lockedSynchronizers") - .description("Synchronizers locked by this thread."), - fieldWithPath("threads.[].lockedSynchronizers.[].className") - .description("Class name of the locked synchronizer.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].lockedSynchronizers.[].identityHashCode") - .description("Identity hash code of the locked synchronizer.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].lockOwnerId") - .description("ID of the thread that owns the object on which " - + "the thread is blocked. `-1` if the " - + "thread is not blocked."), - fieldWithPath("threads.[].lockOwnerName") - .description("Name of the thread that owns the " - + "object on which the thread is blocked, if any.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].priority") - .description("Priority of the thread. Only " - + "available on Java 9 or later.") - .optional().type(JsonFieldType.NUMBER), - fieldWithPath("threads.[].stackTrace") - .description("Stack trace of the thread."), - fieldWithPath("threads.[].stackTrace.[].classLoaderName") - .description("Name of the class loader of the " - + "class that contains the execution " - + "point identified by this entry, if " - + "any. Only available on Java 9 or later.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].className") - .description("Name of the class that contains the " - + "execution point identified by this entry."), - fieldWithPath("threads.[].stackTrace.[].fileName") - .description("Name of the source file that " - + "contains the execution point " - + "identified by this entry, if any.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].lineNumber") - .description("Line number of the execution " - + "point identified by this entry. " - + "Negative if unknown."), - fieldWithPath("threads.[].stackTrace.[].methodName") - .description("Name of the method."), - fieldWithPath("threads.[].stackTrace.[].moduleName") - .description("Name of the module that contains " - + "the execution point identified by " - + "this entry, if any. Only available " - + "on Java 9 or later.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].moduleVersion") - .description("Version of the module that " - + "contains the execution point " - + "identified by this entry, if any. " - + "Only available on Java 9 or later.") - .optional().type(JsonFieldType.STRING), - fieldWithPath("threads.[].stackTrace.[].nativeMethod") - .description("Whether the execution point is a native method."), - fieldWithPath("threads.[].suspended") - .description("Whether the thread is suspended."), - fieldWithPath("threads.[].threadId").description("ID of the thread."), - fieldWithPath("threads.[].threadName") - .description("Name of the thread."), - fieldWithPath("threads.[].threadState") - .description("State of the thread (" - + describeEnumValues(Thread.State.class) + ")."), - fieldWithPath("threads.[].waitedCount") - .description("Total number of times that the thread has waited" - + " for notification."), - fieldWithPath("threads.[].waitedTime") - .description("Time in milliseconds that the thread has spent " - + "waiting. -1 if thread contention " - + "monitoring is disabled")))); + this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation + .document("threaddump/json", preprocessResponse(limit("threads")), responseFields( + fieldWithPath("threads").description("JVM's threads."), + fieldWithPath("threads.[].blockedCount") + .description("Total number of times that the thread has been blocked."), + fieldWithPath("threads.[].blockedTime") + .description("Time in milliseconds that the thread has spent " + + "blocked. -1 if thread contention " + "monitoring is disabled."), + fieldWithPath("threads.[].daemon") + .description( + "Whether the thread is a daemon " + "thread. Only available on Java 9 or later.") + .optional() + .type(JsonFieldType.BOOLEAN), + fieldWithPath("threads.[].inNative") + .description("Whether the thread is executing native code."), + fieldWithPath("threads.[].lockName") + .description("Description of the object on which the " + "thread is blocked, if any.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockInfo") + .description("Object for which the thread is blocked waiting.") + .optional() + .type(JsonFieldType.OBJECT), + fieldWithPath("threads.[].lockInfo.className") + .description("Fully qualified class name of the lock object.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockInfo.identityHashCode") + .description("Identity hash code of the lock object.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockedMonitors") + .description("Monitors locked by this thread, if any"), + fieldWithPath("threads.[].lockedMonitors.[].className") + .description("Class name of the lock object.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockedMonitors.[].identityHashCode") + .description("Identity hash code of the lock object.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockedMonitors.[].lockedStackDepth") + .description("Stack depth where the monitor was locked.") + .optional() + .type(JsonFieldType.NUMBER), + subsectionWithPath("threads.[].lockedMonitors.[].lockedStackFrame") + .description("Stack frame that locked the monitor.") + .optional() + .type(JsonFieldType.OBJECT), + fieldWithPath("threads.[].lockedSynchronizers") + .description("Synchronizers locked by this thread."), + fieldWithPath("threads.[].lockedSynchronizers.[].className") + .description("Class name of the locked synchronizer.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].lockedSynchronizers.[].identityHashCode") + .description("Identity hash code of the locked synchronizer.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].lockOwnerId") + .description("ID of the thread that owns the object on which " + + "the thread is blocked. `-1` if the " + "thread is not blocked."), + fieldWithPath("threads.[].lockOwnerName") + .description("Name of the thread that owns the " + + "object on which the thread is blocked, if any.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].priority") + .description("Priority of the thread. Only " + "available on Java 9 or later.") + .optional() + .type(JsonFieldType.NUMBER), + fieldWithPath("threads.[].stackTrace").description("Stack trace of the thread."), + fieldWithPath("threads.[].stackTrace.[].classLoaderName") + .description("Name of the class loader of the " + "class that contains the execution " + + "point identified by this entry, if " + "any. Only available on Java 9 or later.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].className").description( + "Name of the class that contains the " + "execution point identified by this entry."), + fieldWithPath("threads.[].stackTrace.[].fileName") + .description("Name of the source file that " + "contains the execution point " + + "identified by this entry, if any.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].lineNumber").description("Line number of the execution " + + "point identified by this entry. " + "Negative if unknown."), + fieldWithPath("threads.[].stackTrace.[].methodName").description("Name of the method."), + fieldWithPath("threads.[].stackTrace.[].moduleName") + .description("Name of the module that contains " + "the execution point identified by " + + "this entry, if any. Only available " + "on Java 9 or later.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].moduleVersion") + .description("Version of the module that " + "contains the execution point " + + "identified by this entry, if any. " + "Only available on Java 9 or later.") + .optional() + .type(JsonFieldType.STRING), + fieldWithPath("threads.[].stackTrace.[].nativeMethod") + .description("Whether the execution point is a native method."), + fieldWithPath("threads.[].suspended").description("Whether the thread is suspended."), + fieldWithPath("threads.[].threadId").description("ID of the thread."), + fieldWithPath("threads.[].threadName").description("Name of the thread."), + fieldWithPath("threads.[].threadState") + .description("State of the thread (" + describeEnumValues(Thread.State.class) + ")."), + fieldWithPath("threads.[].waitedCount") + .description("Total number of times that the thread has waited" + " for notification."), + fieldWithPath("threads.[].waitedTime") + .description("Time in milliseconds that the thread has spent " + + "waiting. -1 if thread contention " + "monitoring is disabled")))); latch.countDown(); } @Test void textThreadDump() throws Exception { - this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) - .andDo(MockMvcRestDocumentation.document("threaddump/text", - preprocessResponse(new ContentModifyingOperationPreprocessor((bytes, mediaType) -> { - String content = new String(bytes, StandardCharsets.UTF_8); - int mainThreadIndex = content.indexOf("\"main\" - Thread"); - String truncatedContent = (mainThreadIndex >= 0) ? content.substring(0, mainThreadIndex) - : content; - return truncatedContent.getBytes(); - })))); + this.mockMvc.perform(get("/actuator/threaddump").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()) + .andDo(MockMvcRestDocumentation.document("threaddump/text", + preprocessResponse(new ContentModifyingOperationPreprocessor((bytes, mediaType) -> { + String content = new String(bytes, StandardCharsets.UTF_8); + int mainThreadIndex = content.indexOf("\"main\" - Thread"); + String truncatedContent = (mainThreadIndex >= 0) ? content.substring(0, mainThreadIndex) + : content; + return truncatedContent.getBytes(); + })))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java index b826f9a9d9..b7bdb93c7e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,19 +47,20 @@ class JerseyWebEndpointIntegrationTests { @Test void whenJerseyIsConfiguredToUseAFilterThenResourceRegistrationSucceeds() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class, - JerseyAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - JerseyWebEndpointManagementContextConfiguration.class)) - .withUserConfiguration(ResourceConfigConfiguration.class) - .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)) - .withPropertyValues("spring.jersey.type=filter", "server.port=0").run((context) -> { - assertThat(context).hasNotFailed(); - Set resources = context.getBean(ResourceConfig.class).getResources(); - assertThat(resources).hasSize(1); - Resource resource = resources.iterator().next(); - assertThat(resource.getPath()).isEqualTo("/actuator"); - }); + .withConfiguration( + AutoConfigurations.of(JerseySameManagementContextConfiguration.class, JerseyAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, JerseyWebEndpointManagementContextConfiguration.class)) + .withUserConfiguration(ResourceConfigConfiguration.class) + .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)) + .withPropertyValues("spring.jersey.type=filter", "server.port=0") + .run((context) -> { + assertThat(context).hasNotFailed(); + Set resources = context.getBean(ResourceConfig.class).getResources(); + assertThat(resources).hasSize(1); + Resource resource = resources.iterator().next(); + assertThat(resource.getPath()).isEqualTo("/actuator"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java index d7b3bdd152..4a667841c3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/jersey/JerseyWebEndpointManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,9 +41,9 @@ import static org.assertj.core.api.Assertions.assertThat; class JerseyWebEndpointManagementContextConfigurationTests { private final WebApplicationContextRunner runner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebEndpointAutoConfiguration.class, - JerseyWebEndpointManagementContextConfiguration.class)) - .withBean(WebEndpointsSupplier.class, () -> Collections::emptyList); + .withConfiguration(AutoConfigurations.of(WebEndpointAutoConfiguration.class, + JerseyWebEndpointManagementContextConfiguration.class)) + .withBean(WebEndpointsSupplier.class, () -> Collections::emptyList); @Test void jerseyWebEndpointsResourcesRegistrarForEndpointsIsAutoConfigured() { @@ -53,15 +53,15 @@ class JerseyWebEndpointManagementContextConfigurationTests { @Test void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void autoConfigurationIsConditionalOnClassResourceConfig() { this.runner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java index b53d4533b8..f9b8bc6d56 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/env/EnvironmentEndpointAutoConfigurationTests.java @@ -47,19 +47,19 @@ import static org.assertj.core.api.Assertions.assertThat; class EnvironmentEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EnvironmentEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("dbPassword=123456", "apiKey=123456") - .run(validateSystemProperties("******", "******")); + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .run(validateSystemProperties("******", "******")); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.env.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(EnvironmentEndpoint.class)); } @Test @@ -70,54 +70,56 @@ class EnvironmentEndpointAutoConfigurationTests { @Test void customSanitizingFunctionsAreAppliedInOrder() { this.contextRunner.withUserConfiguration(SanitizingFunctionConfiguration.class) - .withPropertyValues("management.endpoint.env.show-values: WHEN_AUTHORIZED") - .withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("custom=123456", "password=123456").run((context) -> { - assertThat(context).hasSingleBean(EnvironmentEndpoint.class); - EnvironmentEndpoint endpoint = context.getBean(EnvironmentEndpoint.class); - EnvironmentDescriptor env = endpoint.environment(null); - Map systemProperties = getSource("systemProperties", env) - .getProperties(); - assertThat(systemProperties.get("custom").getValue()).isEqualTo("$$$111$$$"); - assertThat(systemProperties.get("password").getValue()).isEqualTo("$$$222$$$"); - }); + .withPropertyValues("management.endpoint.env.show-values: WHEN_AUTHORIZED") + .withPropertyValues("management.endpoints.web.exposure.include=env") + .withSystemProperties("custom=123456", "password=123456") + .run((context) -> { + assertThat(context).hasSingleBean(EnvironmentEndpoint.class); + EnvironmentEndpoint endpoint = context.getBean(EnvironmentEndpoint.class); + EnvironmentDescriptor env = endpoint.environment(null); + Map systemProperties = getSource("systemProperties", env) + .getProperties(); + assertThat(systemProperties.get("custom").getValue()).isEqualTo("$$$111$$$"); + assertThat(systemProperties.get("password").getValue()).isEqualTo("$$$222$$$"); + }); } @Test @SuppressWarnings("unchecked") void rolesCanBeConfiguredViaTheEnvironment() { this.contextRunner.withPropertyValues("management.endpoint.env.roles: test") - .withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("dbPassword=123456", "apiKey=123456").run((context) -> { - assertThat(context).hasSingleBean(EnvironmentEndpointWebExtension.class); - EnvironmentEndpointWebExtension endpoint = context.getBean(EnvironmentEndpointWebExtension.class); - Set roles = (Set) ReflectionTestUtils.getField(endpoint, "roles"); - assertThat(roles).contains("test"); - }); + .withPropertyValues("management.endpoints.web.exposure.include=env") + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .run((context) -> { + assertThat(context).hasSingleBean(EnvironmentEndpointWebExtension.class); + EnvironmentEndpointWebExtension endpoint = context.getBean(EnvironmentEndpointWebExtension.class); + Set roles = (Set) ReflectionTestUtils.getField(endpoint, "roles"); + assertThat(roles).contains("test"); + }); } @Test void showValuesCanBeConfiguredViaTheEnvironment() { this.contextRunner.withPropertyValues("management.endpoint.env.show-values: WHEN_AUTHORIZED") - .withPropertyValues("management.endpoints.web.exposure.include=env") - .withSystemProperties("dbPassword=123456", "apiKey=123456").run((context) -> { - assertThat(context).hasSingleBean(EnvironmentEndpoint.class); - assertThat(context).hasSingleBean(EnvironmentEndpointWebExtension.class); - EnvironmentEndpointWebExtension webExtension = context - .getBean(EnvironmentEndpointWebExtension.class); - EnvironmentEndpoint endpoint = context.getBean(EnvironmentEndpoint.class); - assertThat(webExtension).extracting("showValues").isEqualTo(Show.WHEN_AUTHORIZED); - assertThat(endpoint).extracting("showValues").isEqualTo(Show.WHEN_AUTHORIZED); - }); + .withPropertyValues("management.endpoints.web.exposure.include=env") + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .run((context) -> { + assertThat(context).hasSingleBean(EnvironmentEndpoint.class); + assertThat(context).hasSingleBean(EnvironmentEndpointWebExtension.class); + EnvironmentEndpointWebExtension webExtension = context.getBean(EnvironmentEndpointWebExtension.class); + EnvironmentEndpoint endpoint = context.getBean(EnvironmentEndpoint.class); + assertThat(webExtension).extracting("showValues").isEqualTo(Show.WHEN_AUTHORIZED); + assertThat(endpoint).extracting("showValues").isEqualTo(Show.WHEN_AUTHORIZED); + }); } @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=env") - .run((context) -> assertThat(context).hasSingleBean(EnvironmentEndpoint.class) - .doesNotHaveBean(EnvironmentEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=env") + .run((context) -> assertThat(context).hasSingleBean(EnvironmentEndpoint.class) + .doesNotHaveBean(EnvironmentEndpointWebExtension.class)); } private ContextConsumer validateSystemProperties(String dbPassword, String apiKey) { @@ -132,8 +134,11 @@ class EnvironmentEndpointAutoConfigurationTests { } private PropertySourceDescriptor getSource(String name, EnvironmentDescriptor descriptor) { - return descriptor.getPropertySources().stream().filter((source) -> name.equals(source.getName())).findFirst() - .get(); + return descriptor.getPropertySources() + .stream() + .filter((source) -> name.equals(source.getName())) + .findFirst() + .get(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java index 6f99929e49..fcc99dcc75 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/flyway/FlywayEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,19 +34,19 @@ import static org.mockito.Mockito.mock; class FlywayEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) - .withBean(Flyway.class, () -> mock(Flyway.class)); + .withConfiguration(AutoConfigurations.of(FlywayEndpointAutoConfiguration.class)) + .withBean(Flyway.class, () -> mock(Flyway.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=flyway") - .run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(FlywayEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.flyway.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(FlywayEndpoint.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java index 51b6f0128b..7101dd9522 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -37,8 +37,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastHealthContributorAutoConfigurationIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastHealthContributorAutoConfiguration.class, - HazelcastAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastHealthContributorAutoConfiguration.class, + HazelcastAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void hazelcastUp() { @@ -47,8 +47,9 @@ class HazelcastHealthContributorAutoConfigurationIntegrationTests { HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); Health health = context.getBean(HazelcastHealthIndicator.class).health(); assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnlyKeys("name", "uuid").containsEntry("name", hazelcast.getName()) - .containsEntry("uuid", hazelcast.getLocalEndpoint().getUuid().toString()); + assertThat(health.getDetails()).containsOnlyKeys("name", "uuid") + .containsEntry("name", hazelcast.getName()) + .containsEntry("uuid", hazelcast.getLocalEndpoint().getUuid().toString()); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java index 0d0ea309bd..73ed857e17 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/hazelcast/HazelcastHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,8 +34,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class, - HazelcastHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class, + HazelcastHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -45,7 +45,7 @@ class HazelcastHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.hazelcast.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HazelcastHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HazelcastHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java index ce2b322614..e769d93ef3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AbstractCompositeHealthContributorConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ abstract class AbstractCompositeHealthContributorConfigurationTests beans = Collections.emptyMap(); assertThatIllegalArgumentException().isThrownBy(() -> newComposite().createContributor(beans)) - .withMessage("Beans must not be empty"); + .withMessage("Beans must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java index d17a8e8612..b00c909453 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthContributorRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,10 +37,9 @@ class AutoConfiguredHealthContributorRegistryTests { @Test void createWhenContributorsClashesWithGroupNameThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> new AutoConfiguredHealthContributorRegistry( - Collections.singletonMap("boot", mock(HealthContributor.class)), - Arrays.asList("spring", "boot"))) - .withMessage("HealthContributor with name \"boot\" clashes with group"); + .isThrownBy(() -> new AutoConfiguredHealthContributorRegistry( + Collections.singletonMap("boot", mock(HealthContributor.class)), Arrays.asList("spring", "boot"))) + .withMessage("HealthContributor with name \"boot\" clashes with group"); } @Test @@ -48,8 +47,8 @@ class AutoConfiguredHealthContributorRegistryTests { HealthContributorRegistry registry = new AutoConfiguredHealthContributorRegistry(Collections.emptyMap(), Arrays.asList("spring", "boot")); assertThatIllegalStateException() - .isThrownBy(() -> registry.registerContributor("spring", mock(HealthContributor.class))) - .withMessage("HealthContributor with name \"spring\" clashes with group"); + .isThrownBy(() -> registry.registerContributor("spring", mock(HealthContributor.class))) + .withMessage("HealthContributor with name \"spring\" clashes with group"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java index 641a23fc4c..0044204f21 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -131,7 +131,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "root", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showDetails(this.securityContext)).isTrue(); } @@ -143,7 +143,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "rot", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showDetails(this.securityContext)).isFalse(); } @@ -219,7 +219,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "root", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showComponents(this.securityContext)).isTrue(); } @@ -231,7 +231,7 @@ class AutoConfiguredHealthEndpointGroupTests { Arrays.asList("admin", "rot", "bossmode"), null); Authentication principal = mock(Authentication.class); given(principal.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); given(this.securityContext.getPrincipal()).willReturn(principal); assertThat(group.showComponents(this.securityContext)).isFalse(); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java index 36ac40b308..f967126a9d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroupsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AutoConfiguredHealthEndpointGroupsTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AutoConfiguredHealthEndpointGroupsTestConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AutoConfiguredHealthEndpointGroupsTestConfiguration.class)); @Test void getPrimaryGroupMatchesAllMembers() { @@ -63,11 +63,13 @@ class AutoConfiguredHealthEndpointGroupsTests { @Test void getNamesReturnsGroupNames() { - this.contextRunner.withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.b.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - assertThat(groups.getNames()).containsExactlyInAnyOrder("a", "b"); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + assertThat(groups.getNames()).containsExactlyInAnyOrder("a", "b"); + }); } @Test @@ -90,233 +92,245 @@ class AutoConfiguredHealthEndpointGroupsTests { @Test void createWhenNoDefinedBeansAdaptsProperties() { - this.contextRunner.withPropertyValues("management.endpoint.health.show-components=always", - "management.endpoint.health.show-details=never", "management.endpoint.health.status.order=up,down", - "management.endpoint.health.status.http-mapping.down=200").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - assertThat(primary.showComponents(SecurityContext.NONE)).isTrue(); - assertThat(primary.showDetails(SecurityContext.NONE)).isFalse(); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) - .isEqualTo(Status.UP); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.show-components=always", + "management.endpoint.health.show-details=never", "management.endpoint.health.status.order=up,down", + "management.endpoint.health.status.http-mapping.down=200") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + assertThat(primary.showComponents(SecurityContext.NONE)).isTrue(); + assertThat(primary.showDetails(SecurityContext.NONE)).isFalse(); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) + .isEqualTo(Status.UP); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + }); } @Test void createWhenHasStatusAggregatorBeanReturnsInstanceWithAggregatorUsedForAllGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorConfiguration.class) - .withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - }); + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + }); } @Test void createWhenHasStatusAggregatorBeanAndGroupSpecificPropertyReturnsInstanceThatUsesBeanOnlyForUnconfiguredGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=up,down", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=up,down", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + }); } @Test void createWhenHasStatusAggregatorPropertyReturnsInstanceWithPropertyUsedForAllGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) - .isEqualTo(Status.UP); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) - .isEqualTo(Status.UP); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) + .isEqualTo(Status.UP); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasStatusAggregatorPropertyAndGroupSpecificPropertyReturnsInstanceWithPropertyUsedForExpectedGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=unknown,up,down", - "management.endpoint.health.group.b.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=unknown,up,down", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasStatusAggregatorPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.status.order=up,down", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=up,down", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - }); + .withPropertyValues("management.endpoint.health.status.order=up,down", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=up,down", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasGroupSpecificStatusAggregatorPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomStatusAggregatorGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.order=up,down", - "management.endpoint.health.group.b.include=*", - "management.endpoint.health.group.b.status.order=up,down") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.DOWN); - assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UNKNOWN); - assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) - .isEqualTo(Status.UP); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.order=up,down", + "management.endpoint.health.group.b.include=*", + "management.endpoint.health.group.b.status.order=up,down") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.DOWN); + assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UNKNOWN); + assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN)) + .isEqualTo(Status.UP); + }); } @Test void createWhenHasHttpCodeStatusMapperBeanReturnsInstanceWithMapperUsedForAllGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperConfiguration.class) - .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - }); + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + }); } @Test void createWhenHasHttpCodeStatusMapperBeanAndGroupSpecificPropertyReturnsInstanceThatUsesBeanOnlyForUnconfiguredGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=201", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=201", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + }); } @Test void createWhenHasHttpCodeStatusMapperPropertyReturnsInstanceWithPropertyUsedForAllGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenHasHttpCodeStatusMapperPropertyAndGroupSpecificPropertyReturnsInstanceWithPropertyUsedForExpectedGroups() { - this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=202", - "management.endpoint.health.group.b.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(202); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=202", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(202); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenHasHttpCodeStatusMapperPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", - "management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=201", - "management.endpoint.health.group.b.include=*") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + .withPropertyValues("management.endpoint.health.status.http-mapping.down=201", + "management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=201", + "management.endpoint.health.group.b.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenHasGroupSpecificHttpCodeStatusMapperPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() { this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperGroupAConfiguration.class) - .withPropertyValues("management.endpoint.health.group.a.include=*", - "management.endpoint.health.group.a.status.http-mapping.down=201", - "management.endpoint.health.group.b.include=*", - "management.endpoint.health.group.b.status.http-mapping.down=201") - .run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup primary = groups.getPrimary(); - HealthEndpointGroup groupA = groups.get("a"); - HealthEndpointGroup groupB = groups.get("b"); - assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(503); - assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); - assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); - }); + .withPropertyValues("management.endpoint.health.group.a.include=*", + "management.endpoint.health.group.a.status.http-mapping.down=201", + "management.endpoint.health.group.b.include=*", + "management.endpoint.health.group.b.status.http-mapping.down=201") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup primary = groups.getPrimary(); + HealthEndpointGroup groupA = groups.get("a"); + HealthEndpointGroup groupB = groups.get("b"); + assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(503); + assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200); + assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201); + }); } @Test void createWhenGroupWithNoShowDetailsOverrideInheritsShowDetails() { - this.contextRunner.withPropertyValues("management.endpoint.health.show-details=always", - "management.endpoint.health.group.a.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - HealthEndpointGroup groupA = groups.get("a"); - assertThat(groupA.showDetails(SecurityContext.NONE)).isTrue(); - }); + this.contextRunner + .withPropertyValues("management.endpoint.health.show-details=always", + "management.endpoint.health.group.a.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + HealthEndpointGroup groupA = groups.get("a"); + assertThat(groupA.showDetails(SecurityContext.NONE)).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java index 2f9482cdf8..c222878319 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredReactiveHealthContributorRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,10 +37,10 @@ class AutoConfiguredReactiveHealthContributorRegistryTests { @Test void createWhenContributorsClashesWithGroupNameThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> new AutoConfiguredReactiveHealthContributorRegistry( - Collections.singletonMap("boot", mock(ReactiveHealthContributor.class)), - Arrays.asList("spring", "boot"))) - .withMessage("ReactiveHealthContributor with name \"boot\" clashes with group"); + .isThrownBy(() -> new AutoConfiguredReactiveHealthContributorRegistry( + Collections.singletonMap("boot", mock(ReactiveHealthContributor.class)), + Arrays.asList("spring", "boot"))) + .withMessage("ReactiveHealthContributor with name \"boot\" clashes with group"); } @Test @@ -48,8 +48,8 @@ class AutoConfiguredReactiveHealthContributorRegistryTests { ReactiveHealthContributorRegistry registry = new AutoConfiguredReactiveHealthContributorRegistry( Collections.emptyMap(), Arrays.asList("spring", "boot")); assertThatIllegalStateException() - .isThrownBy(() -> registry.registerContributor("spring", mock(ReactiveHealthContributor.class))) - .withMessage("ReactiveHealthContributor with name \"spring\" clashes with group"); + .isThrownBy(() -> registry.registerContributor("spring", mock(ReactiveHealthContributor.class))) + .withMessage("ReactiveHealthContributor with name \"spring\" clashes with group"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java index 78e7fa9b03..42a30bca3c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -37,34 +37,34 @@ import static org.assertj.core.api.Assertions.assertThat; class HealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class)); @Test void runWhenNoOtherIndicatorsCreatesPingHealthIndicator() { this.contextRunner.run((context) -> assertThat(context).getBean(HealthIndicator.class) - .isInstanceOf(PingHealthIndicator.class)); + .isInstanceOf(PingHealthIndicator.class)); } @Test void runWhenHasDefinedIndicatorCreatesPingHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class) - .hasSingleBean(CustomHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class) + .hasSingleBean(CustomHealthIndicator.class)); } @Test void runWhenHasDefaultsDisabledDoesNotCreatePingHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .withPropertyValues("management.health.defaults.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HealthIndicator.class)); + .withPropertyValues("management.health.defaults.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(HealthIndicator.class)); } @Test void runWhenHasDefaultsDisabledAndPingIndicatorEnabledCreatesPingHealthIndicator() { this.contextRunner.withUserConfiguration(CustomHealthIndicatorConfiguration.class) - .withPropertyValues("management.health.defaults.enabled:false", "management.health.ping.enabled:true") - .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class)); + .withPropertyValues("management.health.defaults.enabled:false", "management.health.ping.enabled:true") + .run((context) -> assertThat(context).hasSingleBean(PingHealthIndicator.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java index 332077f140..0fa0520945 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,14 +71,15 @@ import static org.mockito.Mockito.mock; class HealthEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(HealthIndicatorsConfiguration.class).withConfiguration(AutoConfigurations - .of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); + .withUserConfiguration(HealthIndicatorsConfiguration.class) + .withConfiguration( + AutoConfigurations.of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)); private final ReactiveWebApplicationContextRunner reactiveContextRunner = new ReactiveWebApplicationContextRunner() - .withUserConfiguration(HealthIndicatorsConfiguration.class) - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class)); + .withUserConfiguration(HealthIndicatorsConfiguration.class) + .withConfiguration( + AutoConfigurations.of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class)); @Test void runWhenHealthEndpointIsDisabledDoesNotCreateBeans() { @@ -105,28 +106,30 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasStatusAggregatorBeanIgnoresProperties() { this.contextRunner.withUserConfiguration(StatusAggregatorConfiguration.class) - .withPropertyValues("management.endpoint.health.status.order=up,down").run((context) -> { - StatusAggregator aggregator = context.getBean(StatusAggregator.class); - assertThat(aggregator.getAggregateStatus(Status.UP, Status.DOWN)).isEqualTo(Status.UNKNOWN); - }); + .withPropertyValues("management.endpoint.health.status.order=up,down") + .run((context) -> { + StatusAggregator aggregator = context.getBean(StatusAggregator.class); + assertThat(aggregator.getAggregateStatus(Status.UP, Status.DOWN)).isEqualTo(Status.UNKNOWN); + }); } @Test void runCreatesHttpCodeStatusMapperFromProperties() { this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.up=123") - .run((context) -> { - HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); - assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(123); - }); + .run((context) -> { + HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); + assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(123); + }); } @Test void runWhenHasHttpCodeStatusMapperBeanIgnoresProperties() { this.contextRunner.withUserConfiguration(HttpCodeStatusMapperConfiguration.class) - .withPropertyValues("management.endpoint.health.status.http-mapping.up=123").run((context) -> { - HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); - assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(456); - }); + .withPropertyValues("management.endpoint.health.status.http-mapping.up=123") + .run((context) -> { + HttpCodeStatusMapper mapper = context.getBean(HttpCodeStatusMapper.class); + assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(456); + }); } @Test @@ -141,10 +144,11 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasHealthEndpointGroupsBeanDoesNotCreateAdditionalHealthEndpointGroups() { this.contextRunner.withUserConfiguration(HealthEndpointGroupsConfiguration.class) - .withPropertyValues("management.endpoint.health.group.ready.include=*").run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - assertThat(groups.getNames()).containsOnly("mock"); - }); + .withPropertyValues("management.endpoint.health.group.ready.include=*") + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + assertThat(groups.getNames()).containsOnly("mock"); + }); } @Test @@ -204,12 +208,11 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasReactiveHealthContributorRegistryBeanDoesNotCreateAdditionalReactiveHealthContributorRegistry() { this.reactiveContextRunner.withUserConfiguration(ReactiveHealthContributorRegistryConfiguration.class) - .run((context) -> { - ReactiveHealthContributorRegistry registry = context - .getBean(ReactiveHealthContributorRegistry.class); - Object[] names = registry.stream().map(NamedContributor::getName).toArray(); - assertThat(names).isEmpty(); - }); + .run((context) -> { + ReactiveHealthContributorRegistry registry = context.getBean(ReactiveHealthContributorRegistry.class); + Object[] names = registry.stream().map(NamedContributor::getName).toArray(); + assertThat(names).isEmpty(); + }); } @Test @@ -248,49 +251,53 @@ class HealthEndpointAutoConfigurationTests { @Test void runWhenHasReactiveHealthEndpointWebExtensionBeanDoesNotCreateExtraReactiveHealthEndpointWebExtension() { this.reactiveContextRunner.withUserConfiguration(ReactiveHealthEndpointWebExtensionConfiguration.class) - .run((context) -> { - ReactiveHealthEndpointWebExtension webExtension = context - .getBean(ReactiveHealthEndpointWebExtension.class); - Mono> response = webExtension.health(ApiVersion.V3, - WebServerNamespace.SERVER, SecurityContext.NONE, true, "simple"); - assertThat(response).isNull(); - }); + .run((context) -> { + ReactiveHealthEndpointWebExtension webExtension = context + .getBean(ReactiveHealthEndpointWebExtension.class); + Mono> response = webExtension.health(ApiVersion.V3, + WebServerNamespace.SERVER, SecurityContext.NONE, true, "simple"); + assertThat(response).isNull(); + }); } @Test void runWhenHasHealthEndpointGroupsPostProcessorPerformsProcessing() { - this.contextRunner.withPropertyValues("management.endpoint.health.group.ready.include=*").withUserConfiguration( - HealthEndpointGroupsConfiguration.class, TestHealthEndpointGroupsPostProcessor.class).run((context) -> { - HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> groups.get("test")) - .withMessage("postprocessed"); - }); + this.contextRunner.withPropertyValues("management.endpoint.health.group.ready.include=*") + .withUserConfiguration(HealthEndpointGroupsConfiguration.class, TestHealthEndpointGroupsPostProcessor.class) + .run((context) -> { + HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> groups.get("test")) + .withMessage("postprocessed"); + }); } @Test void runWithIndicatorsInParentContextFindsIndicators() { new ApplicationContextRunner().withUserConfiguration(HealthIndicatorsConfiguration.class) - .run((parent) -> new WebApplicationContextRunner().withConfiguration(AutoConfigurations - .of(HealthContributorAutoConfiguration.class, HealthEndpointAutoConfiguration.class)) - .withParent(parent).run((context) -> { - HealthComponent health = context.getBean(HealthEndpoint.class).health(); - Map components = ((SystemHealth) health).getComponents(); - assertThat(components).containsKeys("additional", "ping", "simple"); - })); + .run((parent) -> new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class)) + .withParent(parent) + .run((context) -> { + HealthComponent health = context.getBean(HealthEndpoint.class).health(); + Map components = ((SystemHealth) health).getComponents(); + assertThat(components).containsKeys("additional", "ping", "simple"); + })); } @Test void runWithReactiveContextAndIndicatorsInParentContextFindsIndicators() { new ApplicationContextRunner().withUserConfiguration(HealthIndicatorsConfiguration.class) - .run((parent) -> new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class)) - .withParent(parent).run((context) -> { - HealthComponent health = context.getBean(HealthEndpoint.class).health(); - Map components = ((SystemHealth) health).getComponents(); - assertThat(components).containsKeys("additional", "ping", "simple"); - })); + .run((parent) -> new ReactiveWebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + EndpointAutoConfiguration.class)) + .withParent(parent) + .run((context) -> { + HealthComponent health = context.getBean(HealthEndpoint.class).health(); + Map components = ((SystemHealth) health).getComponents(); + assertThat(components).containsKeys("additional", "ping", "simple"); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java index dacea343e2..4ed923d504 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/influx/InfluxDbHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -35,8 +35,9 @@ import static org.mockito.Mockito.mock; class InfluxDbHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(InfluxDB.class, () -> mock(InfluxDB.class)).withConfiguration(AutoConfigurations - .of(InfluxDbHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withBean(InfluxDB.class, () -> mock(InfluxDB.class)) + .withConfiguration(AutoConfigurations.of(InfluxDbHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,7 +47,7 @@ class InfluxDbHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.influxdb.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(InfluxDbHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java index fc6f4602ba..62801fdd64 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoContributorAutoConfigurationTests.java @@ -48,12 +48,12 @@ import static org.assertj.core.api.Assertions.assertThat; class InfoContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfoContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfoContributorAutoConfiguration.class)); @Test void envContributor() { this.contextRunner.withPropertyValues("management.info.env.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(EnvironmentInfoContributor.class)); + .run((context) -> assertThat(context).hasSingleBean(EnvironmentInfoContributor.class)); } @Test @@ -64,16 +64,16 @@ class InfoContributorAutoConfigurationTests { @Test void defaultInfoContributorsEnabledWithPrerequisitesInPlace() { this.contextRunner.withUserConfiguration(GitPropertiesConfiguration.class, BuildPropertiesConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(InfoContributor.class)).hasSize(2) - .satisfies((contributors) -> assertThat(contributors.values()) - .hasOnlyElementsOfTypes(BuildInfoContributor.class, GitInfoContributor.class))); + .run((context) -> assertThat(context.getBeansOfType(InfoContributor.class)).hasSize(2) + .satisfies((contributors) -> assertThat(contributors.values()) + .hasOnlyElementsOfTypes(BuildInfoContributor.class, GitInfoContributor.class))); } @Test void defaultInfoContributorsDisabledWithPrerequisitesInPlace() { this.contextRunner.withUserConfiguration(GitPropertiesConfiguration.class, BuildPropertiesConfiguration.class) - .withPropertyValues("management.info.defaults.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InfoContributor.class)); + .withPropertyValues("management.info.defaults.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InfoContributor.class)); } @Test @@ -101,15 +101,16 @@ class InfoContributorAutoConfigurationTests { @Test void gitPropertiesFullMode() { this.contextRunner.withPropertyValues("management.info.git.mode=full") - .withUserConfiguration(GitPropertiesConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(GitInfoContributor.class); - Map content = invokeContributor(context.getBean(GitInfoContributor.class)); - Object git = content.get("git"); - assertThat(git).isInstanceOf(Map.class); - Map gitInfo = (Map) git; - assertThat(gitInfo).containsOnlyKeys("branch", "commit", "foo"); - assertThat(gitInfo).containsEntry("foo", "bar"); - }); + .withUserConfiguration(GitPropertiesConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(GitInfoContributor.class); + Map content = invokeContributor(context.getBean(GitInfoContributor.class)); + Object git = content.get("git"); + assertThat(git).isInstanceOf(Map.class); + Map gitInfo = (Map) git; + assertThat(gitInfo).containsOnlyKeys("branch", "commit", "foo"); + assertThat(gitInfo).containsEntry("foo", "bar"); + }); } @Test @@ -139,7 +140,7 @@ class InfoContributorAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomBuildInfoContributorConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(BuildInfoContributor.class); assertThat(context.getBean(BuildInfoContributor.class)) - .isSameAs(context.getBean("customBuildInfoContributor")); + .isSameAs(context.getBean("customBuildInfoContributor")); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java index 79a10f45f2..fdf1d7a181 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/info/InfoEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -32,12 +32,12 @@ import static org.assertj.core.api.Assertions.assertThat; class InfoEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=info") - .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); } @Test @@ -48,7 +48,7 @@ class InfoEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.info.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(InfoEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java index 4e2fb0ab38..a67d7bf9db 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integration/IntegrationGraphEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,13 +36,13 @@ import static org.assertj.core.api.Assertions.assertThat; class IntegrationGraphEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class, - IntegrationGraphEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class, + IntegrationGraphEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=integrationgraph") - .run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(IntegrationGraphEndpoint.class)); } @Test @@ -64,7 +64,7 @@ class IntegrationGraphEndpointAutoConfigurationTests { @Test void runWhenSpringIntegrationIsNotEnabledShouldNotHaveEndpointBean() { ApplicationContextRunner noSpringIntegrationRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(IntegrationGraphEndpointAutoConfiguration.class)); noSpringIntegrationRunner.run((context) -> { assertThat(context).doesNotHaveBean(IntegrationGraphEndpoint.class); assertThat(context).doesNotHaveBean(IntegrationGraphServer.class); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java index e07687f90e..5e31018325 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/AbstractHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,46 +46,52 @@ abstract class AbstractHealthEndpointAdditionalPathIntegrationTests client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isNotFound(), "local.server.port")); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.web.exposure.exclude=health", + "management.server.port=0", "management.endpoint.health.group.live.include=diskSpace", + "management.endpoint.health.group.live.additional-path=server:healthz", + "management.endpoint.health.group.live.show-components=always") + .run(withWebTestClient((client) -> client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNotFound(), "local.server.port")); } @Test @@ -94,25 +100,42 @@ abstract class AbstractHealthEndpointAdditionalPathIntegrationTests client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isNotFound(), "local.server.port")); + .run(withWebTestClient((client) -> client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNotFound(), "local.server.port")); } @Test void groupsAreNotConfiguredWhenHealthEndpointIsNotExposedWithDifferentManagementPortAndCloudFoundryPlatform() { this.runner - .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.web.exposure.exclude=health", - "spring.main.cloud-platform=cloud_foundry", "management.server.port=0", - "management.endpoint.health.group.live.include=diskSpace", - "management.endpoint.health.group.live.additional-path=server:healthz", - "management.endpoint.health.group.live.show-components=always") - .run(withWebTestClient((client) -> client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isNotFound(), "local.server.port")); + .withPropertyValues("spring.jmx.enabled=true", "management.endpoints.web.exposure.exclude=health", + "spring.main.cloud-platform=cloud_foundry", "management.server.port=0", + "management.endpoint.health.group.live.include=diskSpace", + "management.endpoint.health.group.live.additional-path=server:healthz", + "management.endpoint.health.group.live.show-components=always") + .run(withWebTestClient((client) -> client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNotFound(), "local.server.port")); } private void testResponse(WebTestClient client) { - client.get().uri("/healthz").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk().expectBody() - .jsonPath("status").isEqualTo("UP").jsonPath("components.diskSpace").exists(); + client.get() + .uri("/healthz") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.diskSpace") + .exists(); } private ContextConsumer withWebTestClient(Consumer consumer, String property) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java index 442ad7dff8..884d7bda46 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebFluxIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class ControllerEndpointWebFluxIntegrationTests { @Test void endpointsCanBeAccessed() { TestSecurityContextHolder.getContext() - .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigReactiveWebApplicationContext(); this.context.register(DefaultConfiguration.class, ExampleController.class); TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java index 98187bed94..7c9c7b8f93 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/ControllerEndpointWebMvcIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -74,18 +74,18 @@ class ControllerEndpointWebMvcIntegrationTests { this.context.register(SecureConfiguration.class, ExampleController.class); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/actuator/example").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isUnauthorized()); + .andExpect(status().isUnauthorized()); } @Test void endpointsCanBeAccessed() throws Exception { TestSecurityContextHolder.getContext() - .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class, ExampleController.class); TestPropertyValues - .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") - .applyTo(this.context); + .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") + .applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/example")).andExpect(status().isOk()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java index 29d79fe72d..f027c7f21e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,14 +63,17 @@ class JerseyEndpointIntegrationTests { @Test void linksPageIsNotAvailableWhenDisabled() { getContextRunner(new Class[] { EndpointsConfiguration.class, ResourceConfigConfiguration.class }) - .withPropertyValues("management.endpoints.web.discovery.enabled:false").run((context) -> { - int port = context - .getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build(); - client.get().uri("/actuator").exchange().expectStatus().isNotFound(); - }); + .withPropertyValues("management.endpoints.web.discovery.enabled:false") + .run((context) -> { + int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) + .getWebServer() + .getPort(); + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); + client.get().uri("/actuator").exchange().expectStatus().isNotFound(); + }); } @Test @@ -85,9 +88,12 @@ class JerseyEndpointIntegrationTests { getAutoconfigurations(SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class)); contextRunner.run((context) -> { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build(); + .getWebServer() + .getPort(); + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); client.get().uri("/actuator").exchange().expectStatus().isUnauthorized(); }); } @@ -98,9 +104,12 @@ class JerseyEndpointIntegrationTests { ResourceConfigConfiguration.class, EndpointObjectMapperConfiguration.class }); contextRunner.run((context) -> { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build(); + .getWebServer() + .getPort(); + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); client.get().uri("/actuator/beans").exchange().expectStatus().isOk().expectBody().consumeWith((result) -> { String json = new String(result.getResponseBody(), StandardCharsets.UTF_8); assertThat(json).contains("\"scope\":\"notelgnis\""); @@ -111,12 +120,24 @@ class JerseyEndpointIntegrationTests { protected void testJerseyEndpoints(Class[] userConfigurations) { getContextRunner(userConfigurations).run((context) -> { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port) - .responseTimeout(Duration.ofMinutes(5)).build(); - client.get().uri("/actuator").exchange().expectStatus().isOk().expectBody().jsonPath("_links.beans") - .isNotEmpty().jsonPath("_links.restcontroller").doesNotExist().jsonPath("_links.controller") - .doesNotExist(); + .getWebServer() + .getPort(); + WebTestClient client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); + client.get() + .uri("/actuator") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.beans") + .isNotEmpty() + .jsonPath("_links.restcontroller") + .doesNotExist() + .jsonPath("_links.controller") + .doesNotExist(); }); } @@ -124,10 +145,10 @@ class JerseyEndpointIntegrationTests { Class... additionalAutoConfigurations) { FilteredClassLoader classLoader = new FilteredClassLoader(DispatcherServlet.class); return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withClassLoader(classLoader) - .withConfiguration(AutoConfigurations.of(getAutoconfigurations(additionalAutoConfigurations))) - .withUserConfiguration(userConfigurations) - .withPropertyValues("management.endpoints.web.exposure.include:*", "server.port:0"); + .withClassLoader(classLoader) + .withConfiguration(AutoConfigurations.of(getAutoconfigurations(additionalAutoConfigurations))) + .withUserConfiguration(userConfigurations) + .withPropertyValues("management.endpoints.web.exposure.include:*", "server.port:0"); } private Class[] getAutoconfigurations(Class... additional) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java index 95b2e1d4cc..e995ddfd0e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JerseyHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,13 +44,14 @@ class JerseyHealthEndpointAdditionalPathIntegrationTests extends JerseyHealthEndpointAdditionalPathIntegrationTests() { super(new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, JerseyAutoConfiguration.class, - EndpointAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, - WebEndpointAutoConfiguration.class, JerseyAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)).withPropertyValues("server.port=0")); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, JerseyAutoConfiguration.class, + EndpointAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, + WebEndpointAutoConfiguration.class, JerseyAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withClassLoader(new FilteredClassLoader(DispatcherServlet.class)) + .withPropertyValues("server.port=0")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java index 04529c295f..0513e92a9c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/JmxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,12 +51,12 @@ import static org.assertj.core.api.Assertions.assertThat; class JmxEndpointIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, - JmxEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, - HttpExchangesAutoConfiguration.class)) - .withUserConfiguration(HttpExchangeRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) - .withPropertyValues("spring.jmx.enabled=true") - .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, EndpointAutoConfiguration.class, + JmxEndpointAutoConfiguration.class, HealthContributorAutoConfiguration.class, + HttpExchangesAutoConfiguration.class)) + .withUserConfiguration(HttpExchangeRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) + .withPropertyValues("spring.jmx.enabled=true") + .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)); @Test void jmxEndpointsExposeHealthByDefault() { @@ -70,13 +70,12 @@ class JmxEndpointIntegrationTests { @Test void jmxEndpointsAreExposedWhenLazyInitializationIsEnabled() { this.contextRunner.withPropertyValues("management.endpoints.jmx.exposure.include:*") - .withBean(LazyInitializationBeanFactoryPostProcessor.class, - LazyInitializationBeanFactoryPostProcessor::new) - .run((context) -> { - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", - "health", "info", "mappings", "threaddump", "httpexchanges" }, new String[] { "shutdown" }); - }); + .withBean(LazyInitializationBeanFactoryPostProcessor.class, LazyInitializationBeanFactoryPostProcessor::new) + .run((context) -> { + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + checkEndpointMBeans(mBeanServer, new String[] { "beans", "conditions", "configprops", "env", "health", + "info", "mappings", "threaddump", "httpexchanges" }, new String[] { "shutdown" }); + }); } @Test @@ -101,11 +100,13 @@ class JmxEndpointIntegrationTests { private void checkEndpointMBeans(MBeanServer mBeanServer, String[] enabledEndpoints, String[] disabledEndpoints) { for (String enabledEndpoint : enabledEndpoints) { assertThat(isRegistered(mBeanServer, getDefaultObjectName(enabledEndpoint))) - .as(String.format("Endpoint %s", enabledEndpoint)).isTrue(); + .as(String.format("Endpoint %s", enabledEndpoint)) + .isTrue(); } for (String disabledEndpoint : disabledEndpoints) { assertThat(isRegistered(mBeanServer, getDefaultObjectName(disabledEndpoint))) - .as(String.format("Endpoint %s", disabledEndpoint)).isFalse(); + .as(String.format("Endpoint %s", disabledEndpoint)) + .isFalse(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java index 37ac6e7c3b..f2d6c56aca 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebEndpointsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,19 +59,19 @@ class WebEndpointsAutoConfigurationIntegrationTests { @Test void healthEndpointReactiveWebExtensionIsAutoConfigured() { reactiveWebRunner() - .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); } private WebApplicationContextRunner servletWebRunner() { return new WebApplicationContextRunner() - .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)).withPropertyValues( - "management.tracing.enabled=false", "management.defaults.metrics.export.enabled=false"); + .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)) + .withPropertyValues("management.tracing.enabled=false", "management.defaults.metrics.export.enabled=false"); } private ReactiveWebApplicationContextRunner reactiveWebRunner() { return new ReactiveWebApplicationContextRunner() - .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)).withPropertyValues( - "management.tracing.enabled=false", "management.defaults.metrics.export.enabled=false"); + .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)) + .withPropertyValues("management.tracing.enabled=false", "management.defaults.metrics.export.enabled=false"); } @EnableAutoConfiguration(exclude = { FlywayAutoConfiguration.class, LiquibaseAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java index 2cb180b832..c04d88d360 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointCorsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,126 +47,168 @@ import org.springframework.test.web.reactive.server.WebTestClient; class WebFluxEndpointCorsIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include:*"); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) + .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test void corsIsDisabledByDefault() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .exchange().expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectHeader() + .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))); } @Test void settingAllowedOriginsEnablesCors() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> { - webTestClient.options().uri("/actuator/beans").header("Origin", "test.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectStatus() - .isForbidden(); - performAcceptedCorsRequest(webTestClient, "/actuator/beans"); - })); + .run(withWebTestClient((webTestClient) -> { + webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "test.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectStatus() + .isForbidden(); + performAcceptedCorsRequest(webTestClient, "/actuator/beans"); + })); } @Test void settingAllowedOriginPatternsEnablesCors() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.org", - "management.endpoints.web.cors.allow-credentials:true") - .run(withWebTestClient((webTestClient) -> { - webTestClient.options().uri("/actuator/beans").header("Origin", "spring.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectStatus() - .isForbidden(); - performAcceptedCorsRequest(webTestClient, "/actuator/beans"); - })); + .withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.org", + "management.endpoints.web.cors.allow-credentials:true") + .run(withWebTestClient((webTestClient) -> { + webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectStatus() + .isForbidden(); + performAcceptedCorsRequest(webTestClient, "/actuator/beans"); + })); } @Test void maxAgeDefaultsTo30Minutes() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"))); } @Test void maxAgeCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.max-age: 2400") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.max-age: 2400") + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400"))); } @Test void requestsWithDisallowedHeadersAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus() - .isForbidden())); + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") + .exchange() + .expectStatus() + .isForbidden())); } @Test void allowedHeadersCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha").exchange().expectStatus().isOk() - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha"))); } @Test void requestsWithDisallowedMethodsAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH").exchange().expectStatus() - .isForbidden())); + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH") + .exchange() + .expectStatus() + .isForbidden())); } @Test void allowedMethodsCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .run(withWebTestClient((webTestClient) -> webTestClient.options().uri("/actuator/beans") - .header("Origin", "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD").exchange().expectStatus().isOk() - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allowed-methods:GET,HEAD") + .run(withWebTestClient((webTestClient) -> webTestClient.options() + .uri("/actuator/beans") + .header("Origin", "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD"))); } @Test void credentialsCanBeAllowed() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:true") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:true") + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))); } @Test void credentialsCanBeDisabled() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", - "management.endpoints.web.cors.allow-credentials:false") - .run(withWebTestClient((webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans") - .expectHeader().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:spring.example.org", + "management.endpoints.web.cors.allow-credentials:false") + .run(withWebTestClient( + (webTestClient) -> performAcceptedCorsRequest(webTestClient, "/actuator/beans").expectHeader() + .doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))); } private ContextConsumer withWebTestClient(Consumer webTestClient) { - return (context) -> webTestClient.accept(WebTestClient.bindToApplicationContext(context).configureClient() - .baseUrl("https://spring.example.org").build()); + return (context) -> webTestClient.accept(WebTestClient.bindToApplicationContext(context) + .configureClient() + .baseUrl("https://spring.example.org") + .build()); } private WebTestClient.ResponseSpec performAcceptedCorsRequest(WebTestClient webTestClient, String url) { - return webTestClient.options().uri(url).header(HttpHeaders.ORIGIN, "spring.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET").exchange().expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "spring.example.org").expectStatus().isOk(); + return webTestClient.options() + .uri(url) + .header(HttpHeaders.ORIGIN, "spring.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .exchange() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "spring.example.org") + .expectStatus() + .isOk(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java index d192568240..b0fe7468ae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,19 +48,28 @@ import static org.assertj.core.api.Assertions.assertThat; class WebFluxEndpointIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withUserConfiguration(EndpointsConfiguration.class); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) + .withUserConfiguration(EndpointsConfiguration.class); @Test void linksAreProvidedToAllEndpointTypes() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include:*").run((context) -> { WebTestClient client = createWebTestClient(context); - client.get().uri("/actuator").exchange().expectStatus().isOk().expectBody().jsonPath("_links.beans") - .isNotEmpty().jsonPath("_links.restcontroller").isNotEmpty().jsonPath("_links.controller") - .isNotEmpty(); + client.get() + .uri("/actuator") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.beans") + .isNotEmpty() + .jsonPath("_links.restcontroller") + .isNotEmpty() + .jsonPath("_links.controller") + .isNotEmpty(); }); } @@ -75,19 +84,27 @@ class WebFluxEndpointIntegrationTests { @Test void endpointObjectMapperCanBeApplied() { this.contextRunner.withUserConfiguration(EndpointObjectMapperConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include:*").run((context) -> { - WebTestClient client = createWebTestClient(context); - client.get().uri("/actuator/beans").exchange().expectStatus().isOk().expectBody() - .consumeWith((result) -> { - String json = new String(result.getResponseBody(), StandardCharsets.UTF_8); - assertThat(json).contains("\"scope\":\"notelgnis\""); - }); - }); + .withPropertyValues("management.endpoints.web.exposure.include:*") + .run((context) -> { + WebTestClient client = createWebTestClient(context); + client.get() + .uri("/actuator/beans") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith((result) -> { + String json = new String(result.getResponseBody(), StandardCharsets.UTF_8); + assertThat(json).contains("\"scope\":\"notelgnis\""); + }); + }); } private WebTestClient createWebTestClient(ApplicationContext context) { - return WebTestClient.bindToApplicationContext(context).configureClient().baseUrl("https://spring.example.org") - .build(); + return WebTestClient.bindToApplicationContext(context) + .configureClient() + .baseUrl("https://spring.example.org") + .build(); } @ControllerEndpoint(id = "controller") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java index 9189dda05a..2010657947 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebFluxHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,14 +45,14 @@ class WebFluxHealthEndpointAdditionalPathIntegrationTests extends WebFluxHealthEndpointAdditionalPathIntegrationTests() { super(new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, - EndpointAutoConfiguration.class, HealthEndpointAutoConfiguration.class, - DiskSpaceHealthContributorAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ReactiveWebServerFactoryAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withPropertyValues("server.port=0")); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, EndpointAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class, ReactiveManagementContextAutoConfiguration.class, + BeansEndpointAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java index 0d063be271..9a0ee8a1b4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointCorsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -51,120 +51,125 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class WebMvcEndpointCorsIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include:*"); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, BeansEndpointAutoConfiguration.class)) + .withPropertyValues("management.endpoints.web.exposure.include:*"); @Test void corsIsDisabledByDefault() { this.contextRunner.run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)))); + .perform(options("/actuator/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)))); } @Test void settingAllowedOriginsEnablesCors() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> { - mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(status().isForbidden()); - performAcceptedCorsRequest(mockMvc); - })); + .run(withMockMvc((mockMvc) -> { + mockMvc + .perform(options("/actuator/beans").header("Origin", "bar.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(status().isForbidden()); + performAcceptedCorsRequest(mockMvc); + })); } @Test void settingAllowedOriginPatternsEnablesCors() { - this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.com", - "management.endpoints.web.cors.allow-credentials:true").run(withMockMvc((mockMvc) -> { - mockMvc.perform(options("/actuator/beans").header("Origin", "bar.example.org") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(status().isForbidden()); - performAcceptedCorsRequest(mockMvc); - })); + this.contextRunner + .withPropertyValues("management.endpoints.web.cors.allowed-origin-patterns:*.example.com", + "management.endpoints.web.cors.allow-credentials:true") + .run(withMockMvc((mockMvc) -> { + mockMvc + .perform(options("/actuator/beans").header("Origin", "bar.example.org") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(status().isForbidden()); + performAcceptedCorsRequest(mockMvc); + })); } @Test void maxAgeDefaultsTo30Minutes() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")))); + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")))); } @Test void maxAgeCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.max-age: 2400") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.max-age: 2400") + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "2400")))); } @Test void requestsWithDisallowedHeadersAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> + .run(withMockMvc((mockMvc) -> - mockMvc.perform(options("/actuator/beans").header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) - .andExpect(status().isForbidden()))); + mockMvc + .perform(options("/actuator/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) + .andExpect(status().isForbidden()))); } @Test void allowedHeadersCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") - .run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header("Origin", "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allowed-headers:Alpha,Bravo") + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header("Origin", "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Alpha")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Alpha")))); } @Test void requestsWithDisallowedMethodsAreRejected() { this.contextRunner.withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com") - .run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) - .andExpect(status().isForbidden()))); + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PATCH")) + .andExpect(status().isForbidden()))); } @Test void allowedMethodsCanBeConfigured() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allowed-methods:GET,HEAD") - .run(withMockMvc((mockMvc) -> mockMvc - .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allowed-methods:GET,HEAD") + .run(withMockMvc((mockMvc) -> mockMvc + .perform(options("/actuator/beans").header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "HEAD")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,HEAD")))); } @Test void credentialsCanBeAllowed() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allow-credentials:true") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allow-credentials:true") + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")))); } @Test void credentialsCanBeDisabled() { this.contextRunner - .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", - "management.endpoints.web.cors.allow-credentials:false") - .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))); + .withPropertyValues("management.endpoints.web.cors.allowed-origins:foo.example.com", + "management.endpoints.web.cors.allow-credentials:false") + .run(withMockMvc((mockMvc) -> performAcceptedCorsRequest(mockMvc) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))); } private ContextConsumer withMockMvc(MockMvcConsumer mockMvc) { @@ -177,10 +182,10 @@ class WebMvcEndpointCorsIntegrationTests { private ResultActions performAcceptedCorsRequest(MockMvc mockMvc, String url) throws Exception { return mockMvc - .perform(options(url).header(HttpHeaders.ORIGIN, "foo.example.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "foo.example.com")) - .andExpect(status().isOk()); + .perform(options(url).header(HttpHeaders.ORIGIN, "foo.example.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "foo.example.com")) + .andExpect(status().isOk()); } @FunctionalInterface diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java index 1df1e5409a..6fb027288c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointExposureIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,17 +68,17 @@ class WebMvcEndpointExposureIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class, - DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, - ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, - HttpExchangesAutoConfiguration.class, HealthContributorAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) - .withUserConfiguration(CustomMvcEndpoint.class, CustomServletEndpoint.class, - HttpExchangeRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) - .withPropertyValues("server.port:0"); + .withConfiguration(AutoConfigurations.of(ServletWebServerFactoryAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + ManagementContextAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + HttpExchangesAutoConfiguration.class, HealthContributorAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(EndpointAutoConfigurationClasses.ALL)) + .withUserConfiguration(CustomMvcEndpoint.class, CustomServletEndpoint.class, + HttpExchangeRepositoryConfiguration.class, AuditEventRepositoryConfiguration.class) + .withPropertyValues("server.port:0"); @Test void webEndpointsAreDisabledByDefault() { @@ -102,7 +102,7 @@ class WebMvcEndpointExposureIntegrationTests { @Test void webEndpointsCanBeExposed() { WebApplicationContextRunner contextRunner = this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=*"); + .withPropertyValues("management.endpoints.web.exposure.include=*"); contextRunner.run((context) -> { WebTestClient client = createClient(context); assertThat(isExposed(client, HttpMethod.GET, "beans")).isTrue(); @@ -123,7 +123,7 @@ class WebMvcEndpointExposureIntegrationTests { @Test void singleWebEndpointCanBeExposed() { WebApplicationContextRunner contextRunner = this.contextRunner - .withPropertyValues("management.endpoints.web.exposure.include=beans"); + .withPropertyValues("management.endpoints.web.exposure.include=beans"); contextRunner.run((context) -> { WebTestClient client = createClient(context); assertThat(isExposed(client, HttpMethod.GET, "beans")).isTrue(); @@ -163,12 +163,17 @@ class WebMvcEndpointExposureIntegrationTests { } private WebTestClient createClient(AssertableWebApplicationContext context) { - int port = context.getSourceApplicationContext(ServletWebServerApplicationContext.class).getWebServer() - .getPort(); + int port = context.getSourceApplicationContext(ServletWebServerApplicationContext.class) + .getWebServer() + .getPort(); ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() - .codecs((configurer) -> configurer.defaultCodecs().maxInMemorySize(-1)).build(); - return WebTestClient.bindToServer().baseUrl("http://localhost:" + port).exchangeStrategies(exchangeStrategies) - .responseTimeout(Duration.ofMinutes(5)).build(); + .codecs((configurer) -> configurer.defaultCodecs().maxInMemorySize(-1)) + .build(); + return WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .exchangeStrategies(exchangeStrategies) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } private boolean isExposed(WebTestClient client, HttpMethod method, String path) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java index 0f13ee4301..6108345a1c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -106,18 +106,18 @@ class WebMvcEndpointIntegrationTests { TestPropertyValues.of("management.endpoints.web.base-path:/management").applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isUnauthorized()); + .andExpect(status().isUnauthorized()); } @Test void endpointsAreSecureWithActuatorRoleWithCustomBasePath() throws Exception { TestSecurityContextHolder.getContext() - .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); + .setAuthentication(new TestingAuthenticationToken("user", "N/A", "ROLE_ACTUATOR")); this.context = new AnnotationConfigServletWebApplicationContext(); this.context.register(SecureConfiguration.class); TestPropertyValues - .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") - .applyTo(this.context); + .of("management.endpoints.web.base-path:/management", "management.endpoints.web.exposure.include=*") + .applyTo(this.context); MockMvc mockMvc = createSecureMockMvc(); mockMvc.perform(get("/management/beans")).andExpect(status().isOk()); } @@ -128,8 +128,12 @@ class WebMvcEndpointIntegrationTests { this.context.register(DefaultConfiguration.class, EndpointsConfiguration.class); TestPropertyValues.of("management.endpoints.web.exposure.include=*").applyTo(this.context); MockMvc mockMvc = doCreateMockMvc(); - mockMvc.perform(get("/actuator").accept("*/*")).andExpect(status().isOk()).andExpect(jsonPath("_links", - both(hasKey("beans")).and(hasKey("servlet")).and(hasKey("restcontroller")).and(hasKey("controller")))); + mockMvc.perform(get("/actuator").accept("*/*")) + .andExpect(status().isOk()) + .andExpect(jsonPath("_links", + both(hasKey("beans")).and(hasKey("servlet")) + .and(hasKey("restcontroller")) + .and(hasKey("controller")))); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java index 03bc1904a2..1c2167bdbb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/integrationtest/WebMvcHealthEndpointAdditionalPathIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,14 +44,14 @@ class WebMvcHealthEndpointAdditionalPathIntegrationTests extends WebMvcHealthEndpointAdditionalPathIntegrationTests() { super(new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, WebMvcAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withPropertyValues("server.port=0")); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, WebMvcAutoConfiguration.class, + ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, + EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, DiskSpaceHealthContributorAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java index 8316f0acd9..6945cb71bb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -54,8 +54,8 @@ import static org.mockito.Mockito.mock; class DataSourceHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HealthContributorAutoConfiguration.class, DataSourceHealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + HealthContributorAutoConfiguration.class, DataSourceHealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -68,33 +68,34 @@ class DataSourceHealthContributorAutoConfigurationTests { @Test void runWhenMultipleDataSourceBeansShouldCreateCompositeIndicator() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, DataSourceConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(CompositeHealthContributor.class); - CompositeHealthContributor contributor = context.getBean(CompositeHealthContributor.class); - String[] names = contributor.stream().map(NamedContributor::getName).toArray(String[]::new); - assertThat(names).containsExactlyInAnyOrder("dataSource", "testDataSource"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(CompositeHealthContributor.class); + CompositeHealthContributor contributor = context.getBean(CompositeHealthContributor.class); + String[] names = contributor.stream().map(NamedContributor::getName).toArray(String[]::new); + assertThat(names).containsExactlyInAnyOrder("dataSource", "testDataSource"); + }); } @Test void runWithRoutingAndEmbeddedDataSourceShouldIncludeRoutingDataSource() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDataSourceConfig.class) - .run((context) -> { - CompositeHealthContributor composite = context.getBean(CompositeHealthContributor.class); - assertThat(composite.getContributor("dataSource")).isInstanceOf(DataSourceHealthIndicator.class); - assertThat(composite.getContributor("routingDataSource")) - .isInstanceOf(RoutingDataSourceHealthContributor.class); - }); + .run((context) -> { + CompositeHealthContributor composite = context.getBean(CompositeHealthContributor.class); + assertThat(composite.getContributor("dataSource")).isInstanceOf(DataSourceHealthIndicator.class); + assertThat(composite.getContributor("routingDataSource")) + .isInstanceOf(RoutingDataSourceHealthContributor.class); + }); } @Test void runWithRoutingAndEmbeddedDataSourceShouldNotIncludeRoutingDataSourceWhenIgnored() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, RoutingDataSourceConfig.class) - .withPropertyValues("management.health.db.ignore-routing-datasources:true").run((context) -> { - assertThat(context).doesNotHaveBean(CompositeHealthContributor.class); - assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); - assertThat(context).doesNotHaveBean(RoutingDataSourceHealthContributor.class); - }); + .withPropertyValues("management.health.db.ignore-routing-datasources:true") + .run((context) -> { + assertThat(context).doesNotHaveBean(CompositeHealthContributor.class); + assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); + assertThat(context).doesNotHaveBean(RoutingDataSourceHealthContributor.class); + }); } @Test @@ -102,39 +103,42 @@ class DataSourceHealthContributorAutoConfigurationTests { this.contextRunner.withUserConfiguration(RoutingDataSourceConfig.class).run((context) -> { assertThat(context).hasSingleBean(RoutingDataSourceHealthContributor.class); RoutingDataSourceHealthContributor routingHealthContributor = context - .getBean(RoutingDataSourceHealthContributor.class); + .getBean(RoutingDataSourceHealthContributor.class); assertThat(routingHealthContributor.getContributor("one")).isInstanceOf(DataSourceHealthIndicator.class); assertThat(routingHealthContributor.getContributor("two")).isInstanceOf(DataSourceHealthIndicator.class); - assertThat(routingHealthContributor.iterator()).toIterable().extracting("name") - .containsExactlyInAnyOrder("one", "two"); + assertThat(routingHealthContributor.iterator()).toIterable() + .extracting("name") + .containsExactlyInAnyOrder("one", "two"); }); } @Test void runWithOnlyRoutingDataSourceShouldCrashWhenIgnored() { this.contextRunner.withUserConfiguration(RoutingDataSourceConfig.class) - .withPropertyValues("management.health.db.ignore-routing-datasources:true") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasRootCauseInstanceOf(IllegalArgumentException.class)); + .withPropertyValues("management.health.db.ignore-routing-datasources:true") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasRootCauseInstanceOf(IllegalArgumentException.class)); } @Test void runWithValidationQueryPropertyShouldUseCustomQuery() { this.contextRunner - .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class) - .withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR").run((context) -> { - assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); - DataSourceHealthIndicator indicator = context.getBean(DataSourceHealthIndicator.class); - assertThat(indicator.getQuery()).isEqualTo("SELECT from FOOBAR"); - }); + .withUserConfiguration(DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class) + .withPropertyValues("spring.datasource.test.validation-query:SELECT from FOOBAR") + .run((context) -> { + assertThat(context).hasSingleBean(DataSourceHealthIndicator.class); + DataSourceHealthIndicator indicator = context.getBean(DataSourceHealthIndicator.class); + assertThat(indicator.getQuery()).isEqualTo("SELECT from FOOBAR"); + }); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("management.health.db.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class) - .doesNotHaveBean(CompositeHealthContributor.class)); + .withPropertyValues("management.health.db.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(DataSourceHealthIndicator.class) + .doesNotHaveBean(CompositeHealthContributor.class)); } @Test @@ -142,12 +146,13 @@ class DataSourceHealthContributorAutoConfigurationTests { this.contextRunner.withUserConfiguration(NullKeyRoutingDataSourceConfig.class).run((context) -> { assertThat(context).hasSingleBean(RoutingDataSourceHealthContributor.class); RoutingDataSourceHealthContributor routingHealthContributor = context - .getBean(RoutingDataSourceHealthContributor.class); + .getBean(RoutingDataSourceHealthContributor.class); assertThat(routingHealthContributor.getContributor("unnamed")) - .isInstanceOf(DataSourceHealthIndicator.class); + .isInstanceOf(DataSourceHealthIndicator.class); assertThat(routingHealthContributor.getContributor("one")).isInstanceOf(DataSourceHealthIndicator.class); - assertThat(routingHealthContributor.iterator()).toIterable().extracting("name") - .containsExactlyInAnyOrder("unnamed", "one"); + assertThat(routingHealthContributor.iterator()).toIterable() + .extracting("name") + .containsExactlyInAnyOrder("unnamed", "one"); }); } @@ -158,8 +163,12 @@ class DataSourceHealthContributorAutoConfigurationTests { @Bean @ConfigurationProperties(prefix = "spring.datasource.test") DataSource testDataSource() { - return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class) - .driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test").username("sa").build(); + return DataSourceBuilder.create() + .type(org.apache.tomcat.jdbc.pool.DataSource.class) + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .url("jdbc:hsqldb:mem:test") + .username("sa") + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java index 58246815a4..c8fa3c6962 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/jms/JmsHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class JmsHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, - JmsHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, + JmsHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,7 +46,7 @@ class JmsHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.jms.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java index 38f897ab94..90ee152976 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/ldap/LdapHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -36,8 +36,9 @@ import static org.mockito.Mockito.mock; class LdapHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(LdapOperations.class, () -> mock(LdapOperations.class)).withConfiguration(AutoConfigurations - .of(LdapHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); + .withBean(LdapOperations.class, () -> mock(LdapOperations.class)) + .withConfiguration(AutoConfigurations.of(LdapHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -47,7 +48,7 @@ class LdapHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.ldap.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LdapHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java index 02e82ed131..d1c8a0b0a6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,20 +37,20 @@ import static org.mockito.Mockito.mock; class LiquibaseEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LiquibaseEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=liquibase") - .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) - .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); + .withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) + .run((context) -> assertThat(context).hasSingleBean(LiquibaseEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withBean(SpringLiquibase.class, () -> mock(SpringLiquibase.class)) - .withPropertyValues("management.endpoint.liquibase.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); + .withPropertyValues("management.endpoint.liquibase.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class)); } @Test @@ -61,21 +61,23 @@ class LiquibaseEndpointAutoConfigurationTests { @Test void disablesCloseOfDataSourceWhenEndpointIsEnabled() { this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=liquibase").run((context) -> { - assertThat(context).hasSingleBean(LiquibaseEndpoint.class); - assertThat(context.getBean(DataSourceClosingSpringLiquibase.class)) - .hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", false); - }); + .withPropertyValues("management.endpoints.web.exposure.include=liquibase") + .run((context) -> { + assertThat(context).hasSingleBean(LiquibaseEndpoint.class); + assertThat(context.getBean(DataSourceClosingSpringLiquibase.class)) + .hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", false); + }); } @Test void doesNotDisableCloseOfDataSourceWhenEndpointIsDisabled() { this.contextRunner.withUserConfiguration(DataSourceClosingLiquibaseConfiguration.class) - .withPropertyValues("management.endpoint.liquibase.enabled:false").run((context) -> { - assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class); - DataSourceClosingSpringLiquibase bean = context.getBean(DataSourceClosingSpringLiquibase.class); - assertThat(bean).hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", true); - }); + .withPropertyValues("management.endpoint.liquibase.enabled:false") + .run((context) -> { + assertThat(context).doesNotHaveBean(LiquibaseEndpoint.class); + DataSourceClosingSpringLiquibase bean = context.getBean(DataSourceClosingSpringLiquibase.class); + assertThat(bean).hasFieldOrPropertyWithValue("closeDataSourceOnceMigrated", true); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java index 6492a90207..27831b04ae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LogFileWebEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -43,66 +43,68 @@ import static org.assertj.core.api.Assertions.contentOf; class LogFileWebEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LogFileWebEndpointAutoConfiguration.class)); @Test void runWithOnlyExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingFileIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.name:test.log") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingFileIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.file.name:test.log", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingPathIsSetAndNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("logging.file.path:test/logs") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void runWhenLoggingPathIsSetAndExposedShouldHaveEndpointBean() { this.contextRunner - .withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("logging.file.path:test/logs", "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test void logFileWebEndpointIsAutoConfiguredWhenExternalFileIsSet() { this.contextRunner - .withPropertyValues("management.endpoint.logfile.external-file:external.log", - "management.endpoints.web.exposure.include=logfile") - .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); + .withPropertyValues("management.endpoint.logfile.external-file:external.log", + "management.endpoints.web.exposure.include=logfile") + .run((context) -> assertThat(context).hasSingleBean(LogFileWebEndpoint.class)); } @Test void logFileWebEndpointCanBeDisabled() { this.contextRunner.withPropertyValues("logging.file.name:test.log", "management.endpoint.logfile.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LogFileWebEndpoint.class)); } @Test void logFileWebEndpointUsesConfiguredExternalFile(@TempDir Path temp) throws IOException { File file = new File(temp.toFile(), "logfile"); FileCopyUtils.copy("--TEST--".getBytes(), file); - this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=logfile", - "management.endpoint.logfile.external-file:" + file.getAbsolutePath()).run((context) -> { - assertThat(context).hasSingleBean(LogFileWebEndpoint.class); - LogFileWebEndpoint endpoint = context.getBean(LogFileWebEndpoint.class); - Resource resource = endpoint.logFile(); - assertThat(resource).isNotNull(); - assertThat(contentOf(resource.getFile())).isEqualTo("--TEST--"); - }); + this.contextRunner + .withPropertyValues("management.endpoints.web.exposure.include=logfile", + "management.endpoint.logfile.external-file:" + file.getAbsolutePath()) + .run((context) -> { + assertThat(context).hasSingleBean(LogFileWebEndpoint.class); + LogFileWebEndpoint endpoint = context.getBean(LogFileWebEndpoint.class); + Resource resource = endpoint.logFile(); + assertThat(resource).isNotNull(); + assertThat(contentOf(resource.getFile())).isEqualTo("--TEST--"); + }); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java index 9c0ee779c9..271fdef003 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/logging/LoggersEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,19 +36,19 @@ import static org.mockito.Mockito.mock; class LoggersEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) - .withUserConfiguration(LoggingConfiguration.class); + .withConfiguration(AutoConfigurations.of(LoggersEndpointAutoConfiguration.class)) + .withUserConfiguration(LoggingConfiguration.class); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=loggers") - .run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(LoggersEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.loggers.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Test @@ -59,7 +59,7 @@ class LoggersEndpointAutoConfigurationTests { @Test void runWithNoneLoggingSystemShouldNotHaveEndpointBean() { this.contextRunner.withSystemProperties("org.springframework.boot.logging.LoggingSystem=none") - .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(LoggersEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java index b51a8fed00..1c599275d6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/mail/MailHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,9 +34,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MailHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, - MailHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)) - .withPropertyValues("spring.mail.host:smtp.example.com"); + .withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, + MailHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)) + .withPropertyValues("spring.mail.host:smtp.example.com"); @Test void runShouldCreateIndicator() { @@ -46,7 +46,7 @@ class MailHealthContributorAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mail.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(MailHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java index 48403bc5b2..23a4296c21 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/HeapDumpWebEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -31,8 +31,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HeapDumpWebEndpointAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withPropertyValues("management.endpoints.web.exposure.include:*") - .withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class); + .withPropertyValues("management.endpoints.web.exposure.include:*") + .withUserConfiguration(HeapDumpWebEndpointAutoConfiguration.class); @Test void runShouldCreateIndicator() { @@ -42,7 +42,7 @@ class HeapDumpWebEndpointAutoConfigurationTests { @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.endpoint.heapdump.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HeapDumpWebEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java index b87afc45b2..e8ef6e2c46 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -33,12 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; class ThreadDumpEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ThreadDumpEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=threaddump") - .run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(ThreadDumpEndpoint.class)); } @Test @@ -49,8 +49,8 @@ class ThreadDumpEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=*") - .withPropertyValues("management.endpoint.threaddump.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); + .withPropertyValues("management.endpoint.threaddump.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ThreadDumpEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java index 4b6f8610be..26d59a87a0 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -42,8 +42,8 @@ class CompositeMeterRegistryAutoConfigurationTests { private static final String COMPOSITE_NAME = "compositeMeterRegistry"; private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(BaseConfig.class) - .withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); + .withUserConfiguration(BaseConfig.class) + .withConfiguration(AutoConfigurations.of(CompositeMeterRegistryAutoConfiguration.class)); @Test void registerWhenHasNoMeterRegistryShouldRegisterEmptyNoOpComposite() { @@ -66,8 +66,8 @@ class CompositeMeterRegistryAutoConfigurationTests { @Test void registerWhenHasMultipleMeterRegistriesShouldAddPrimaryComposite() { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesConfig.class).run((context) -> { - assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3).containsKeys("meterRegistryOne", - "meterRegistryTwo", COMPOSITE_NAME); + assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(3) + .containsKeys("meterRegistryOne", "meterRegistryTwo", COMPOSITE_NAME); MeterRegistry primary = context.getBean(MeterRegistry.class); assertThat(primary).isInstanceOf(CompositeMeterRegistry.class); assertThat(((CompositeMeterRegistry) primary).getRegistries()).hasSize(2); @@ -78,8 +78,8 @@ class CompositeMeterRegistryAutoConfigurationTests { @Test void registerWhenHasMultipleRegistriesAndOneIsPrimaryShouldDoNothing() { this.contextRunner.withUserConfiguration(MultipleMeterRegistriesWithOnePrimaryConfig.class).run((context) -> { - assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2).containsKeys("meterRegistryOne", - "meterRegistryTwo"); + assertThat(context.getBeansOfType(MeterRegistry.class)).hasSize(2) + .containsKeys("meterRegistryOne", "meterRegistryTwo"); MeterRegistry primary = context.getBean(MeterRegistry.class); assertThat(primary).isInstanceOf(TestMeterRegistry.class); }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java index 8b2599863c..16d1e47389 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/JvmMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JvmMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test void autoConfiguresJvmMetrics() { @@ -55,50 +55,54 @@ class JvmMetricsAutoConfigurationTests { @Test void allowsCustomJvmGcMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmGcMetricsConfiguration.class) - .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmGcMetrics"))); + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmGcMetrics"))); } @Test void allowsCustomJvmHeapPressureMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomJvmHeapPressureMetricsConfiguration.class).run( - assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmHeapPressureMetrics"))); + this.contextRunner.withUserConfiguration(CustomJvmHeapPressureMetricsConfiguration.class) + .run(assertMetricsBeans() + .andThen((context) -> assertThat(context).hasBean("customJvmHeapPressureMetrics"))); } @Test void allowsCustomJvmMemoryMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmMemoryMetricsConfiguration.class) - .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmMemoryMetrics"))); + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmMemoryMetrics"))); } @Test void allowsCustomJvmThreadMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmThreadMetricsConfiguration.class) - .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmThreadMetrics"))); + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmThreadMetrics"))); } @Test void allowsCustomClassLoaderMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class).run( - assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customClassLoaderMetrics"))); + this.contextRunner.withUserConfiguration(CustomClassLoaderMetricsConfiguration.class) + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customClassLoaderMetrics"))); } @Test void allowsCustomJvmInfoMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomJvmInfoMetricsConfiguration.class) - .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmInfoMetrics"))); + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmInfoMetrics"))); } @Test void allowsCustomJvmCompilationMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomJvmCompilationMetricsConfiguration.class).run( - assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmCompilationMetrics"))); + this.contextRunner.withUserConfiguration(CustomJvmCompilationMetricsConfiguration.class) + .run(assertMetricsBeans().andThen((context) -> assertThat(context).hasBean("customJvmCompilationMetrics"))); } private ContextConsumer assertMetricsBeans() { return (context) -> assertThat(context).hasSingleBean(JvmGcMetrics.class) - .hasSingleBean(JvmHeapPressureMetrics.class).hasSingleBean(JvmMemoryMetrics.class) - .hasSingleBean(JvmThreadMetrics.class).hasSingleBean(ClassLoaderMetrics.class) - .hasSingleBean(JvmInfoMetrics.class).hasSingleBean(JvmCompilationMetrics.class); + .hasSingleBean(JvmHeapPressureMetrics.class) + .hasSingleBean(JvmMemoryMetrics.class) + .hasSingleBean(JvmThreadMetrics.class) + .hasSingleBean(ClassLoaderMetrics.class) + .hasSingleBean(JvmInfoMetrics.class) + .hasSingleBean(JvmCompilationMetrics.class); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java index 8a2dcf27c1..2b23092193 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/KafkaMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -50,50 +50,52 @@ import static org.assertj.core.api.Assertions.assertThat; class KafkaMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KafkaMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KafkaMetricsAutoConfiguration.class)); @Test void whenThereIsAMeterRegistryThenMetricsListenersAreAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)).run((context) -> { - assertThat(((DefaultKafkaProducerFactory) context.getBean(DefaultKafkaProducerFactory.class)) - .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerProducerListener.class); - assertThat(((DefaultKafkaConsumerFactory) context.getBean(DefaultKafkaConsumerFactory.class)) - .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerConsumerListener.class); - }); + .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)) + .run((context) -> { + assertThat(((DefaultKafkaProducerFactory) context.getBean(DefaultKafkaProducerFactory.class)) + .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerProducerListener.class); + assertThat(((DefaultKafkaConsumerFactory) context.getBean(DefaultKafkaConsumerFactory.class)) + .getListeners()).hasSize(1).hasOnlyElementsOfTypes(MicrometerConsumerListener.class); + }); } @Test void whenThereIsNoMeterRegistryThenListenerCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)).run((context) -> { assertThat(((DefaultKafkaProducerFactory) context.getBean(DefaultKafkaProducerFactory.class)) - .getListeners()).isEmpty(); + .getListeners()).isEmpty(); assertThat(((DefaultKafkaConsumerFactory) context.getBean(DefaultKafkaConsumerFactory.class)) - .getListeners()).isEmpty(); + .getListeners()).isEmpty(); }); } @Test void whenKafkaStreamsIsEnabledAndThereIsAMeterRegistryThenMetricsListenersAreAdded() { this.contextRunner.withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)) - .withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app").with(MetricsRun.simple()).run((context) -> { - StreamsBuilderFactoryBean streamsBuilderFactoryBean = context - .getBean(StreamsBuilderFactoryBean.class); - assertThat(streamsBuilderFactoryBean.getListeners()).hasSize(1) - .hasOnlyElementsOfTypes(KafkaStreamsMicrometerListener.class); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app") + .with(MetricsRun.simple()) + .run((context) -> { + StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean(StreamsBuilderFactoryBean.class); + assertThat(streamsBuilderFactoryBean.getListeners()).hasSize(1) + .hasOnlyElementsOfTypes(KafkaStreamsMicrometerListener.class); + }); } @Test void whenKafkaStreamsIsEnabledAndThereIsNoMeterRegistryThenListenerCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)) - .withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app").run((context) -> { - StreamsBuilderFactoryBean streamsBuilderFactoryBean = context - .getBean(StreamsBuilderFactoryBean.class); - assertThat(streamsBuilderFactoryBean.getListeners()).isEmpty(); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app") + .run((context) -> { + StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean(StreamsBuilderFactoryBean.class); + assertThat(streamsBuilderFactoryBean.getListeners()).isEmpty(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java index b89d1b06b8..eb872327d3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,21 +38,21 @@ import static org.assertj.core.api.Assertions.assertThat; class Log4J2MetricsWithLog4jLoggerContextAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test void autoConfiguresLog4J2Metrics() { assertThat(LogManager.getContext().getClass().getName()) - .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); + .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); this.contextRunner.run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class)); } @Test void allowsCustomLog4J2MetricsToBeUsed() { assertThat(LogManager.getContext().getClass().getName()) - .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); - this.contextRunner.withUserConfiguration(CustomLog4J2MetricsConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class).hasBean("customLog4J2Metrics")); + .isEqualTo("org.apache.logging.log4j.core.LoggerContext"); + this.contextRunner.withUserConfiguration(CustomLog4J2MetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Log4j2Metrics.class).hasBean("customLog4J2Metrics")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java index 1026186658..4408fddad5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class Log4J2MetricsWithSlf4jLoggerContextAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(Log4J2MetricsAutoConfiguration.class)); @Test void backsOffWhenLoggerContextIsBackedBySlf4j() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java index b8c3830183..c9b7d63339 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; class LogbackMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)); @Test void autoConfiguresLogbackMetrics() { @@ -45,8 +45,8 @@ class LogbackMetricsAutoConfigurationTests { @Test void allowsCustomLogbackMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomLogbackMetricsConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(LogbackMetrics.class).hasBean("customLogbackMetrics")); + this.contextRunner.withUserConfiguration(CustomLogbackMetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(LogbackMetrics.class).hasBean("customLogbackMetrics")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java index a764a32afa..523d9eda47 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,8 +36,8 @@ import static org.assertj.core.api.Assertions.assertThat; class LogbackMetricsAutoConfigurationWithLog4j2AndLogbackTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class, LogbackMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, + SimpleMetricsExportAutoConfiguration.class, LogbackMetricsAutoConfiguration.class)); @Test void doesNotConfigureLogbackMetrics() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java index d1d48fdf9b..a24345324b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -40,9 +40,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MeterRegistryCustomizerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); + .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, + PrometheusMetricsExportAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test void commonTagsAreAppliedToAutoConfiguredBinders() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java index 316eea078b..baeba52d9a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -84,9 +84,11 @@ class MeterValueTests { MockEnvironment environment = new MockEnvironment(); TestPropertyValues.of("duration=10ms", "number=20.42").applyTo(environment); assertThat(Binder.get(environment).bind("duration", Bindable.of(MeterValue.class)).get().getValue(Type.TIMER)) - .isEqualTo(10000000); - assertThat(Binder.get(environment).bind("number", Bindable.of(MeterValue.class)).get() - .getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(20.42); + .isEqualTo(10000000); + assertThat(Binder.get(environment) + .bind("number", Bindable.of(MeterValue.class)) + .get() + .getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(20.42); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java index a5d7e2fec6..c6cbbbafd9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationIntegrationTests.java @@ -60,19 +60,22 @@ class MetricsAutoConfigurationIntegrationTests { @Test void propertyBasedCommonTagsIsAutoConfigured() { this.contextRunner - .withPropertyValues("management.metrics.tags.region=test", "management.metrics.tags.origin=local") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.counter("my.counter", "env", "qa"); - assertThat(registry.find("my.counter").tags("env", "qa").tags("region", "test") - .tags("origin", "local").counter()).isNotNull(); - }); + .withPropertyValues("management.metrics.tags.region=test", "management.metrics.tags.origin=local") + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.counter("my.counter", "env", "qa"); + assertThat(registry.find("my.counter") + .tags("env", "qa") + .tags("region", "test") + .tags("origin", "local") + .counter()).isNotNull(); + }); } @Test void simpleMeterRegistryIsUsedAsAFallback() { - this.contextRunner.run( - (context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); + this.contextRunner + .run((context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); } @Test @@ -87,59 +90,64 @@ class MetricsAutoConfigurationIntegrationTests { @Test void noCompositeIsCreatedWhenASingleMeterRegistryIsAutoConfigured() { new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(MeterRegistry.class)) - .isInstanceOf(GraphiteMeterRegistry.class)); + .run((context) -> assertThat(context.getBean(MeterRegistry.class)) + .isInstanceOf(GraphiteMeterRegistry.class)); } @Test void noCompositeIsCreatedWithMultipleRegistriesAndOneThatIsPrimary() { new ApplicationContextRunner() - .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, - JmxMetricsExportAutoConfiguration.class)) - .withUserConfiguration(PrimaryMeterRegistryConfiguration.class) - .run((context) -> assertThat(context.getBean(MeterRegistry.class)) - .isInstanceOf(SimpleMeterRegistry.class)); + .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, + JmxMetricsExportAutoConfiguration.class)) + .withUserConfiguration(PrimaryMeterRegistryConfiguration.class) + .run((context) -> assertThat(context.getBean(MeterRegistry.class)).isInstanceOf(SimpleMeterRegistry.class)); } @Test void compositeCreatedWithMultipleRegistries() { - new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, - JmxMetricsExportAutoConfiguration.class)).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); - assertThat(((CompositeMeterRegistry) registry).getRegistries()) - .hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) - .hasAtLeastOneElementOfType(JmxMeterRegistry.class); - }); + new ApplicationContextRunner() + .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, + JmxMetricsExportAutoConfiguration.class)) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry).isInstanceOf(CompositeMeterRegistry.class); + assertThat(((CompositeMeterRegistry) registry).getRegistries()) + .hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) + .hasAtLeastOneElementOfType(JmxMeterRegistry.class); + }); } @Test void autoConfiguredCompositeDoesNotHaveMeterFiltersApplied() { - new ApplicationContextRunner().with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, - JmxMetricsExportAutoConfiguration.class)).run((context) -> { - MeterRegistry composite = context.getBean(MeterRegistry.class); - assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).isEmpty(); - assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); - Set registries = ((CompositeMeterRegistry) composite).getRegistries(); - assertThat(registries).hasSize(2); - assertThat(registries).hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) - .hasAtLeastOneElementOfType(JmxMeterRegistry.class); - assertThat(registries).allSatisfy((registry) -> assertThat(registry) - .extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(1)); - }); + new ApplicationContextRunner() + .with(MetricsRun.limitedTo(GraphiteMetricsExportAutoConfiguration.class, + JmxMetricsExportAutoConfiguration.class)) + .run((context) -> { + MeterRegistry composite = context.getBean(MeterRegistry.class); + assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).isEmpty(); + assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); + Set registries = ((CompositeMeterRegistry) composite).getRegistries(); + assertThat(registries).hasSize(2); + assertThat(registries).hasAtLeastOneElementOfType(GraphiteMeterRegistry.class) + .hasAtLeastOneElementOfType(JmxMeterRegistry.class); + assertThat(registries).allSatisfy( + (registry) -> assertThat(registry).extracting("filters", InstanceOfAssertFactories.ARRAY) + .hasSize(1)); + }); } @Test void userConfiguredCompositeHasMeterFiltersApplied() { new ApplicationContextRunner().with(MetricsRun.limitedTo()) - .withUserConfiguration(CompositeMeterRegistryConfiguration.class).run((context) -> { - MeterRegistry composite = context.getBean(MeterRegistry.class); - assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(1); - assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); - Set registries = ((CompositeMeterRegistry) composite).getRegistries(); - assertThat(registries).hasSize(2); - assertThat(registries).hasOnlyElementsOfTypes(SimpleMeterRegistry.class); - }); + .withUserConfiguration(CompositeMeterRegistryConfiguration.class) + .run((context) -> { + MeterRegistry composite = context.getBean(MeterRegistry.class); + assertThat(composite).extracting("filters", InstanceOfAssertFactories.ARRAY).hasSize(1); + assertThat(composite).isInstanceOf(CompositeMeterRegistry.class); + Set registries = ((CompositeMeterRegistry) composite).getRegistries(); + assertThat(registries).hasSize(2); + assertThat(registries).hasOnlyElementsOfTypes(SimpleMeterRegistry.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java index 61db666d3f..ef1558f043 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java @@ -49,9 +49,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); + .with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class, + PrometheusMetricsExportAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class)); @Test void binderMetricsAreSearchableFromTheComposite() { @@ -59,48 +59,49 @@ class MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests { CompositeMeterRegistry composite = context.getBean(CompositeMeterRegistry.class); composite.get("jvm.memory.used").gauge(); context.getBeansOfType(MeterRegistry.class) - .forEach((name, registry) -> registry.get("jvm.memory.used").gauge()); + .forEach((name, registry) -> registry.get("jvm.memory.used").gauge()); }); } @Test void customizersAreAppliedBeforeBindersAreCreated() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - }); + .withConfiguration( + AutoConfigurations.of(MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + }); } @Test void counterIsIncrementedOncePerEventWithoutCompositeMeterRegistry() { new ApplicationContextRunner().with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> { - Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("test-logger"); - logger.error("Error."); - Map registriesByName = context.getBeansOfType(MeterRegistry.class); - assertThat(registriesByName).hasSize(1); - MeterRegistry registry = registriesByName.values().iterator().next(); - assertThat(registry.get("logback.events").tag("level", "error").counter().count()).isOne(); - }); + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)) + .run((context) -> { + Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("test-logger"); + logger.error("Error."); + Map registriesByName = context.getBeansOfType(MeterRegistry.class); + assertThat(registriesByName).hasSize(1); + MeterRegistry registry = registriesByName.values().iterator().next(); + assertThat(registry.get("logback.events").tag("level", "error").counter().count()).isOne(); + }); } @Test void counterIsIncrementedOncePerEventWithCompositeMeterRegistry() { new ApplicationContextRunner() - .with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class, - PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> { - Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("test-logger"); - logger.error("Error."); - Map registriesByName = context.getBeansOfType(MeterRegistry.class); - assertThat(registriesByName).hasSize(3); - registriesByName - .forEach((name, - registry) -> assertThat( - registry.get("logback.events").tag("level", "error").counter().count()) - .isOne()); - }); + .with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class, + PrometheusMetricsExportAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)) + .run((context) -> { + Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("test-logger"); + logger.error("Error."); + Map registriesByName = context.getBeansOfType(MeterRegistry.class); + assertThat(registriesByName).hasSize(3); + registriesByName.forEach((name, + registry) -> assertThat(registry.get("logback.events").tag("level", "error").counter().count()) + .isOne()); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java index fd8f773084..c04c31435a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock; class MetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)); @Test void autoConfiguresAClock() { @@ -54,7 +54,7 @@ class MetricsAutoConfigurationTests { @Test void allowsACustomClockToBeUsed() { this.contextRunner.withUserConfiguration(CustomClockConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasBean("customClock")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasBean("customClock")); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java index 7c5d733d6e..5db70a5285 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class PropertiesMeterFilterTests { @Test void createWhenPropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertiesMeterFilter(null)) - .withMessageContaining("Properties must not be null"); + .withMessageContaining("Properties must not be null"); } @Test @@ -119,7 +119,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -127,7 +127,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring.boot=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isFalse(); + .isPercentileHistogram()).isFalse(); } @Test @@ -135,7 +135,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -143,7 +143,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.spring=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isFalse(); + .isPercentileHistogram()).isFalse(); } @Test @@ -152,7 +152,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.percentiles-histogram.spring=true", "distribution.percentiles-histogram.spring.boot=false")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isFalse(); + .isPercentileHistogram()).isFalse(); } @Test @@ -161,7 +161,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.percentiles-histogram.spring=false", "distribution.percentiles-histogram.spring.boot=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -169,7 +169,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles-histogram.all=true")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .isPercentileHistogram()).isTrue(); + .isPercentileHistogram()).isTrue(); } @Test @@ -177,7 +177,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring.boot=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(1, 1.5, 2); + .containsExactly(1, 1.5, 2); } @Test @@ -185,7 +185,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.spring=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(1, 1.5, 2); + .containsExactly(1, 1.5, 2); } @Test @@ -193,7 +193,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( "distribution.percentiles.spring=1,1.5,2", "distribution.percentiles.spring.boot=3,3.5,4")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(3, 3.5, 4); + .containsExactly(3, 3.5, 4); } @Test @@ -201,7 +201,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.percentiles.all=1,1.5,2")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getPercentiles()) - .containsExactly(1, 1.5, 2); + .containsExactly(1, 1.5, 2); } @Test @@ -209,14 +209,14 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.slo.spring.boot=1,2,3")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); + .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); } @Test void configureWhenHasHigherSloShouldSetPercentilesToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.slo.spring=1,2,3")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); + .getServiceLevelObjectiveBoundaries()).containsExactly(1000000, 2000000, 3000000); } @Test @@ -224,7 +224,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.slo.spring=1,2,3", "distribution.slo.spring.boot=4,5,6")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getServiceLevelObjectiveBoundaries()).containsExactly(4000000, 5000000, 6000000); + .getServiceLevelObjectiveBoundaries()).containsExactly(4000000, 5000000, 6000000); } @Test @@ -232,7 +232,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring.boot=10")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); + .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); } @Test @@ -240,7 +240,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.minimum-expected-value.spring=10")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); + .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10).toNanos()); } @Test @@ -248,7 +248,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties( "distribution.minimum-expected-value.spring=10", "distribution.minimum-expected-value.spring.boot=50")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(50).toNanos()); + .getMinimumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(50).toNanos()); } @Test @@ -256,7 +256,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring.boot=5000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); + .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); } @Test @@ -264,7 +264,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.maximum-expected-value.spring=5000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); + .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(5000).toNanos()); } @Test @@ -273,7 +273,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.maximum-expected-value.spring=5000", "distribution.maximum-expected-value.spring.boot=10000")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT) - .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10000).toNanos()); + .getMaximumExpectedValueAsDouble()).isEqualTo(Duration.ofMillis(10000).toNanos()); } @Test @@ -281,14 +281,14 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.expiry[spring.boot]=5ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(5)); + .isEqualTo(Duration.ofMillis(5)); } @Test void configureWhenHasHigherExpiryShouldSetExpiryToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.expiry.spring=5ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(5)); + .isEqualTo(Duration.ofMillis(5)); } @Test @@ -296,14 +296,14 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter( createProperties("distribution.expiry.spring=5ms", "distribution.expiry[spring.boot]=10ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(10)); + .isEqualTo(Duration.ofMillis(10)); } @Test void configureWhenAllExpirySetShouldSetExpiryToValue() { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.expiry.all=5ms")); assertThat(filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getExpiry()) - .isEqualTo(Duration.ofMillis(5)); + .isEqualTo(Duration.ofMillis(5)); } @Test @@ -312,7 +312,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.buffer-length.spring.boot=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } @Test @@ -321,7 +321,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.buffer-length.spring=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } @Test @@ -330,7 +330,7 @@ class PropertiesMeterFilterTests { createProperties("distribution.buffer-length.spring=2", "distribution.buffer-length.spring.boot=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } @Test @@ -338,7 +338,7 @@ class PropertiesMeterFilterTests { PropertiesMeterFilter filter = new PropertiesMeterFilter(createProperties("distribution.buffer-length.all=3")); assertThat( filter.configure(createMeterId("spring.boot"), DistributionStatisticConfig.DEFAULT).getBufferLength()) - .isEqualTo(3); + .isEqualTo(3); } private Id createMeterId(String name) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java index cba6e2c355..3a9c1215a8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/SystemMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; class SystemMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(SystemMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SystemMetricsAutoConfiguration.class)); @Test void autoConfiguresUptimeMetrics() { @@ -54,8 +54,8 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomUptimeMetricsToBeUsed() { - this.contextRunner.withUserConfiguration(CustomUptimeMetricsConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(UptimeMetrics.class).hasBean("customUptimeMetrics")); + this.contextRunner.withUserConfiguration(CustomUptimeMetricsConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(UptimeMetrics.class).hasBean("customUptimeMetrics")); } @Test @@ -66,8 +66,8 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomProcessorMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomProcessorMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class) - .hasBean("customProcessorMetrics")); + .run((context) -> assertThat(context).hasSingleBean(ProcessorMetrics.class) + .hasBean("customProcessorMetrics")); } @Test @@ -78,8 +78,8 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomFileDescriptorMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomFileDescriptorMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class) - .hasBean("customFileDescriptorMetrics")); + .run((context) -> assertThat(context).hasSingleBean(FileDescriptorMetrics.class) + .hasBean("customFileDescriptorMetrics")); } @Test @@ -90,29 +90,31 @@ class SystemMetricsAutoConfigurationTests { @Test void allowsCustomDiskSpaceMetricsToBeUsed() { this.contextRunner.withUserConfiguration(CustomDiskSpaceMetricsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(DiskSpaceMetricsBinder.class) - .hasBean("customDiskSpaceMetrics")); + .run((context) -> assertThat(context).hasSingleBean(DiskSpaceMetricsBinder.class) + .hasBean("customDiskSpaceMetrics")); } @Test void diskSpaceMetricsUsesDefaultPath() { - this.contextRunner - .run((context) -> assertThat(context).hasBean("diskSpaceMetrics").getBean(DiskSpaceMetricsBinder.class) - .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File(".")))); + this.contextRunner.run((context) -> assertThat(context).hasBean("diskSpaceMetrics") + .getBean(DiskSpaceMetricsBinder.class) + .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File(".")))); } @Test void allowsDiskSpaceMetricsPathToBeConfiguredWithSinglePath() { this.contextRunner.withPropertyValues("management.metrics.system.diskspace.paths:..") - .run((context) -> assertThat(context).hasBean("diskSpaceMetrics").getBean(DiskSpaceMetricsBinder.class) - .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File("..")))); + .run((context) -> assertThat(context).hasBean("diskSpaceMetrics") + .getBean(DiskSpaceMetricsBinder.class) + .hasFieldOrPropertyWithValue("paths", Collections.singletonList(new File("..")))); } @Test void allowsDiskSpaceMetricsPathToBeConfiguredWithMultiplePaths() { this.contextRunner.withPropertyValues("management.metrics.system.diskspace.paths:.,..") - .run((context) -> assertThat(context).hasBean("diskSpaceMetrics").getBean(DiskSpaceMetricsBinder.class) - .hasFieldOrPropertyWithValue("paths", Arrays.asList(new File("."), new File("..")))); + .run((context) -> assertThat(context).hasBean("diskSpaceMetrics") + .getBean(DiskSpaceMetricsBinder.class) + .hasFieldOrPropertyWithValue("paths", Arrays.asList(new File("."), new File("..")))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java index 4a8f4e0d6b..15352a43c9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/ValidationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class ValidationFailureAnalyzerTests { @Test void analyzesMissingRequiredConfiguration() { FailureAnalysis analysis = new ValidationFailureAnalyzer() - .analyze(createFailure(MissingAccountIdAndApiKeyConfiguration.class)); + .analyze(createFailure(MissingAccountIdAndApiKeyConfiguration.class)); assertThat(analysis).isNotNull(); assertThat(analysis.getCause().getMessage()).contains("management.newrelic.metrics.export.apiKey was 'null'"); assertThat(analysis.getDescription()).isEqualTo(String.format("Invalid Micrometer configuration detected:%n%n" diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java index dd2c9931a3..9193d5adda 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -38,8 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; class RabbitMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration( - AutoConfigurations.of(RabbitAutoConfiguration.class, RabbitMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class, RabbitMetricsAutoConfiguration.class)); @Test void autoConfiguredConnectionFactoryIsInstrumented() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java index 5c16b62c69..1d3894f07f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/cache/CacheMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,49 +36,57 @@ import static org.assertj.core.api.Assertions.assertThat; class CacheMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withUserConfiguration(CachingConfiguration.class).withConfiguration( - AutoConfigurations.of(CacheAutoConfiguration.class, CacheMetricsAutoConfiguration.class)); + .withUserConfiguration(CachingConfiguration.class) + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, CacheMetricsAutoConfiguration.class)); @Test void autoConfiguredCache2kIsInstrumented() { this.contextRunner.withPropertyValues("spring.cache.type=cache2k", "spring.cache.cache-names=cache1,cache2") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); - registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); + registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); + }); } @Test void autoConfiguredCacheManagerIsInstrumented() { this.contextRunner.withPropertyValues("spring.cache.type=caffeine", "spring.cache.cache-names=cache1,cache2") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); - registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager").meter(); + registry.get("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager").meter(); + }); } @Test void autoConfiguredNonSupportedCacheManagerIsIgnored() { this.contextRunner.withPropertyValues("spring.cache.type=simple", "spring.cache.cache-names=cache1,cache2") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("cache.gets").tags("name", "cache1").tags("cache.manager", "cacheManager") - .meter()).isNull(); - assertThat(registry.find("cache.gets").tags("name", "cache2").tags("cache.manager", "cacheManager") - .meter()).isNull(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("cache.gets") + .tags("name", "cache1") + .tags("cache.manager", "cacheManager") + .meter()).isNull(); + assertThat(registry.find("cache.gets") + .tags("name", "cache2") + .tags("cache.manager", "cacheManager") + .meter()).isNull(); + }); } @Test void cacheInstrumentationCanBeDisabled() { - this.contextRunner.withPropertyValues("management.metrics.enable.cache=false", "spring.cache.type=caffeine", - "spring.cache.cache-names=cache1").run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("cache.requests").tags("name", "cache1") - .tags("cache.manager", "cacheManager").meter()).isNull(); - }); + this.contextRunner + .withPropertyValues("management.metrics.enable.cache=false", "spring.cache.type=caffeine", + "spring.cache.cache-names=cache1") + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("cache.requests") + .tags("name", "cache1") + .tags("cache.manager", "cacheManager") + .meter()).isNull(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java index 8af724a05d..67138448b1 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class MetricsRepositoryMethodInvocationListenerBeanPostProcessorTests { Object result = this.postProcessor.postProcessBeforeInitialization(bean, "name"); assertThat(result).isSameAs(bean); ArgumentCaptor customizer = ArgumentCaptor - .forClass(RepositoryFactoryCustomizer.class); + .forClass(RepositoryFactoryCustomizer.class); then(bean).should().addRepositoryFactoryCustomizer(customizer.capture()); RepositoryFactorySupport repositoryFactory = mock(RepositoryFactorySupport.class); customizer.getValue().customize(repositoryFactory); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java index 534f0a73ee..7242d8d999 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationIntegrationTests.java @@ -43,25 +43,27 @@ import static org.assertj.core.api.Assertions.assertThat; class RepositoryMetricsAutoConfigurationIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration( - AutoConfigurations.of(HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, RepositoryMetricsAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, TestConfig.class); + .withConfiguration( + AutoConfigurations.of(HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, RepositoryMetricsAutoConfiguration.class)) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, TestConfig.class); @Test void repositoryMethodCallRecordsMetrics() { this.contextRunner.run((context) -> { context.getBean(CityRepository.class).count(); MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.get("spring.data.repository.invocations").tag("repository", "CityRepository").timer() - .count()).isOne(); + assertThat(registry.get("spring.data.repository.invocations") + .tag("repository", "CityRepository") + .timer() + .count()).isOne(); }); } @Test void doesNotPreventMeterBindersFromDependingUponSpringDataRepositories() { this.contextRunner.withUserConfiguration(SpringDataRepositoryMeterBinderConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java index bf461b030f..2d4e21993d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/data/RepositoryMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -58,13 +58,13 @@ import static org.mockito.Mockito.mock; class RepositoryMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)); @Test void backsOffWhenMeterRegistryIsMissing() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(RepositoryTagsProvider.class)); + .withConfiguration(AutoConfigurations.of(RepositoryMetricsAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(RepositoryTagsProvider.class)); } @Test @@ -87,58 +87,60 @@ class RepositoryMetricsAutoConfigurationTests { @Test void metricsRepositoryMethodInvocationListenerBacksOff() { this.contextRunner.withUserConfiguration(MetricsRepositoryMethodInvocationListenerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(MetricsRepositoryMethodInvocationListener.class); - assertThat(context).hasSingleBean(TestMetricsRepositoryMethodInvocationListener.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(MetricsRepositoryMethodInvocationListener.class); + assertThat(context).hasSingleBean(TestMetricsRepositoryMethodInvocationListener.class); + }); } @Test void metricNameCanBeConfigured() { this.contextRunner.withPropertyValues("management.metrics.data.repository.metric-name=datarepo") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); - Timer timer = registry.get("datarepo").timer(); - assertThat(timer).isNotNull(); - }); + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); + Timer timer = registry.get("datarepo").timer(); + assertThat(timer).isNotNull(); + }); } @Test void autoTimeRequestsCanBeConfigured() { - this.contextRunner.withPropertyValues("management.metrics.data.repository.autotime.enabled=true", - "management.metrics.data.repository.autotime.percentiles=0.5,0.7").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); - Timer timer = registry.get("spring.data.repository.invocations").timer(); - HistogramSnapshot snapshot = timer.takeSnapshot(); - assertThat(snapshot.percentileValues()).hasSize(2); - assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); - assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); - }); + this.contextRunner + .withPropertyValues("management.metrics.data.repository.autotime.enabled=true", + "management.metrics.data.repository.autotime.percentiles=0.5,0.7") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context, ExampleRepository.class); + Timer timer = registry.get("spring.data.repository.invocations").timer(); + HistogramSnapshot snapshot = timer.takeSnapshot(); + assertThat(snapshot.percentileValues()).hasSize(2); + assertThat(snapshot.percentileValues()[0].percentile()).isEqualTo(0.5); + assertThat(snapshot.percentileValues()[1].percentile()).isEqualTo(0.7); + }); } @Test void timerWorksWithTimedAnnotationsWhenAutoTimeRequestsIsFalse() { this.contextRunner.withPropertyValues("management.metrics.data.repository.autotime.enabled=false") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context, ExampleAnnotatedRepository.class); - Collection meters = registry.get("spring.data.repository.invocations").meters(); - assertThat(meters).hasSize(1); - Meter meter = meters.iterator().next(); - assertThat(meter.getId().getTag("method")).isEqualTo("count"); - }); + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context, ExampleAnnotatedRepository.class); + Collection meters = registry.get("spring.data.repository.invocations").meters(); + assertThat(meters).hasSize(1); + Meter meter = meters.iterator().next(); + assertThat(meter.getId().getTag("method")).isEqualTo("count"); + }); } @Test void doesNotTriggerEarlyInitializationThatPreventsMeterBindersFromBindingMeters() { this.contextRunner.withUserConfiguration(MeterBinderConfiguration.class) - .run((context) -> assertThat(context.getBean(MeterRegistry.class).find("binder.test").counter()) - .isNotNull()); + .run((context) -> assertThat(context.getBean(MeterRegistry.class).find("binder.test").counter()) + .isNotNull()); } private MeterRegistry getInitializedMeterRegistry(AssertableApplicationContext context, Class repositoryInterface) { MetricsRepositoryMethodInvocationListener listener = context - .getBean(MetricsRepositoryMethodInvocationListener.class); + .getBean(MetricsRepositoryMethodInvocationListener.class); ReflectionUtils.doWithLocalMethods(repositoryInterface, (method) -> { RepositoryMethodInvocationResult result = mock(RepositoryMethodInvocationResult.class); given(result.getState()).willReturn(State.SUCCESS); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java index f5af6d67cc..eb0cf1cc6e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ConditionalOnEnabledMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,21 +40,21 @@ class ConditionalOnEnabledMetricsExportAutoConfigurationTests { @Test void exporterCanBeSpecificallyDisabled() { this.contextRunner.withPropertyValues("management.simple.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); + .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); } @Test void exporterCanBeGloballyDisabled() { this.contextRunner.withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); + .run((context) -> assertThat(context).doesNotHaveBean("simpleMeterRegistry")); } @Test void exporterCanBeGloballyDisabledWithSpecificOverride() { this.contextRunner - .withPropertyValues("management.defaults.metrics.export.enabled=false", - "management.simple.metrics.export.enabled=true") - .run((context) -> assertThat(context).hasBean("simpleMeterRegistry")); + .withPropertyValues("management.defaults.metrics.export.enabled=false", + "management.simple.metrics.export.enabled=true") + .run((context) -> assertThat(context).hasBean("simpleMeterRegistry")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java index 05a14b771f..82799cca91 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/appoptics/AppOpticsMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AppOpticsMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AppOpticsMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AppOpticsMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,50 +47,54 @@ class AppOpticsMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { this.contextRunner.withPropertyValues("management.appoptics.metrics.export.api-token=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AppOpticsMeterRegistry.class).hasSingleBean(AppOpticsConfig.class)); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) + .hasSingleBean(AppOpticsConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) - .doesNotHaveBean(AppOpticsConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) + .doesNotHaveBean(AppOpticsConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.appoptics.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) - .doesNotHaveBean(AppOpticsConfig.class)); + .withPropertyValues("management.appoptics.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AppOpticsMeterRegistry.class) + .doesNotHaveBean(AppOpticsConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) - .hasSingleBean(AppOpticsConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) + .hasSingleBean(AppOpticsConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withPropertyValues("management.appoptics.metrics.export.api-token=abcde") - .withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(AppOpticsConfig.class)); + .withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AppOpticsMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(AppOpticsConfig.class)); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withPropertyValues("management.appoptics.metrics.export.api-token=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - AppOpticsMeterRegistry registry = context.getBean(AppOpticsMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + AppOpticsMeterRegistry registry = context.getBean(AppOpticsMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java index 6d24e0cc17..58acc17be7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class AtlasMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AtlasMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AtlasMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,36 +46,41 @@ class AtlasMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AtlasMeterRegistry.class) + .hasSingleBean(AtlasConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) - .doesNotHaveBean(AtlasConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) + .doesNotHaveBean(AtlasConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.atlas.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) - .doesNotHaveBean(AtlasConfig.class)); + .withPropertyValues("management.atlas.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(AtlasMeterRegistry.class) + .doesNotHaveBean(AtlasConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class).hasSingleBean(AtlasConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AtlasMeterRegistry.class) + .hasSingleBean(AtlasConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(AtlasMeterRegistry.class).hasBean("customRegistry").hasSingleBean(AtlasConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AtlasMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(AtlasConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java index 48b777c69d..b84575c0f7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/atlas/AtlasPropertiesConfigAdapterTests.java @@ -90,7 +90,7 @@ class AtlasPropertiesConfigAdapterTests { AtlasProperties properties = new AtlasProperties(); properties.setConfigRefreshFrequency(Duration.ofMinutes(5)); assertThat(new AtlasPropertiesConfigAdapter(properties).configRefreshFrequency()) - .isEqualTo(Duration.ofMinutes(5)); + .isEqualTo(Duration.ofMinutes(5)); } @Test @@ -105,7 +105,7 @@ class AtlasPropertiesConfigAdapterTests { AtlasProperties properties = new AtlasProperties(); properties.setConfigUri("https://atlas.example.com/config"); assertThat(new AtlasPropertiesConfigAdapter(properties).configUri()) - .isEqualTo("https://atlas.example.com/config"); + .isEqualTo("https://atlas.example.com/config"); } @Test @@ -113,7 +113,7 @@ class AtlasPropertiesConfigAdapterTests { AtlasProperties properties = new AtlasProperties(); properties.setEvalUri("https://atlas.example.com/evaluate"); assertThat(new AtlasPropertiesConfigAdapter(properties).evalUri()) - .isEqualTo("https://atlas.example.com/evaluate"); + .isEqualTo("https://atlas.example.com/evaluate"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java index 50202cb474..5364e79d52 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/datadog/DatadogMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class DatadogMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DatadogMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DatadogMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,56 +47,60 @@ class DatadogMetricsExportAutoConfigurationTests { @Test void failsWithoutAnApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasFailed()); + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.datadog.metrics.export.api-key=abcde") - .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) - .hasSingleBean(DatadogConfig.class)); + .withPropertyValues("management.datadog.metrics.export.api-key=abcde") + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) + .hasSingleBean(DatadogConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) - .doesNotHaveBean(DatadogConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) + .doesNotHaveBean(DatadogConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.datadog.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) - .doesNotHaveBean(DatadogConfig.class)); + .withPropertyValues("management.datadog.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DatadogMeterRegistry.class) + .doesNotHaveBean(DatadogConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(DatadogMeterRegistry.class).hasSingleBean(DatadogConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) + .hasSingleBean(DatadogConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.datadog.metrics.export.api-key=abcde") - .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(DatadogConfig.class)); + .withPropertyValues("management.datadog.metrics.export.api-key=abcde") + .run((context) -> assertThat(context).hasSingleBean(DatadogMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(DatadogConfig.class)); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.datadog.metrics.export.api-key=abcde").run((context) -> { - DatadogMeterRegistry registry = context.getBean(DatadogMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.datadog.metrics.export.api-key=abcde") + .run((context) -> { + DatadogMeterRegistry registry = context.getBean(DatadogMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java index 47028a921c..94c7923f4b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatraceMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; class DynatraceMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DynatraceMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DynatraceMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -50,56 +50,61 @@ class DynatraceMetricsExportAutoConfigurationTests { @Test void failsWithADeviceIdWithoutAUri() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.dynatrace.metrics.export.v1.device-id:dev-1") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.dynatrace.metrics.export.v1.device-id:dev-1") + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(v1MandatoryProperties()) - .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) - .hasSingleBean(DynatraceConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .with(v1MandatoryProperties()) + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) + .hasSingleBean(DynatraceConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) - .doesNotHaveBean(DynatraceConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) + .doesNotHaveBean(DynatraceConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.dynatrace.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) - .doesNotHaveBean(DynatraceConfig.class)); + .withPropertyValues("management.dynatrace.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(DynatraceMeterRegistry.class) + .doesNotHaveBean(DynatraceConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) - .hasSingleBean(DynatraceConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) + .hasSingleBean(DynatraceConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).with(v1MandatoryProperties()) - .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(DynatraceConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .with(v1MandatoryProperties()) + .run((context) -> assertThat(context).hasSingleBean(DynatraceMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(DynatraceConfig.class)); } @Test void stopsMeterRegistryForV1ApiWhenContextIsClosed() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).with(v1MandatoryProperties()) - .run((context) -> { - DynatraceMeterRegistry registry = context.getBean(DynatraceMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .with(v1MandatoryProperties()) + .run((context) -> { + DynatraceMeterRegistry registry = context.getBean(DynatraceMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java index 86143ac76f..16a8dd2bf9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -108,7 +108,7 @@ class DynatracePropertiesConfigAdapterTests { defaultDimensions.put("dim2", "value2"); properties.getV2().setDefaultDimensions(defaultDimensions); assertThat(new DynatracePropertiesConfigAdapter(properties).defaultDimensions()) - .containsExactlyEntriesOf(defaultDimensions); + .containsExactlyEntriesOf(defaultDimensions); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java index fe35df10a8..69f3651bc3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/dynatrace/DynatracePropertiesTests.java @@ -37,7 +37,7 @@ class DynatracePropertiesTests extends StepRegistryPropertiesTests { assertStepRegistryDefaultValues(properties, config); assertThat(properties.getV1().getTechnologyType()).isEqualTo(config.technologyType()); assertThat(properties.getV2().isUseDynatraceSummaryInstruments()) - .isEqualTo(config.useDynatraceSummaryInstruments()); + .isEqualTo(config.useDynatraceSummaryInstruments()); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java index 2bf60b0b58..776606d7db 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/elastic/ElasticMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ElasticMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,38 +47,42 @@ class ElasticMetricsExportAutoConfigurationTests { @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) + .hasSingleBean(ElasticConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) - .doesNotHaveBean(ElasticConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) + .doesNotHaveBean(ElasticConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.elastic.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) - .doesNotHaveBean(ElasticConfig.class)); + .withPropertyValues("management.elastic.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(ElasticMeterRegistry.class) + .doesNotHaveBean(ElasticConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ElasticMeterRegistry.class).hasSingleBean(ElasticConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) + .hasSingleBean(ElasticConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(ElasticConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(ElasticMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(ElasticConfig.class)); } @Test @@ -94,19 +98,23 @@ class ElasticMetricsExportAutoConfigurationTests { @Test void apiKeyCredentialsIsMutuallyExclusiveWithUserName() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.elastic.metrics.export.api-key-credentials:secret", - "management.elastic.metrics.export.user-name:alice") - .run((context) -> assertThat(context).hasFailed().getFailure().rootCause() - .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); + .withPropertyValues("management.elastic.metrics.export.api-key-credentials:secret", + "management.elastic.metrics.export.user-name:alice") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .rootCause() + .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); } @Test void apiKeyCredentialsIsMutuallyExclusiveWithPassword() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.elastic.metrics.export.api-key-credentials:secret", - "management.elastic.metrics.export.password:secret") - .run((context) -> assertThat(context).hasFailed().getFailure().rootCause() - .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); + .withPropertyValues("management.elastic.metrics.export.api-key-credentials:secret", + "management.elastic.metrics.export.password:secret") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .rootCause() + .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java index d7485f1554..a73a1ba82f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class GangliaMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GangliaMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GangliaMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,37 +46,41 @@ class GangliaMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) + .hasSingleBean(GangliaConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) - .doesNotHaveBean(GangliaConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) + .doesNotHaveBean(GangliaConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.ganglia.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) - .doesNotHaveBean(GangliaConfig.class)); + .withPropertyValues("management.ganglia.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GangliaMeterRegistry.class) + .doesNotHaveBean(GangliaConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(GangliaMeterRegistry.class).hasSingleBean(GangliaConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) + .hasSingleBean(GangliaConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(GangliaConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(GangliaMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(GangliaConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java index 3afd087f8b..d837b00192 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/ganglia/GangliaPropertiesConfigAdapterTests.java @@ -57,7 +57,7 @@ class GangliaPropertiesConfigAdapterTests { GangliaProperties properties = new GangliaProperties(); properties.setAddressingMode(UDPAddressingMode.UNICAST); assertThat(new GangliaPropertiesConfigAdapter(properties).addressingMode()) - .isEqualTo(UDPAddressingMode.UNICAST); + .isEqualTo(UDPAddressingMode.UNICAST); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java index 8bcf7e996f..8112e3a55a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/graphite/GraphiteMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; class GraphiteMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -49,61 +49,65 @@ class GraphiteMetricsExportAutoConfigurationTests { @Test void autoConfiguresUseTagsAsPrefix() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.graphite.metrics.export.tags-as-prefix=app").run((context) -> { - assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); - GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); - registry.counter("test.count", Tags.of("app", "myapp")); - assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("myapp.testCount"); - }); + .withPropertyValues("management.graphite.metrics.export.tags-as-prefix=app") + .run((context) -> { + assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); + GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); + registry.counter("test.count", Tags.of("app", "myapp")); + assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("myapp.testCount"); + }); } @Test void autoConfiguresWithTagsAsPrefixCanBeDisabled() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.graphite.metrics.export.tags-as-prefix=app", - "management.graphite.metrics.export.graphite-tags-enabled=true") - .run((context) -> { - assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); - GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); - registry.counter("test.count", Tags.of("app", "myapp")); - assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("test.count;app=myapp"); - }); + .withPropertyValues("management.graphite.metrics.export.tags-as-prefix=app", + "management.graphite.metrics.export.graphite-tags-enabled=true") + .run((context) -> { + assertThat(context).hasSingleBean(GraphiteMeterRegistry.class); + GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class); + registry.counter("test.count", Tags.of("app", "myapp")); + assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("test.count;app=myapp"); + }); } @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(GraphiteMeterRegistry.class).hasSingleBean(GraphiteConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) + .hasSingleBean(GraphiteConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) - .doesNotHaveBean(GraphiteConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) + .doesNotHaveBean(GraphiteConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.graphite.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) - .doesNotHaveBean(GraphiteConfig.class)); + .withPropertyValues("management.graphite.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class) + .doesNotHaveBean(GraphiteConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) - .hasSingleBean(GraphiteConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) + .hasSingleBean(GraphiteConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(GraphiteConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(GraphiteConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java index d8af629c2b..7391edbc89 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HumioMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HumioMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HumioMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,36 +47,41 @@ class HumioMetricsExportAutoConfigurationTests { @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(HumioMeterRegistry.class) + .hasSingleBean(HumioConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) - .doesNotHaveBean(HumioConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) + .doesNotHaveBean(HumioConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.humio.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) - .doesNotHaveBean(HumioConfig.class)); + .withPropertyValues("management.humio.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(HumioMeterRegistry.class) + .doesNotHaveBean(HumioConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class).hasSingleBean(HumioConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(HumioMeterRegistry.class) + .hasSingleBean(HumioConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(HumioMeterRegistry.class).hasBean("customRegistry").hasSingleBean(HumioConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(HumioMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(HumioConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java index dffce7e8eb..37b99bb9bc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/humio/HumioPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ class HumioPropertiesConfigAdapterTests { HumioProperties properties = new HumioProperties(); properties.setTags(Collections.singletonMap("name", "test")); assertThat(new HumioPropertiesConfigAdapter(properties).tags()) - .isEqualTo(Collections.singletonMap("name", "test")); + .isEqualTo(Collections.singletonMap("name", "test")); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java index b9a7e09555..ca41bed08c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/influx/InfluxMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class InfluxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfluxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfluxMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,36 +46,41 @@ class InfluxMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(InfluxMeterRegistry.class) + .hasSingleBean(InfluxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) - .doesNotHaveBean(InfluxConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) + .doesNotHaveBean(InfluxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.influx.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) - .doesNotHaveBean(InfluxConfig.class)); + .withPropertyValues("management.influx.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InfluxMeterRegistry.class) + .doesNotHaveBean(InfluxConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class).hasSingleBean(InfluxConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(InfluxMeterRegistry.class) + .hasSingleBean(InfluxConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(InfluxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(InfluxConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(InfluxMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(InfluxConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java index 79eaecb3fb..3fb1b62069 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/jmx/JmxMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JmxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,35 +46,40 @@ class JmxMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class) - .doesNotHaveBean(JmxConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class) + .doesNotHaveBean(JmxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.jmx.metrics.export.enabled=false").run((context) -> assertThat(context) - .doesNotHaveBean(JmxMeterRegistry.class).doesNotHaveBean(JmxConfig.class)); + .withPropertyValues("management.jmx.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(JmxMeterRegistry.class) + .doesNotHaveBean(JmxConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JmxMeterRegistry.class).hasSingleBean(JmxConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class) + .hasSingleBean(JmxConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JmxMeterRegistry.class).hasBean("customRegistry").hasSingleBean(JmxConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JmxMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(JmxConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java index 2e30390154..d1d702c0a4 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class KairosMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KairosMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KairosMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,36 +46,41 @@ class KairosMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(KairosMeterRegistry.class) + .hasSingleBean(KairosConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) - .doesNotHaveBean(KairosConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) + .doesNotHaveBean(KairosConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.kairos.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) - .doesNotHaveBean(KairosConfig.class)); + .withPropertyValues("management.kairos.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(KairosMeterRegistry.class) + .doesNotHaveBean(KairosConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class).hasSingleBean(KairosConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(KairosMeterRegistry.class) + .hasSingleBean(KairosConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(KairosMeterRegistry.class).hasBean("customRegistry").hasSingleBean(KairosConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(KairosMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(KairosConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java index 711069faff..94e6617c26 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/kairos/KairosPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class KairosPropertiesConfigAdapterTests KairosProperties properties = createProperties(); properties.setUri("https://kairos.example.com:8080/api/v1/datapoints"); assertThat(createConfigAdapter(properties).uri()) - .isEqualTo("https://kairos.example.com:8080/api/v1/datapoints"); + .isEqualTo("https://kairos.example.com:8080/api/v1/datapoints"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java index e38feddb9d..f3fd55adf7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/newrelic/NewRelicMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ import static org.mockito.Mockito.mock; class NewRelicMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(NewRelicMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(NewRelicMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -51,112 +51,115 @@ class NewRelicMetricsExportAutoConfigurationTests { @Test void failsWithoutAnApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.account-id=12345") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.newrelic.metrics.export.account-id=12345") + .run((context) -> assertThat(context).hasFailed()); } @Test void failsWithoutAnAccountId() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde") + .run((context) -> assertThat(context).hasFailed()); } @Test void failsToAutoConfigureWithoutEventType() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=12345", - "management.newrelic.metrics.export.event-type=") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=12345", + "management.newrelic.metrics.export.event-type=") + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresWithEventTypeOverridden() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=12345", - "management.newrelic.metrics.export.event-type=wxyz") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(NewRelicConfig.class)); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=12345", + "management.newrelic.metrics.export.event-type=wxyz") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(NewRelicConfig.class)); } @Test void autoConfiguresWithMeterNameEventTypeEnabledAndWithoutEventType() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=12345", - "management.newrelic.metrics.export.event-type=", - "management.newrelic.metrics.export.meter-name-event-type-enabled=true") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(NewRelicConfig.class)); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=12345", + "management.newrelic.metrics.export.event-type=", + "management.newrelic.metrics.export.meter-name-event-type-enabled=true") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(NewRelicConfig.class)); } @Test void autoConfiguresWithAccountIdAndApiKey() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=12345") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(NewRelicConfig.class)); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=12345") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(NewRelicConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) - .doesNotHaveBean(NewRelicConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) + .doesNotHaveBean(NewRelicConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) - .doesNotHaveBean(NewRelicConfig.class)); + .withPropertyValues("management.newrelic.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(NewRelicMeterRegistry.class) + .doesNotHaveBean(NewRelicConfig.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=12345") - .run((context) -> assertThat(context).hasSingleBean(NewRelicConfig.class).hasBean("customConfig")); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=12345") + .run((context) -> assertThat(context).hasSingleBean(NewRelicConfig.class).hasBean("customConfig")); } @Test void allowsRegistryToBeCustomized() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=12345") - .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class) - .hasBean("customRegistry")); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=12345") + .run((context) -> assertThat(context).hasSingleBean(NewRelicMeterRegistry.class).hasBean("customRegistry")); } @Test void allowsClientProviderToBeCustomized() { this.contextRunner.withUserConfiguration(CustomClientProviderConfiguration.class) - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=12345") - .run((context) -> { - assertThat(context).hasSingleBean(NewRelicMeterRegistry.class); - assertThat(context.getBean(NewRelicMeterRegistry.class)) - .hasFieldOrPropertyWithValue("clientProvider", context.getBean("customClientProvider")); - }); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=12345") + .run((context) -> { + assertThat(context).hasSingleBean(NewRelicMeterRegistry.class); + assertThat(context.getBean(NewRelicMeterRegistry.class)).hasFieldOrPropertyWithValue("clientProvider", + context.getBean("customClientProvider")); + }); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner - .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", - "management.newrelic.metrics.export.account-id=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - NewRelicMeterRegistry registry = context.getBean(NewRelicMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.newrelic.metrics.export.api-key=abcde", + "management.newrelic.metrics.export.account-id=abcde") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + NewRelicMeterRegistry registry = context.getBean(NewRelicMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/otlp/OtlpMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/otlp/OtlpMetricsExportAutoConfigurationTests.java index 2cbb87dd0c..09752dd0c7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/otlp/OtlpMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/otlp/OtlpMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class OtlpMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OtlpMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(OtlpMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,35 +46,41 @@ class OtlpMetricsExportAutoConfigurationTests { @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(OtlpMeterRegistry.class).hasSingleBean(OtlpConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OtlpMeterRegistry.class) + .hasSingleBean(OtlpConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(OtlpMeterRegistry.class) - .doesNotHaveBean(OtlpConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(OtlpMeterRegistry.class) + .doesNotHaveBean(OtlpConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.otlp.metrics.export.enabled=false").run((context) -> assertThat(context) - .doesNotHaveBean(OtlpMeterRegistry.class).doesNotHaveBean(OtlpConfig.class)); + .withPropertyValues("management.otlp.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(OtlpMeterRegistry.class) + .doesNotHaveBean(OtlpConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(OtlpMeterRegistry.class).hasSingleBean(OtlpConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OtlpMeterRegistry.class) + .hasSingleBean(OtlpConfig.class) + .hasBean("customConfig")); } @Test void allowsRegistryToBeCustomized() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(OtlpMeterRegistry.class).hasSingleBean(OtlpConfig.class).hasBean("customRegistry")); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OtlpMeterRegistry.class) + .hasSingleBean(OtlpConfig.class) + .hasBean("customRegistry")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java index bde2db3c5e..74bc1ef458 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,7 @@ import static org.assertj.core.api.Assertions.assertThat; class PrometheusMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(PrometheusMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PrometheusMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -67,138 +67,148 @@ class PrometheusMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigCollectorRegistryAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) - .doesNotHaveBean(CollectorRegistry.class).doesNotHaveBean(PrometheusConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) + .doesNotHaveBean(CollectorRegistry.class) + .doesNotHaveBean(PrometheusConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.prometheus.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) - .doesNotHaveBean(CollectorRegistry.class).doesNotHaveBean(PrometheusConfig.class)); + .withPropertyValues("management.prometheus.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusMeterRegistry.class) + .doesNotHaveBean(CollectorRegistry.class) + .doesNotHaveBean(PrometheusConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasSingleBean(CollectorRegistry.class).hasSingleBean(PrometheusConfig.class) - .hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(CollectorRegistry.class) - .hasSingleBean(PrometheusConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class)); } @Test void allowsCustomCollectorRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomCollectorRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) - .hasBean("customCollectorRegistry").hasSingleBean(CollectorRegistry.class) - .hasSingleBean(PrometheusConfig.class)); + .run((context) -> assertThat(context).hasSingleBean(PrometheusMeterRegistry.class) + .hasBean("customCollectorRegistry") + .hasSingleBean(CollectorRegistry.class) + .hasSingleBean(PrometheusConfig.class)); } @Test void autoConfiguresExemplarSamplerIfSpanContextSupplierIsPresent() { this.contextRunner.withUserConfiguration(ExemplarsConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(SpanContextSupplier.class) - .hasSingleBean(ExemplarSampler.class).hasSingleBean(PrometheusMeterRegistry.class)); + .run((context) -> assertThat(context).hasSingleBean(SpanContextSupplier.class) + .hasSingleBean(ExemplarSampler.class) + .hasSingleBean(PrometheusMeterRegistry.class)); } @Test void exemplarSamplerIsNotAutoConfiguredIfSpanContextSupplierIsMissing() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class) - .doesNotHaveBean(ExemplarSampler.class).hasSingleBean(PrometheusMeterRegistry.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class) + .doesNotHaveBean(ExemplarSampler.class) + .hasSingleBean(PrometheusMeterRegistry.class)); } @Test void addsScrapeEndpointToManagementContext() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=prometheus") - .run((context) -> assertThat(context).hasSingleBean(PrometheusScrapeEndpoint.class)); + .withUserConfiguration(BaseConfiguration.class) + .withPropertyValues("management.endpoints.web.exposure.include=prometheus") + .run((context) -> assertThat(context).hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test void scrapeEndpointNotAddedToManagementContextWhenNotExposed() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); } @Test void scrapeEndpointCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include=prometheus") - .withPropertyValues("management.endpoint.prometheus.enabled=false") - .withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=prometheus") + .withPropertyValues("management.endpoint.prometheus.enabled=false") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusScrapeEndpoint.class)); } @Test void allowsCustomScrapeEndpointToBeUsed() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withUserConfiguration(CustomEndpointConfiguration.class).run((context) -> assertThat(context) - .hasBean("customEndpoint").hasSingleBean(PrometheusScrapeEndpoint.class)); + .withUserConfiguration(CustomEndpointConfiguration.class) + .run((context) -> assertThat(context).hasBean("customEndpoint") + .hasSingleBean(PrometheusScrapeEndpoint.class)); } @Test void pushGatewayIsNotConfiguredWhenEnabledFlagIsNotSet() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PrometheusPushGatewayManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PrometheusPushGatewayManager.class)); } @Test void withPushGatewayEnabled(CapturedOutput output) { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - assertThat(output).doesNotContain("Invalid PushGateway base url"); - hasGatewayURL(context, "http://localhost:9091/metrics/"); - }); + .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + assertThat(output).doesNotContain("Invalid PushGateway base url"); + hasGatewayURL(context, "http://localhost:9091/metrics/"); + }); } @Test void withPushGatewayNoBasicAuth() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true") - .withUserConfiguration(BaseConfiguration.class) - .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) - .isInstanceOf(DefaultHttpConnectionFactory.class))); + .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true") + .withUserConfiguration(BaseConfiguration.class) + .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) + .isInstanceOf(DefaultHttpConnectionFactory.class))); } @Test void withCustomPushGatewayURL() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true", - "management.prometheus.metrics.export.pushgateway.base-url=https://example.com:8080") - .withUserConfiguration(BaseConfiguration.class) - .run((context) -> hasGatewayURL(context, "https://example.com:8080/metrics/")); + .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true", + "management.prometheus.metrics.export.pushgateway.base-url=https://example.com:8080") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> hasGatewayURL(context, "https://example.com:8080/metrics/")); } @Test void withPushGatewayBasicAuth() { this.contextRunner.withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class)) - .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true", - "management.prometheus.metrics.export.pushgateway.username=admin", - "management.prometheus.metrics.export.pushgateway.password=secret") - .withUserConfiguration(BaseConfiguration.class) - .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) - .isInstanceOf(BasicAuthHttpConnectionFactory.class))); + .withPropertyValues("management.prometheus.metrics.export.pushgateway.enabled=true", + "management.prometheus.metrics.export.pushgateway.username=admin", + "management.prometheus.metrics.export.pushgateway.password=secret") + .withUserConfiguration(BaseConfiguration.class) + .run(hasHttpConnectionFactory((httpConnectionFactory) -> assertThat(httpConnectionFactory) + .isInstanceOf(BasicAuthHttpConnectionFactory.class))); } private void hasGatewayURL(AssertableApplicationContext context, String url) { @@ -210,7 +220,7 @@ class PrometheusMetricsExportAutoConfigurationTests { return (context) -> { PushGateway pushGateway = getPushGateway(context); httpConnectionFactory - .accept((HttpConnectionFactory) ReflectionTestUtils.getField(pushGateway, "connectionFactory")); + .accept((HttpConnectionFactory) ReflectionTestUtils.getField(pushGateway, "connectionFactory")); }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java index 66aa5920aa..4fa2176884 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/prometheus/PrometheusPropertiesConfigAdapterTests.java @@ -42,7 +42,7 @@ class PrometheusPropertiesConfigAdapterTests { PrometheusProperties properties = new PrometheusProperties(); properties.setHistogramFlavor(HistogramFlavor.VictoriaMetrics); assertThat(new PrometheusPropertiesConfigAdapter(properties).histogramFlavor()) - .isEqualTo(HistogramFlavor.VictoriaMetrics); + .isEqualTo(HistogramFlavor.VictoriaMetrics); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java index 675ad4e2a4..d3db91eacb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/signalfx/SignalFxMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class SignalFxMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SignalFxMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SignalFxMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,59 +47,64 @@ class SignalFxMetricsExportAutoConfigurationTests { @Test void failsWithoutAnAccessToken() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasFailed()); + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresWithAnAccessToken() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.signalfx.metrics.export.access-token=abcde") - .run((context) -> assertThat(context).hasSingleBean(SignalFxMeterRegistry.class) - .hasSingleBean(Clock.class).hasSingleBean(SignalFxConfig.class)); + .withPropertyValues("management.signalfx.metrics.export.access-token=abcde") + .run((context) -> assertThat(context).hasSingleBean(SignalFxMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(SignalFxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) - .doesNotHaveBean(SignalFxConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) + .doesNotHaveBean(SignalFxConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.signalfx.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) - .doesNotHaveBean(SignalFxConfig.class)); + .withPropertyValues("management.signalfx.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SignalFxMeterRegistry.class) + .doesNotHaveBean(SignalFxConfig.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withPropertyValues("management.signalfx.metrics.export.access-token=abcde") - .withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(SignalFxMeterRegistry.class).hasSingleBean(SignalFxConfig.class) - .hasBean("customConfig")); + .withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(SignalFxMeterRegistry.class) + .hasSingleBean(SignalFxConfig.class) + .hasBean("customConfig")); } @Test void allowsRegistryToBeCustomized() { this.contextRunner.withPropertyValues("management.signalfx.metrics.export.access-token=abcde") - .withUserConfiguration(CustomRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(SignalFxConfig.class) - .hasSingleBean(SignalFxMeterRegistry.class).hasBean("customRegistry")); + .withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(SignalFxConfig.class) + .hasSingleBean(SignalFxMeterRegistry.class) + .hasBean("customRegistry")); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withPropertyValues("management.signalfx.metrics.export.access-token=abcde") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - SignalFxMeterRegistry registry = context.getBean(SignalFxMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + SignalFxMeterRegistry registry = context.getBean(SignalFxMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java index 6ca17f61c1..6521cafe8d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimpleMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,40 +40,44 @@ import static org.mockito.Mockito.mock; class SimpleMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SimpleMetricsExportAutoConfiguration.class)); @Test void autoConfiguresConfigAndMeterRegistry() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(SimpleMeterRegistry.class).hasSingleBean(Clock.class).hasSingleBean(SimpleConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(SimpleMeterRegistry.class) + .hasSingleBean(Clock.class) + .hasSingleBean(SimpleConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) - .doesNotHaveBean(SimpleConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) + .doesNotHaveBean(SimpleConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.simple.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) - .doesNotHaveBean(SimpleConfig.class)); + .withPropertyValues("management.simple.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(SimpleMeterRegistry.class) + .doesNotHaveBean(SimpleConfig.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(SimpleConfig.class).hasBean("customConfig")); } @Test void backsOffEntirelyWithCustomMeterRegistry() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(MeterRegistry.class).hasBean("customRegistry").doesNotHaveBean(SimpleConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(MeterRegistry.class) + .hasBean("customRegistry") + .doesNotHaveBean(SimpleConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java index 9db4d27b3d..60aebf01e9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class StackdriverMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(StackdriverMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StackdriverMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -47,57 +47,60 @@ class StackdriverMetricsExportAutoConfigurationTests { @Test void failsWithoutAProjectId() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .run((context) -> assertThat(context).hasFailed()); + .run((context) -> assertThat(context).hasFailed()); } @Test void autoConfiguresConfigAndMeterRegistry() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.stackdriver.metrics.export.project-id=test-project") - .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) - .hasSingleBean(StackdriverConfig.class)); + .withPropertyValues("management.stackdriver.metrics.export.project-id=test-project") + .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) + .hasSingleBean(StackdriverConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) - .doesNotHaveBean(StackdriverConfig.class)); + .withPropertyValues("management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) + .doesNotHaveBean(StackdriverConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.stackdriver.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) - .doesNotHaveBean(StackdriverConfig.class)); + .withPropertyValues("management.stackdriver.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(StackdriverMeterRegistry.class) + .doesNotHaveBean(StackdriverConfig.class)); } @Test void allowsCustomConfigToBeUsed() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) - .hasSingleBean(StackdriverConfig.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) + .hasSingleBean(StackdriverConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.stackdriver.metrics.export.project-id=test-project") - .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) - .hasBean("customRegistry").hasSingleBean(StackdriverConfig.class)); + .withPropertyValues("management.stackdriver.metrics.export.project-id=test-project") + .run((context) -> assertThat(context).hasSingleBean(StackdriverMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(StackdriverConfig.class)); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.stackdriver.metrics.export.project-id=test-project").run((context) -> { - StackdriverMeterRegistry registry = context.getBean(StackdriverMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.stackdriver.metrics.export.project-id=test-project") + .run((context) -> { + StackdriverMeterRegistry registry = context.getBean(StackdriverMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java index 6018cbc91f..9b2f2fe964 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/stackdriver/StackdriverPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,7 @@ class StackdriverPropertiesConfigAdapterTests { StackdriverProperties properties = new StackdriverProperties(); properties.setResourceLabels(labels); assertThat(new StackdriverPropertiesConfigAdapter(properties).resourceLabels()) - .containsExactlyInAnyOrderEntriesOf(labels); + .containsExactlyInAnyOrderEntriesOf(labels); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java index d004803683..2786b326a8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class StatsdMetricsExportAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(StatsdMetricsExportAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StatsdMetricsExportAutoConfiguration.class)); @Test void backsOffWithoutAClock() { @@ -46,34 +46,39 @@ class StatsdMetricsExportAutoConfigurationTests { @Test void autoConfiguresItsConfigMeterRegistryAndMetrics() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class).hasSingleBean(StatsdConfig.class)); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) + .hasSingleBean(StatsdConfig.class)); } @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withPropertyValues("management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) - .doesNotHaveBean(StatsdConfig.class)); + .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) + .doesNotHaveBean(StatsdConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withPropertyValues("management.statsd.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) - .doesNotHaveBean(StatsdConfig.class)); + .run((context) -> assertThat(context).doesNotHaveBean(StatsdMeterRegistry.class) + .doesNotHaveBean(StatsdConfig.class)); } @Test void allowsCustomConfigToBeUsed() { - this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class).hasSingleBean(StatsdConfig.class).hasBean("customConfig")); + this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) + .hasSingleBean(StatsdConfig.class) + .hasBean("customConfig")); } @Test void allowsCustomRegistryToBeUsed() { - this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(StatsdMeterRegistry.class).hasBean("customRegistry").hasSingleBean(StatsdConfig.class)); + this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(StatsdMeterRegistry.class) + .hasBean("customRegistry") + .hasSingleBean(StatsdConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java index e6bce8be43..9eae3d00dc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/statsd/StatsdPropertiesConfigAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ class StatsdPropertiesConfigAdapterTests { StatsdProperties properties = new StatsdProperties(); properties.setMaxPacketLength(1234); assertThat(new StatsdPropertiesConfigAdapter(properties).maxPacketLength()) - .isEqualTo(properties.getMaxPacketLength()); + .isEqualTo(properties.getMaxPacketLength()); } @Test @@ -79,7 +79,7 @@ class StatsdPropertiesConfigAdapterTests { StatsdProperties properties = new StatsdProperties(); properties.setPollingFrequency(Duration.ofSeconds(1)); assertThat(new StatsdPropertiesConfigAdapter(properties).pollingFrequency()) - .isEqualTo(properties.getPollingFrequency()); + .isEqualTo(properties.getPollingFrequency()); } @Test @@ -94,7 +94,7 @@ class StatsdPropertiesConfigAdapterTests { StatsdProperties properties = new StatsdProperties(); properties.setPublishUnchangedMeters(false); assertThat(new StatsdPropertiesConfigAdapter(properties).publishUnchangedMeters()) - .isEqualTo(properties.isPublishUnchangedMeters()); + .isEqualTo(properties.isPublishUnchangedMeters()); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java index 1b8b098477..f9d6cf7ed5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/wavefront/WavefrontMetricsExportAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,35 +56,39 @@ class WavefrontMetricsExportAutoConfigurationTests { @Test void autoConfigurationCanBeDisabledWithDefaultsEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.wavefront.api-token=abcde", - "management.defaults.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) - .doesNotHaveBean(WavefrontConfig.class)); + .withPropertyValues("management.wavefront.api-token=abcde", + "management.defaults.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) + .doesNotHaveBean(WavefrontConfig.class)); } @Test void autoConfigurationCanBeDisabledWithSpecificEnabledProperty() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.wavefront.api-token=abcde", - "management.wavefront.metrics.export.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) - .doesNotHaveBean(WavefrontConfig.class)); + .withPropertyValues("management.wavefront.api-token=abcde", + "management.wavefront.metrics.export.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(WavefrontMeterRegistry.class) + .doesNotHaveBean(WavefrontConfig.class)); } @Test void allowsConfigToBeCustomized() { this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Clock.class) - .hasSingleBean(WavefrontMeterRegistry.class).hasSingleBean(WavefrontConfig.class) - .hasSingleBean(WavefrontSender.class).hasBean("customConfig")); + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(WavefrontMeterRegistry.class) + .hasSingleBean(WavefrontConfig.class) + .hasSingleBean(WavefrontSender.class) + .hasBean("customConfig")); } @Test void allowsRegistryToBeCustomized() { this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class) - .withPropertyValues("management.wavefront.api-token=abcde") - .run((context) -> assertThat(context).hasSingleBean(Clock.class).hasSingleBean(WavefrontConfig.class) - .hasSingleBean(WavefrontMeterRegistry.class).hasBean("customRegistry")); + .withPropertyValues("management.wavefront.api-token=abcde") + .run((context) -> assertThat(context).hasSingleBean(Clock.class) + .hasSingleBean(WavefrontConfig.class) + .hasSingleBean(WavefrontMeterRegistry.class) + .hasBean("customRegistry")); } @Test @@ -94,41 +98,53 @@ class WavefrontMetricsExportAutoConfigurationTests { builder.shard("super-shard"); builder.customTags(Map.of("custom-key", "custom-val")); this.contextRunner.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class).withBean(ApplicationTags.class, builder::build) - .run((context) -> { - WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); - registry.counter("my.counter", "env", "qa"); - assertThat(registry.find("my.counter").tags("env", "qa").tags("application", "super-application") - .tags("service", "super-service").tags("cluster", "super-cluster") - .tags("shard", "super-shard").tags("custom-key", "custom-val").counter()).isNotNull(); - }); + .withUserConfiguration(BaseConfiguration.class) + .withBean(ApplicationTags.class, builder::build) + .run((context) -> { + WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); + registry.counter("my.counter", "env", "qa"); + assertThat(registry.find("my.counter") + .tags("env", "qa") + .tags("application", "super-application") + .tags("service", "super-service") + .tags("cluster", "super-cluster") + .tags("shard", "super-shard") + .tags("custom-key", "custom-val") + .counter()).isNotNull(); + }); } @Test void exportsApplicationTagsInWavefrontRegistryWhenInProperties() { this.contextRunner.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class)) - .withPropertyValues("management.wavefront.application.service-name=super-service", - "management.wavefront.application.name=super-application", - "management.wavefront.application.cluster-name=super-cluster", - "management.wavefront.application.shard-name=super-shard") - .withUserConfiguration(BaseConfiguration.class).run((context) -> { - WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); - registry.counter("my.counter", "env", "qa"); - assertThat(registry.find("my.counter").tags("env", "qa").tags("application", "super-application") - .tags("service", "super-service").tags("cluster", "super-cluster") - .tags("shard", "super-shard").counter()).isNotNull(); - }); + .withPropertyValues("management.wavefront.application.service-name=super-service", + "management.wavefront.application.name=super-application", + "management.wavefront.application.cluster-name=super-cluster", + "management.wavefront.application.shard-name=super-shard") + .withUserConfiguration(BaseConfiguration.class) + .run((context) -> { + WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); + registry.counter("my.counter", "env", "qa"); + assertThat(registry.find("my.counter") + .tags("env", "qa") + .tags("application", "super-application") + .tags("service", "super-service") + .tags("cluster", "super-cluster") + .tags("shard", "super-shard") + .counter()).isNotNull(); + }); } @Test void stopsMeterRegistryWhenContextIsClosed() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("management.wavefront.api-token=abcde").run((context) -> { - WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); - assertThat(registry.isClosed()).isFalse(); - context.close(); - assertThat(registry.isClosed()).isTrue(); - }); + .withPropertyValues("management.wavefront.api-token=abcde") + .run((context) -> { + WavefrontMeterRegistry registry = context.getBean(WavefrontMeterRegistry.class); + assertThat(registry.isClosed()).isFalse(); + context.close(); + assertThat(registry.isClosed()).isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java index 8d44c8f133..ff258d7366 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/integration/IntegrationMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -36,9 +36,10 @@ import static org.assertj.core.api.Assertions.assertThat; class IntegrationMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class, - IntegrationGraphEndpointAutoConfiguration.class, IntegrationMetricsAutoConfiguration.class)) - .with(MetricsRun.simple()).withPropertyValues("management.metrics.tags.someTag=someValue"); + .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class, + IntegrationGraphEndpointAutoConfiguration.class, IntegrationMetricsAutoConfiguration.class)) + .with(MetricsRun.simple()) + .withPropertyValues("management.metrics.tags.someTag=someValue"); @Test void integrationMetersAreInstrumented() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java index 12e21aecf5..a20bd8ebd7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jdbc/DataSourcePoolMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,146 +55,157 @@ import static org.assertj.core.api.Assertions.assertThat; class DataSourcePoolMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true").with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(DataSourcePoolMetricsAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(DataSourcePoolMetricsAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void autoConfiguredDataSourceIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { - context.getBean(DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jdbc.connections.max").tags("name", "dataSource").meter(); - }); + .run((context) -> { + context.getBean(DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("jdbc.connections.max").tags("name", "dataSource").meter(); + }); } @Test void dataSourceInstrumentationCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("management.metrics.enable.jdbc=false").run((context) -> { - context.getBean(DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("jdbc.connections.max").tags("name", "dataSource").meter()).isNull(); - }); + .withPropertyValues("management.metrics.enable.jdbc=false") + .run((context) -> { + context.getBean(DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("jdbc.connections.max").tags("name", "dataSource").meter()).isNull(); + }); } @Test void allDataSourcesCanBeInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withUserConfiguration(TwoDataSourcesConfiguration.class).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); - context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jdbc.connections.max").tags("name", "first").meter(); - registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); - }); + .withUserConfiguration(TwoDataSourcesConfiguration.class) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); + context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("jdbc.connections.max").tags("name", "first").meter(); + registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); + }); } @Test void allDataSourcesCanBeInstrumentedWithLazyInitialization() { - this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).withInitializer( - (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) - .withUserConfiguration(TwoDataSourcesConfiguration.class).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); - context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("jdbc.connections.max").tags("name", "first").meter(); - registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); - }); + this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withInitializer( + (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) + .withUserConfiguration(TwoDataSourcesConfiguration.class) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection().getMetaData(); + context.getBean("secondOne", DataSource.class).getConnection().getMetaData(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("jdbc.connections.max").tags("name", "first").meter(); + registry.get("jdbc.connections.max").tags("name", "secondOne").meter(); + }); } @Test void autoConfiguredHikariDataSourceIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").meter(); - }); + .run((context) -> { + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").meter(); + }); } @Test void autoConfiguredHikariDataSourceIsInstrumentedWhenUsingDataSourceInitialization() { - this.contextRunner.withPropertyValues("spring.sql.init.schema:db/create-custom-schema.sql").withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, SqlInitializationAutoConfiguration.class)) - .run((context) -> { - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").meter(); - }); + this.contextRunner.withPropertyValues("spring.sql.init.schema:db/create-custom-schema.sql") + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, SqlInitializationAutoConfiguration.class)) + .run((context) -> { + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").meter(); + }); } @Test void hikariCanBeInstrumentedAfterThePoolHasBeenSealed() { this.contextRunner.withUserConfiguration(HikariSealingConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hikaricp.connections").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hikaricp.connections").meter()).isNotNull(); + }); } @Test void hikariDataSourceInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.hikaricp=false") - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean(DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hikaricp.connections").meter()).isNull(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean(DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hikaricp.connections").meter()).isNull(); + }); } @Test void allHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(TwoHikariDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection(); - context.getBean("secondOne", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection(); + context.getBean("secondOne", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); + }); } @Test void someHikariDataSourcesCanBeInstrumented() { this.contextRunner.withUserConfiguration(MixedDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection(); - context.getBean("secondOne", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) - .containsExactly(Tag.of("pool", "firstDataSource")); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection(); + context.getBean("secondOne", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) + .containsExactly(Tag.of("pool", "firstDataSource")); + }); } @Test void allHikariDataSourcesCanBeInstrumentedWhenUsingLazyInitialization() { this.contextRunner.withUserConfiguration(TwoHikariDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withInitializer((context) -> context - .addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) - .run((context) -> { - context.getBean("firstDataSource", DataSource.class).getConnection(); - context.getBean("secondOne", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withInitializer( + (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) + .run((context) -> { + context.getBean("firstDataSource", DataSource.class).getConnection(); + context.getBean("secondOne", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); + }); } @Test void hikariProxiedDataSourceCanBeInstrumented() { this.contextRunner.withUserConfiguration(ProxiedHikariDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)).run((context) -> { - context.getBean("proxiedDataSource", DataSource.class).getConnection(); - context.getBean("delegateDataSource", DataSource.class).getConnection(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); - registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .run((context) -> { + context.getBean("proxiedDataSource", DataSource.class).getConnection(); + context.getBean("delegateDataSource", DataSource.class).getConnection(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hikaricp.connections").tags("pool", "firstDataSource").meter(); + registry.get("hikaricp.connections").tags("pool", "secondOne").meter(); + }); } @Test @@ -204,7 +215,7 @@ class DataSourcePoolMetricsAutoConfigurationTests { context.getBean("hikariDataSource", DataSource.class).getConnection(); MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.get("hikaricp.connections").meter().getId().getTags()) - .containsExactly(Tag.of("pool", "hikariDataSource")); + .containsExactly(Tag.of("pool", "hikariDataSource")); }); } @@ -300,8 +311,10 @@ class DataSourcePoolMetricsAutoConfigurationTests { private HikariDataSource createHikariDataSource(String poolName) { String url = "jdbc:hsqldb:mem:test-" + UUID.randomUUID(); - HikariDataSource hikariDataSource = DataSourceBuilder.create().url(url).type(HikariDataSource.class) - .build(); + HikariDataSource hikariDataSource = DataSourceBuilder.create() + .url(url) + .type(HikariDataSource.class) + .build(); hikariDataSource.setPoolName(poolName); return hikariDataSource; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java index f78b9f69d0..a7b1a6326e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/jersey/JerseyServerMetricsAutoConfigurationTests.java @@ -59,14 +59,16 @@ import static org.assertj.core.api.Assertions.assertThat; class JerseyServerMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(JerseyServerMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseyServerMetricsAutoConfiguration.class)); private final WebApplicationContextRunner webContextRunner = new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new).withConfiguration( - AutoConfigurations.of(JerseyAutoConfiguration.class, JerseyServerMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class, - ObservationAutoConfiguration.class, MetricsAutoConfiguration.class)) - .withUserConfiguration(ResourceConfiguration.class).withPropertyValues("server.port:0"); + AnnotationConfigServletWebServerApplicationContext::new) + .withConfiguration( + AutoConfigurations.of(JerseyAutoConfiguration.class, JerseyServerMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class, + ObservationAutoConfiguration.class, MetricsAutoConfiguration.class)) + .withUserConfiguration(ResourceConfiguration.class) + .withPropertyValues("server.port:0"); @Test void shouldOnlyBeActiveInWebApplicationContext() { @@ -76,13 +78,13 @@ class JerseyServerMetricsAutoConfigurationTests { @Test void shouldProvideAllNecessaryBeans() { this.webContextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultJerseyTagsProvider.class) - .hasSingleBean(ResourceConfigCustomizer.class)); + .hasSingleBean(ResourceConfigCustomizer.class)); } @Test void shouldHonorExistingTagProvider() { this.webContextRunner.withUserConfiguration(CustomJerseyTagsProviderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CustomJerseyTagsProvider.class)); + .run((context) -> assertThat(context).hasSingleBean(CustomJerseyTagsProvider.class)); } @Test @@ -98,17 +100,18 @@ class JerseyServerMetricsAutoConfigurationTests { @Test void noHttpRequestsTimedWhenJerseyInstrumentationMissingFromClasspath() { this.webContextRunner.withClassLoader(new FilteredClassLoader(MetricsApplicationEventListener.class)) - .run((context) -> { - doRequest(context); + .run((context) -> { + doRequest(context); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("http.server.requests").timer()).isNull(); - }); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("http.server.requests").timer()).isNull(); + }); } private static void doRequest(AssertableWebApplicationContext context) { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); + .getWebServer() + .getPort(); RestTemplate restTemplate = new RestTemplate(); restTemplate.getForEntity(URI.create("http://localhost:" + port + "/users/3"), String.class); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java index f0382a6606..7c3d870c3b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/mongo/MongoMetricsAutoConfigurationTests.java @@ -52,119 +52,124 @@ import static org.mockito.Mockito.mock; class MongoMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoMetricsAutoConfiguration.class)); @Test void whenThereIsAMeterRegistryThenMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(MongoMetricsCommandListener.class); - assertThat(getActualMongoClientSettingsUsedToConstructClient(context)) - .extracting(MongoClientSettings::getCommandListeners).asList() - .containsExactly(context.getBean(MongoMetricsCommandListener.class)); - assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) - .isInstanceOf(DefaultMongoCommandTagsProvider.class); - }); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(MongoMetricsCommandListener.class); + assertThat(getActualMongoClientSettingsUsedToConstructClient(context)) + .extracting(MongoClientSettings::getCommandListeners) + .asList() + .containsExactly(context.getBean(MongoMetricsCommandListener.class)); + assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) + .isInstanceOf(DefaultMongoCommandTagsProvider.class); + }); } @Test void whenThereIsAMeterRegistryThenMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(MongoMetricsConnectionPoolListener.class); - assertThat(getConnectionPoolListenersFromClient(context)) - .containsExactly(context.getBean(MongoMetricsConnectionPoolListener.class)); - assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) - .isInstanceOf(DefaultMongoConnectionPoolTagsProvider.class); - }); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(MongoMetricsConnectionPoolListener.class); + assertThat(getConnectionPoolListenersFromClient(context)) + .containsExactly(context.getBean(MongoMetricsConnectionPoolListener.class)); + assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) + .isInstanceOf(DefaultMongoConnectionPoolTagsProvider.class); + }); } @Test void whenThereIsNoMeterRegistryThenNoMetricsCommandListenerIsAdded() { this.contextRunner.withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .run(assertThatMetricsCommandListenerNotAdded()); + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenThereIsNoMeterRegistryThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } @Test void whenThereIsACustomMetricsCommandTagsProviderItIsUsed() { final MongoCommandTagsProvider customTagsProvider = mock(MongoCommandTagsProvider.class); this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withBean("customMongoCommandTagsProvider", MongoCommandTagsProvider.class, () -> customTagsProvider) - .run((context) -> assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) - .isSameAs(customTagsProvider)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withBean("customMongoCommandTagsProvider", MongoCommandTagsProvider.class, () -> customTagsProvider) + .run((context) -> assertThat(getMongoCommandTagsProviderUsedToConstructListener(context)) + .isSameAs(customTagsProvider)); } @Test void whenThereIsACustomMetricsConnectionPoolTagsProviderItIsUsed() { final MongoConnectionPoolTagsProvider customTagsProvider = mock(MongoConnectionPoolTagsProvider.class); this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withBean("customMongoConnectionPoolTagsProvider", MongoConnectionPoolTagsProvider.class, - () -> customTagsProvider) - .run((context) -> assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) - .isSameAs(customTagsProvider)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withBean("customMongoConnectionPoolTagsProvider", MongoConnectionPoolTagsProvider.class, + () -> customTagsProvider) + .run((context) -> assertThat(getMongoConnectionPoolTagsProviderUsedToConstructListener(context)) + .isSameAs(customTagsProvider)); } @Test void whenThereIsNoMongoClientSettingsOnClasspathThenNoMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) - .run(assertThatMetricsCommandListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenThereIsNoMongoClientSettingsOnClasspathThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoClientSettings.class)) + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } @Test void whenThereIsNoMongoMetricsCommandListenerOnClasspathThenNoMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoMetricsCommandListener.class)) - .run(assertThatMetricsCommandListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoMetricsCommandListener.class)) + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenThereIsNoMongoMetricsConnectionPoolListenerOnClasspathThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(MongoMetricsConnectionPoolListener.class)) - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(MongoMetricsConnectionPoolListener.class)) + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } @Test void whenMetricsCommandListenerEnabledPropertyFalseThenNoMetricsCommandListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withPropertyValues("management.metrics.mongo.command.enabled:false") - .run(assertThatMetricsCommandListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withPropertyValues("management.metrics.mongo.command.enabled:false") + .run(assertThatMetricsCommandListenerNotAdded()); } @Test void whenMetricsConnectionPoolListenerEnabledPropertyFalseThenNoMetricsConnectionPoolListenerIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) - .withPropertyValues("management.metrics.mongo.connectionpool.enabled:false") - .run(assertThatMetricsConnectionPoolListenerNotAdded()); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)) + .withPropertyValues("management.metrics.mongo.connectionpool.enabled:false") + .run(assertThatMetricsConnectionPoolListenerNotAdded()); } private ContextConsumer assertThatMetricsCommandListenerNotAdded() { return (context) -> { assertThat(context).doesNotHaveBean(MongoMetricsCommandListener.class); assertThat(getActualMongoClientSettingsUsedToConstructClient(context)) - .extracting(MongoClientSettings::getCommandListeners).asList().isEmpty(); + .extracting(MongoClientSettings::getCommandListeners) + .asList() + .isEmpty(); }; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java index d3013c38c3..ddad799755 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/orm/jpa/HibernateMetricsAutoConfigurationTests.java @@ -63,87 +63,92 @@ import static org.mockito.Mockito.mock; class HibernateMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, HibernateMetricsAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, + HibernateMetricsAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void autoConfiguredEntityManagerFactoryWithStatsIsInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); - }); + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); + }); } @Test void autoConfiguredEntityManagerFactoryWithoutStatsIsNotInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:false") - .run((context) -> { - context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + .run((context) -> { + context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void entityManagerFactoryInstrumentationCanBeDisabled() { - this.contextRunner.withPropertyValues("management.metrics.enable.hibernate=false", - "spring.jpa.properties.hibernate.generate_statistics:true").run((context) -> { - context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + this.contextRunner + .withPropertyValues("management.metrics.enable.hibernate=false", + "spring.jpa.properties.hibernate.generate_statistics:true") + .run((context) -> { + context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void allEntityManagerFactoriesCanBeInstrumented() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") - .withUserConfiguration(TwoEntityManagerFactoriesConfiguration.class).run((context) -> { - context.getBean("firstEntityManagerFactory", EntityManagerFactory.class) - .unwrap(SessionFactory.class); - context.getBean("secondOne", EntityManagerFactory.class).unwrap(SessionFactory.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements").tags("entityManagerFactory", "first").meter(); - registry.get("hibernate.statements").tags("entityManagerFactory", "secondOne").meter(); - }); + .withUserConfiguration(TwoEntityManagerFactoriesConfiguration.class) + .run((context) -> { + context.getBean("firstEntityManagerFactory", EntityManagerFactory.class).unwrap(SessionFactory.class); + context.getBean("secondOne", EntityManagerFactory.class).unwrap(SessionFactory.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hibernate.statements").tags("entityManagerFactory", "first").meter(); + registry.get("hibernate.statements").tags("entityManagerFactory", "secondOne").meter(); + }); } @Test void entityManagerFactoryInstrumentationIsDisabledIfNotHibernateSessionFactory() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true") - .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { - // ensure EntityManagerFactory is not a Hibernate SessionFactory - assertThatThrownBy(() -> context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class)) - .isInstanceOf(PersistenceException.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class) + .run((context) -> { + // ensure EntityManagerFactory is not a Hibernate SessionFactory + assertThatThrownBy(() -> context.getBean(EntityManagerFactory.class).unwrap(SessionFactory.class)) + .isInstanceOf(PersistenceException.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void entityManagerFactoryInstrumentationIsDisabledIfHibernateIsNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader(SessionFactory.class)) - .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean(HibernateMetricsAutoConfiguration.class); - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("hibernate.statements").meter()).isNull(); - }); + .withUserConfiguration(NonHibernateEntityManagerFactoryConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(HibernateMetricsAutoConfiguration.class); + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("hibernate.statements").meter()).isNull(); + }); } @Test void entityManagerFactoryInstrumentationDoesNotDeadlockWithDeferredInitialization() { - this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true", - "spring.sql.init.schema-locations:city-schema.sql", "spring.sql.init.data-locations=city-data.sql") - .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) - .withBean(EntityManagerFactoryBuilderCustomizer.class, - () -> (builder) -> builder.setBootstrapExecutor(new SimpleAsyncTaskExecutor())) - .run((context) -> { - JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); - assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) from CITY", Integer.class)).isOne(); - MeterRegistry registry = context.getBean(MeterRegistry.class); - registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); - }); + this.contextRunner + .withPropertyValues("spring.jpa.properties.hibernate.generate_statistics:true", + "spring.sql.init.schema-locations:city-schema.sql", "spring.sql.init.data-locations=city-data.sql") + .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) + .withBean(EntityManagerFactoryBuilderCustomizer.class, + () -> (builder) -> builder.setBootstrapExecutor(new SimpleAsyncTaskExecutor())) + .run((context) -> { + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) from CITY", Integer.class)).isOne(); + MeterRegistry registry = context.getBean(MeterRegistry.class); + registry.get("hibernate.statements").tags("entityManagerFactory", "entityManagerFactory").meter(); + }); } @Configuration(proxyBeanMethods = false) @@ -185,7 +190,8 @@ class HibernateMetricsAutoConfigurationTests { Map jpaProperties = new HashMap<>(); jpaProperties.put("hibernate.generate_statistics", "true"); return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), jpaProperties, null).dataSource(ds) - .packages(PACKAGE_CLASSES).build(); + .packages(PACKAGE_CLASSES) + .build(); } } @@ -198,7 +204,7 @@ class HibernateMetricsAutoConfigurationTests { EntityManagerFactory mockedFactory = mock(EntityManagerFactory.class); // enforces JPA contract given(mockedFactory.unwrap(ArgumentMatchers.>any())) - .willThrow(PersistenceException.class); + .willThrow(PersistenceException.class); return mockedFactory; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java index 41137e5b98..de32507ba3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,9 +52,10 @@ import static org.assertj.core.api.Assertions.assertThat; class ConnectionPoolMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.r2dbc.generate-unique-name=true").with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(ConnectionPoolMetricsAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withPropertyValues("spring.r2dbc.generate-unique-name=true") + .with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(ConnectionPoolMetricsAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void autoConfiguredDataSourceIsInstrumented() { @@ -67,21 +68,23 @@ class ConnectionPoolMetricsAutoConfigurationTests { @Test void autoConfiguredDataSourceExposedAsConnectionFactoryTypeIsInstrumented() { this.contextRunner - .withPropertyValues( - "spring.r2dbc.url:r2dbc:pool:h2:mem:///name?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("r2dbc.pool.acquired").gauges()).hasSize(1); - }); + .withPropertyValues( + "spring.r2dbc.url:r2dbc:pool:h2:mem:///name?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("r2dbc.pool.acquired").gauges()).hasSize(1); + }); } @Test void connectionPoolInstrumentationCanBeDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withPropertyValues("management.metrics.enable.r2dbc=false").run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("r2dbc.pool.acquired").gauge()).isNull(); - }); + .withPropertyValues("management.metrics.enable.r2dbc=false") + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("r2dbc.pool.acquired").gauge()).isNull(); + }); } @Test @@ -89,7 +92,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { this.contextRunner.withUserConfiguration(ConnectionFactoryConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId) - .extracting((id) -> id.getTag("name")).containsExactly("testConnectionPool"); + .extracting((id) -> id.getTag("name")) + .containsExactly("testConnectionPool"); }); } @@ -98,7 +102,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { this.contextRunner.withUserConfiguration(WrappedConnectionPoolConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId) - .extracting((id) -> id.getTag("name")).containsExactly("wrappedConnectionPool"); + .extracting((id) -> id.getTag("name")) + .containsExactly("wrappedConnectionPool"); }); } @@ -107,7 +112,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { this.contextRunner.withUserConfiguration(TwoConnectionPoolsConfiguration.class).run((context) -> { MeterRegistry registry = context.getBean(MeterRegistry.class); assertThat(registry.find("r2dbc.pool.acquired").gauges()).extracting(Meter::getId) - .extracting((id) -> id.getTag("name")).containsExactlyInAnyOrder("firstPool", "secondPool"); + .extracting((id) -> id.getTag("name")) + .containsExactlyInAnyOrder("firstPool", "secondPool"); }); } @@ -128,7 +134,8 @@ class ConnectionPoolMetricsAutoConfigurationTests { ConnectionFactory testConnectionPool() { return new ConnectionPool( ConnectionPoolConfiguration.builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa", - "", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))).build()); + "", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))) + .build()); } } @@ -138,12 +145,10 @@ class ConnectionPoolMetricsAutoConfigurationTests { @Bean ConnectionFactory wrappedConnectionPool() { - return new Wrapper( - new ConnectionPool( - ConnectionPoolConfiguration - .builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa", "", - Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))) - .build())); + return new Wrapper(new ConnectionPool( + ConnectionPoolConfiguration.builder(H2ConnectionFactory.inMemory("db-" + UUID.randomUUID(), "sa", + "", Collections.singletonMap(H2ConnectionOption.DB_CLOSE_DELAY, "-1"))) + .build())); } static class Wrapper implements ConnectionFactory, Wrapped { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java index 29a81195b8..c2479f3fbd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/redis/LettuceMetricsAutoConfigurationTests.java @@ -39,44 +39,45 @@ import static org.assertj.core.api.Assertions.assertThat; class LettuceMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LettuceMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LettuceMetricsAutoConfiguration.class)); @Test void whenThereIsAMeterRegistryThenCommandLatencyRecorderIsAdded() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { - ClientResources clientResources = context.getBean(LettuceConnectionFactory.class) - .getClientResources(); - assertThat(clientResources.commandLatencyRecorder()) - .isInstanceOf(MicrometerCommandLatencyRecorder.class); - }); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run((context) -> { + ClientResources clientResources = context.getBean(LettuceConnectionFactory.class).getClientResources(); + assertThat(clientResources.commandLatencyRecorder()) + .isInstanceOf(MicrometerCommandLatencyRecorder.class); + }); } @Test void autoConfiguredMicrometerOptionsUsesLettucesDefaults() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { - MicrometerOptions micrometerOptions = context.getBean(MicrometerOptions.class); - assertThat(micrometerOptions.isEnabled()).isTrue(); - assertThat(micrometerOptions.isHistogram()).isFalse(); - assertThat(micrometerOptions.localDistinction()).isFalse(); - assertThat(micrometerOptions.maxLatency()).isEqualTo(MicrometerOptions.DEFAULT_MAX_LATENCY); - assertThat(micrometerOptions.minLatency()).isEqualTo(MicrometerOptions.DEFAULT_MIN_LATENCY); - }); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run((context) -> { + MicrometerOptions micrometerOptions = context.getBean(MicrometerOptions.class); + assertThat(micrometerOptions.isEnabled()).isTrue(); + assertThat(micrometerOptions.isHistogram()).isFalse(); + assertThat(micrometerOptions.localDistinction()).isFalse(); + assertThat(micrometerOptions.maxLatency()).isEqualTo(MicrometerOptions.DEFAULT_MAX_LATENCY); + assertThat(micrometerOptions.minLatency()).isEqualTo(MicrometerOptions.DEFAULT_MIN_LATENCY); + }); } @Test void whenUserDefinesAMicrometerOptionsBeanThenCommandLatencyRecorderUsesIt() { this.contextRunner.with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withUserConfiguration(CustomMicrometerOptionsConfiguration.class).run((context) -> { - ClientResources clientResources = context.getBean(LettuceConnectionFactory.class) - .getClientResources(); - assertThat(clientResources.commandLatencyRecorder()) - .isInstanceOf(MicrometerCommandLatencyRecorder.class); - assertThat(clientResources.commandLatencyRecorder()).hasFieldOrPropertyWithValue("options", - context.getBean("customMicrometerOptions")); - }); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .withUserConfiguration(CustomMicrometerOptionsConfiguration.class) + .run((context) -> { + ClientResources clientResources = context.getBean(LettuceConnectionFactory.class).getClientResources(); + assertThat(clientResources.commandLatencyRecorder()) + .isInstanceOf(MicrometerCommandLatencyRecorder.class); + assertThat(clientResources.commandLatencyRecorder()).hasFieldOrPropertyWithValue("options", + context.getBean("customMicrometerOptions")); + }); } @Test @@ -84,7 +85,7 @@ class LettuceMetricsAutoConfigurationTests { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { ClientResources clientResources = context.getBean(LettuceConnectionFactory.class).getClientResources(); assertThat(clientResources.commandLatencyRecorder()) - .isNotInstanceOf(MicrometerCommandLatencyRecorder.class); + .isNotInstanceOf(MicrometerCommandLatencyRecorder.class); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java index dae7409542..f68265f387 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/startup/StartupTimeMetricsListenerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class StartupTimeMetricsListenerAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(StartupTimeMetricsListenerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StartupTimeMetricsListenerAutoConfiguration.class)); @Test void startupTimeMetricsAreRecorded() { @@ -65,25 +65,27 @@ class StartupTimeMetricsListenerAutoConfigurationTests { @Test void startupTimeMetricsCanBeDisabled() { - this.contextRunner.withPropertyValues("management.metrics.enable.application.started.time:false", - "management.metrics.enable.application.ready.time:false").run((context) -> { - context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, - context.getSourceApplicationContext(), Duration.ofMillis(2500))); - context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null, - context.getSourceApplicationContext(), Duration.ofMillis(3000))); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("application.started.time").timeGauge()).isNull(); - assertThat(registry.find("application.ready.time").timeGauge()).isNull(); - }); + this.contextRunner + .withPropertyValues("management.metrics.enable.application.started.time:false", + "management.metrics.enable.application.ready.time:false") + .run((context) -> { + context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null, + context.getSourceApplicationContext(), Duration.ofMillis(2500))); + context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null, + context.getSourceApplicationContext(), Duration.ofMillis(3000))); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("application.started.time").timeGauge()).isNull(); + assertThat(registry.find("application.ready.time").timeGauge()).isNull(); + }); } @Test void customStartupTimeMetricsAreRespected() { this.contextRunner - .withBean("customStartupTimeMetrics", StartupTimeMetricsListener.class, - () -> mock(StartupTimeMetricsListener.class)) - .run((context) -> assertThat(context).hasSingleBean(StartupTimeMetricsListener.class) - .hasBean("customStartupTimeMetrics")); + .withBean("customStartupTimeMetrics", StartupTimeMetricsListener.class, + () -> mock(StartupTimeMetricsListener.class)) + .run((context) -> assertThat(context).hasSingleBean(StartupTimeMetricsListener.class) + .hasBean("customStartupTimeMetrics")); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java index 53093101b1..35087e1e40 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -48,30 +48,32 @@ import static org.mockito.Mockito.mock; class TaskExecutorMetricsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(TaskExecutorMetricsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TaskExecutorMetricsAutoConfiguration.class)); @Test void taskExecutorUsingAutoConfigurationIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)) - .run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement().satisfies( + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies( (meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("applicationTaskExecutor")); - assertThatExceptionOfType(MeterNotFoundException.class) - .isThrownBy(() -> registry.get("executor").timer()); - }); + assertThatExceptionOfType(MeterNotFoundException.class) + .isThrownBy(() -> registry.get("executor").timer()); + }); } @Test void taskExecutorsWithCustomNamesAreInstrumented() { this.contextRunner.withBean("firstTaskExecutor", Executor.class, ThreadPoolTaskExecutor::new) - .withBean("customName", ThreadPoolTaskExecutor.class, ThreadPoolTaskExecutor::new).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).map((meter) -> meter.getId().getTag("name")) - .containsExactlyInAnyOrder("firstTaskExecutor", "customName"); - }); + .withBean("customName", ThreadPoolTaskExecutor.class, ThreadPoolTaskExecutor::new) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).map((meter) -> meter.getId().getTag("name")) + .containsExactlyInAnyOrder("firstTaskExecutor", "customName"); + }); } @Test @@ -79,46 +81,51 @@ class TaskExecutorMetricsAutoConfigurationTests { ThreadPoolTaskExecutor unavailableTaskExecutor = mock(ThreadPoolTaskExecutor.class); given(unavailableTaskExecutor.getThreadPoolExecutor()).willThrow(new IllegalStateException("Test")); this.contextRunner.withBean("firstTaskExecutor", ThreadPoolTaskExecutor.class, ThreadPoolTaskExecutor::new) - .withBean("customName", ThreadPoolTaskExecutor.class, () -> unavailableTaskExecutor).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement().satisfies( - (meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskExecutor")); - }); + .withBean("customName", ThreadPoolTaskExecutor.class, () -> unavailableTaskExecutor) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskExecutor")); + }); } @Test void taskExecutorInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.executor=false") - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("executor.completed").tags("name", "applicationTaskExecutor") - .functionCounter()).isNull(); - }); + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat( + registry.find("executor.completed").tags("name", "applicationTaskExecutor").functionCounter()) + .isNull(); + }); } @Test void taskSchedulerUsingAutoConfigurationIsInstrumented() { this.contextRunner.withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withUserConfiguration(SchedulingTestConfiguration.class).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement() - .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("taskScheduler")); - assertThatExceptionOfType(MeterNotFoundException.class) - .isThrownBy(() -> registry.get("executor").timer()); - }); + .withUserConfiguration(SchedulingTestConfiguration.class) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("taskScheduler")); + assertThatExceptionOfType(MeterNotFoundException.class) + .isThrownBy(() -> registry.get("executor").timer()); + }); } @Test void taskSchedulersWithCustomNamesAreInstrumented() { this.contextRunner.withBean("firstTaskScheduler", Executor.class, ThreadPoolTaskScheduler::new) - .withBean("customName", ThreadPoolTaskScheduler.class, ThreadPoolTaskScheduler::new).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).map((meter) -> meter.getId().getTag("name")) - .containsExactlyInAnyOrder("firstTaskScheduler", "customName"); - }); + .withBean("customName", ThreadPoolTaskScheduler.class, ThreadPoolTaskScheduler::new) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).map((meter) -> meter.getId().getTag("name")) + .containsExactlyInAnyOrder("firstTaskScheduler", "customName"); + }); } @Test @@ -126,23 +133,25 @@ class TaskExecutorMetricsAutoConfigurationTests { ThreadPoolTaskScheduler unavailableTaskExecutor = mock(ThreadPoolTaskScheduler.class); given(unavailableTaskExecutor.getScheduledThreadPoolExecutor()).willThrow(new IllegalStateException("Test")); this.contextRunner.withBean("firstTaskScheduler", ThreadPoolTaskScheduler.class, ThreadPoolTaskScheduler::new) - .withBean("customName", ThreadPoolTaskScheduler.class, () -> unavailableTaskExecutor).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - Collection meters = registry.get("executor.completed").functionCounters(); - assertThat(meters).singleElement().satisfies( - (meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskScheduler")); - }); + .withBean("customName", ThreadPoolTaskScheduler.class, () -> unavailableTaskExecutor) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + Collection meters = registry.get("executor.completed").functionCounters(); + assertThat(meters).singleElement() + .satisfies((meter) -> assertThat(meter.getId().getTag("name")).isEqualTo("firstTaskScheduler")); + }); } @Test void taskSchedulerInstrumentationCanBeDisabled() { this.contextRunner.withPropertyValues("management.metrics.enable.executor=false") - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withUserConfiguration(SchedulingTestConfiguration.class).run((context) -> { - MeterRegistry registry = context.getBean(MeterRegistry.class); - assertThat(registry.find("executor.completed").tags("name", "taskScheduler").functionCounter()) - .isNull(); - }); + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) + .withUserConfiguration(SchedulingTestConfiguration.class) + .run((context) -> { + MeterRegistry registry = context.getBean(MeterRegistry.class); + assertThat(registry.find("executor.completed").tags("name", "taskScheduler").functionCounter()) + .isNull(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java index 3d7450bc98..b054df3ab6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsIntegrationTests.java @@ -103,8 +103,9 @@ class MetricsIntegrationTests { @Test void restTemplateIsInstrumented() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.external).build(); - server.expect(once(), requestTo("/api/external")).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess("{\"message\": \"hello\"}", MediaType.APPLICATION_JSON)); + server.expect(once(), requestTo("/api/external")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess("{\"message\": \"hello\"}", MediaType.APPLICATION_JSON)); assertThat(this.external.getForObject("/api/external", Map.class)).containsKey("message"); assertThat(this.registry.get("http.client.requests").timer().count()).isOne(); } @@ -113,26 +114,27 @@ class MetricsIntegrationTests { void requestMappingIsInstrumented() { this.loopback.getForObject("/api/people", Set.class); waitAtMost(Duration.ofSeconds(5)) - .untilAsserted(() -> assertThat(this.registry.get("http.server.requests").timer().count()).isOne()); + .untilAsserted(() -> assertThat(this.registry.get("http.server.requests").timer().count()).isOne()); } @Test void automaticallyRegisteredBinders() { assertThat(this.context.getBeansOfType(MeterBinder.class).values()) - .hasAtLeastOneElementOfType(LogbackMetrics.class).hasAtLeastOneElementOfType(JvmMemoryMetrics.class); + .hasAtLeastOneElementOfType(LogbackMetrics.class) + .hasAtLeastOneElementOfType(JvmMemoryMetrics.class); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) void metricsFilterRegisteredForAsyncDispatches() { Map filterRegistrations = this.context - .getBeansOfType(FilterRegistrationBean.class); + .getBeansOfType(FilterRegistrationBean.class); assertThat(filterRegistrations).containsKey("webMvcObservationFilter"); FilterRegistrationBean registration = filterRegistrations.get("webMvcObservationFilter"); assertThat(registration.getFilter()).isInstanceOf(ServerHttpObservationFilter.class); assertThat((Set) ReflectionTestUtils.getField(registration, "dispatcherTypes")) - .containsExactlyInAnyOrder(DispatcherType.REQUEST, DispatcherType.ASYNC); + .containsExactlyInAnyOrder(DispatcherType.REQUEST, DispatcherType.ASYNC); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java index 9514e63739..95fef97721 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/test/MetricsRun.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -102,8 +102,8 @@ public final class MetricsRun { () -> "Unknown export auto-configuration " + configuration.getName()); } return (T) contextRunner.withPropertyValues("management.metrics.use-global-registry=false") - .withConfiguration(AUTO_CONFIGURATIONS) - .withConfiguration(AutoConfigurations.of(exportAutoConfigurations)); + .withConfiguration(AUTO_CONFIGURATIONS) + .withConfiguration(AutoConfigurations.of(exportAutoConfigurations)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java index 5aa68a27c2..d53632c544 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/jetty/JettyMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,156 +56,157 @@ class JettyMetricsAutoConfigurationTests { @Test void autoConfiguresThreadPoolMetricsWithEmbeddedServletJetty() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); + }); } @Test void autoConfiguresThreadPoolMetricsWithEmbeddedReactiveJetty() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.threads.config.min").meter()).isNotNull(); + }); } @Test void allowsCustomJettyServerThreadPoolMetricsBinderToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class)) - .withUserConfiguration(CustomJettyServerThreadPoolMetricsBinder.class, MeterRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class) - .hasBean("customJettyServerThreadPoolMetricsBinder")); + .withUserConfiguration(CustomJettyServerThreadPoolMetricsBinder.class, MeterRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JettyServerThreadPoolMetricsBinder.class) + .hasBean("customJettyServerThreadPoolMetricsBinder")); } @Test void autoConfiguresConnectionMetricsWithEmbeddedServletJetty() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); + }); } @Test void autoConfiguresConnectionMetricsWithEmbeddedReactiveJetty() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.connections.messages.in").meter()).isNotNull(); + }); } @Test void allowsCustomJettyConnectionMetricsBinderToBeUsed() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettyConnectionMetricsBinder.class, - MeterRegistryConfiguration.class) - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class) - .hasBean("customJettyConnectionMetricsBinder"); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.connections.messages.in").tag("custom-tag-name", "custom-tag-value") - .meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettyConnectionMetricsBinder.class, + MeterRegistryConfiguration.class) + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettyConnectionMetricsBinder.class) + .hasBean("customJettyConnectionMetricsBinder"); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.connections.messages.in") + .tag("custom-tag-name", "custom-tag-value") + .meter()).isNotNull(); + }); } @Test void autoConfiguresSslHandshakeMetricsWithEmbeddedServletJetty() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); + }); } @Test void autoConfiguresSslHandshakeMetricsWithEmbeddedReactiveJetty() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.ssl.handshakes").meter()).isNotNull(); + }); } @Test void allowsCustomJettySslHandshakeMetricsBinderToBeUsed() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettySslHandshakeMetricsBinder.class, - MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) - .hasBean("customJettySslHandshakeMetricsBinder"); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("jetty.ssl.handshakes").tag("custom-tag-name", "custom-tag-value").meter()) - .isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, CustomJettySslHandshakeMetricsBinder.class, + MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) + .hasBean("customJettySslHandshakeMetricsBinder"); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("jetty.ssl.handshakes").tag("custom-tag-name", "custom-tag-value").meter()) + .isNotNull(); + }); new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class)) - .withUserConfiguration(CustomJettySslHandshakeMetricsBinder.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", - "server.ssl.key-store-password: secret", "server.ssl.key-password: password") - .run((context) -> assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) - .hasBean("customJettySslHandshakeMetricsBinder")); + .withUserConfiguration(CustomJettySslHandshakeMetricsBinder.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: true", "server.ssl.key-store: src/test/resources/test.jks", + "server.ssl.key-store-password: secret", "server.ssl.key-password: password") + .run((context) -> assertThat(context).hasSingleBean(JettySslHandshakeMetricsBinder.class) + .hasBean("customJettySslHandshakeMetricsBinder")); } @Test void doesNotAutoConfigureSslHandshakeMetricsWhenSslEnabledPropertyNotSpecified() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); } @Test void doesNotAutoConfigureSslHandshakeMetricsWhenSslEnabledPropertySetToFalse() { new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.ssl.enabled: false") - .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); + .withConfiguration(AutoConfigurations.of(JettyMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.ssl.enabled: false") + .run((context) -> assertThat(context).doesNotHaveBean(JettySslHandshakeMetricsBinder.class)); } private ApplicationStartedEvent createApplicationStartedEvent(ConfigurableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java index 1356e9ab5a..0fe2d3c39e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/web/tomcat/TomcatMetricsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,54 +58,56 @@ class TomcatMetricsAutoConfigurationTests { void autoConfiguresTomcatMetricsWithEmbeddedServletTomcat() { resetTomcatState(); new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.tomcat.mbeanregistry.enabled=true").run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - assertThat(context).hasSingleBean(TomcatMetricsBinder.class); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); - assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ServletWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.tomcat.mbeanregistry.enabled=true") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + assertThat(context).hasSingleBean(TomcatMetricsBinder.class); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test void autoConfiguresTomcatMetricsWithEmbeddedReactiveTomcat() { resetTomcatState(); new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) - .withPropertyValues("server.tomcat.mbeanregistry.enabled=true").run((context) -> { - context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); - SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); - assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); - assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(ReactiveWebServerConfiguration.class, MeterRegistryConfiguration.class) + .withPropertyValues("server.tomcat.mbeanregistry.enabled=true") + .run((context) -> { + context.publishEvent(createApplicationStartedEvent(context.getSourceApplicationContext())); + SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class); + assertThat(registry.find("tomcat.sessions.active.max").meter()).isNotNull(); + assertThat(registry.find("tomcat.threads.current").meter()).isNotNull(); + }); } @Test void autoConfiguresTomcatMetricsWithStandaloneTomcat() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class)); + .withUserConfiguration(MeterRegistryConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class)); } @Test void allowsCustomTomcatMetricsBinderToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetricsBinder.class) - .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class) - .hasBean("customTomcatMetricsBinder")); + .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetricsBinder.class) + .run((context) -> assertThat(context).hasSingleBean(TomcatMetricsBinder.class) + .hasBean("customTomcatMetricsBinder")); } @Test void allowsCustomTomcatMetricsToBeUsed() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(TomcatMetricsAutoConfiguration.class)) - .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetrics.class) - .run((context) -> assertThat(context).doesNotHaveBean(TomcatMetricsBinder.class) - .hasBean("customTomcatMetrics")); + .withUserConfiguration(MeterRegistryConfiguration.class, CustomTomcatMetrics.class) + .run((context) -> assertThat(context).doesNotHaveBean(TomcatMetricsBinder.class) + .hasBean("customTomcatMetrics")); } private ApplicationStartedEvent createApplicationStartedEvent(ConfigurableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java index c47a0d0e39..5135660ba8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/neo4j/Neo4jHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -46,44 +46,46 @@ import static org.mockito.Mockito.mock; class Neo4jHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - Neo4jHealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + Neo4jHealthContributorAutoConfiguration.class)); @Test void runShouldCreateHealthIndicator() { - this.contextRunner.withUserConfiguration(Neo4jConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(Neo4jReactiveHealthIndicator.class).doesNotHaveBean(Neo4jHealthIndicator.class)); + this.contextRunner.withUserConfiguration(Neo4jConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Neo4jReactiveHealthIndicator.class) + .doesNotHaveBean(Neo4jHealthIndicator.class)); } @Test void runWithoutReactorShouldCreateHealthIndicator() { this.contextRunner.withUserConfiguration(Neo4jConfiguration.class) - .withClassLoader(new FilteredClassLoader(Flux.class)).run((context) -> assertThat(context) - .hasSingleBean(Neo4jHealthIndicator.class).doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); + .withClassLoader(new FilteredClassLoader(Flux.class)) + .run((context) -> assertThat(context).hasSingleBean(Neo4jHealthIndicator.class) + .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withUserConfiguration(Neo4jConfiguration.class) - .withPropertyValues("management.health.neo4j.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) - .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); + .withPropertyValues("management.health.neo4j.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) + .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); } @Test void defaultIndicatorCanBeReplaced() { this.contextRunner.withUserConfiguration(Neo4jConfiguration.class, CustomIndicatorConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("neo4jHealthIndicator"); - Health health = context.getBean("neo4jHealthIndicator", HealthIndicator.class).health(); - assertThat(health.getDetails()).containsOnly(entry("test", true)); - }); + .run((context) -> { + assertThat(context).hasBean("neo4jHealthIndicator"); + Health health = context.getBean("neo4jHealthIndicator", HealthIndicator.class).health(); + assertThat(health.getDetails()).containsOnly(entry("test", true)); + }); } @Test void shouldRequireDriverBean() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(Neo4jHealthIndicator.class) - .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); + .doesNotHaveBean(Neo4jReactiveHealthIndicator.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationAutoConfigurationTests.java index e9587a6e2c..28e4bd0100 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationAutoConfigurationTests.java @@ -62,33 +62,34 @@ import static org.mockito.Mockito.mock; class ObservationAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withClassLoader(new FilteredClassLoader("io.micrometer.tracing")) - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)); + .withClassLoader(new FilteredClassLoader("io.micrometer.tracing")) + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)); private final ApplicationContextRunner tracingContextRunner = new ApplicationContextRunner() - .with(MetricsRun.simple()).withUserConfiguration(TracerConfiguration.class) - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)); + .with(MetricsRun.simple()) + .withUserConfiguration(TracerConfiguration.class) + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)); @Test void beansShouldNotBeSuppliedWhenMicrometerObservationIsNotOnClassPath() { this.tracingContextRunner.withClassLoader(new FilteredClassLoader("io.micrometer.observation")) - .run((context) -> { - assertThat(context).hasSingleBean(MeterRegistry.class); - assertThat(context).doesNotHaveBean(ObservationRegistry.class); - assertThat(context).doesNotHaveBean(ObservationHandler.class); - assertThat(context).doesNotHaveBean(ObservationHandlerGrouping.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(MeterRegistry.class); + assertThat(context).doesNotHaveBean(ObservationRegistry.class); + assertThat(context).doesNotHaveBean(ObservationHandler.class); + assertThat(context).doesNotHaveBean(ObservationHandlerGrouping.class); + }); } @Test void supplyObservationRegistryWhenMicrometerCoreAndTracingAreNotOnClassPath() { this.contextRunner.withClassLoader(new FilteredClassLoader("io.micrometer.core", "io.micrometer.tracing")) - .run((context) -> { - ObservationRegistry observationRegistry = context.getBean(ObservationRegistry.class); - Observation.start("test-observation", observationRegistry).stop(); - assertThat(context).doesNotHaveBean(ObservationHandler.class); - assertThat(context).doesNotHaveBean(ObservationHandlerGrouping.class); - }); + .run((context) -> { + ObservationRegistry observationRegistry = context.getBean(ObservationRegistry.class); + Observation.start("test-observation", observationRegistry).stop(); + assertThat(context).doesNotHaveBean(ObservationHandler.class); + assertThat(context).doesNotHaveBean(ObservationHandlerGrouping.class); + }); } @Test @@ -131,14 +132,15 @@ class ObservationAutoConfigurationTests { @Test void supplyMeterHandlerAndGroupingWhenMicrometerCoreAndTracingAreOnClassPathButThereIsNoTracer() { new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)).run((context) -> { - ObservationRegistry observationRegistry = context.getBean(ObservationRegistry.class); - Observation.start("test-observation", observationRegistry).stop(); - assertThat(context).hasSingleBean(ObservationHandler.class); - assertThat(context).hasSingleBean(DefaultMeterObservationHandler.class); - assertThat(context).hasSingleBean(ObservationHandlerGrouping.class); - assertThat(context).hasBean("metricsAndTracingObservationHandlerGrouping"); - }); + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)) + .run((context) -> { + ObservationRegistry observationRegistry = context.getBean(ObservationRegistry.class); + Observation.start("test-observation", observationRegistry).stop(); + assertThat(context).hasSingleBean(ObservationHandler.class); + assertThat(context).hasSingleBean(DefaultMeterObservationHandler.class); + assertThat(context).hasSingleBean(ObservationHandlerGrouping.class); + assertThat(context).hasBean("metricsAndTracingObservationHandlerGrouping"); + }); } @Test @@ -159,7 +161,7 @@ class ObservationAutoConfigurationTests { @Test void allowsDefaultMeterObservationHandlerToBeDisabled() { this.contextRunner.withClassLoader(new FilteredClassLoader(MeterRegistry.class)) - .run((context) -> assertThat(context).doesNotHaveBean(ObservationHandler.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ObservationHandler.class)); } @Test @@ -173,7 +175,7 @@ class ObservationAutoConfigurationTests { MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); assertThat(meterRegistry.get("observation1").timer().count()).isOne(); assertThatThrownBy(() -> meterRegistry.get("observation2").timer()) - .isInstanceOf(MeterNotFoundException.class); + .isInstanceOf(MeterNotFoundException.class); }); } @@ -212,7 +214,7 @@ class ObservationAutoConfigurationTests { // one assertThat(handlers.get(1)).isInstanceOf(CustomMeterObservationHandler.class); assertThat(((CustomMeterObservationHandler) handlers.get(1)).getName()) - .isEqualTo("customMeterObservationHandler1"); + .isEqualTo("customMeterObservationHandler1"); assertThat(context).doesNotHaveBean(DefaultMeterObservationHandler.class); assertThat(context).doesNotHaveBean(TracingAwareMeterObservationHandler.class); }); @@ -221,16 +223,16 @@ class ObservationAutoConfigurationTests { @Test void autoConfiguresObservationHandlerWithCustomContext() { this.contextRunner.withUserConfiguration(ObservationHandlerWithCustomContextConfiguration.class) - .run((context) -> { - ObservationRegistry observationRegistry = context.getBean(ObservationRegistry.class); - List> handlers = context.getBean(CalledHandlers.class).getCalledHandlers(); - CustomContext customContext = new CustomContext(); - Observation.start("test-observation", () -> customContext, observationRegistry).stop(); - assertThat(handlers).hasSize(1); - assertThat(handlers.get(0)).isInstanceOf(ObservationHandlerWithCustomContext.class); - assertThat(context).hasSingleBean(DefaultMeterObservationHandler.class); - assertThat(context).doesNotHaveBean(TracingAwareMeterObservationHandler.class); - }); + .run((context) -> { + ObservationRegistry observationRegistry = context.getBean(ObservationRegistry.class); + List> handlers = context.getBean(CalledHandlers.class).getCalledHandlers(); + CustomContext customContext = new CustomContext(); + Observation.start("test-observation", () -> customContext, observationRegistry).stop(); + assertThat(handlers).hasSize(1); + assertThat(handlers.get(0)).isInstanceOf(ObservationHandlerWithCustomContext.class); + assertThat(context).hasSingleBean(DefaultMeterObservationHandler.class); + assertThat(context).doesNotHaveBean(TracingAwareMeterObservationHandler.class); + }); } @Test @@ -262,13 +264,13 @@ class ObservationAutoConfigurationTests { // one assertThat(handlers.get(1)).isInstanceOf(CustomTracingObservationHandler.class); assertThat(((CustomTracingObservationHandler) handlers.get(1)).getName()) - .isEqualTo("customTracingHandler1"); + .isEqualTo("customTracingHandler1"); // Multiple MeterObservationHandler are wrapped in // FirstMatchingCompositeObservationHandler, which calls only the first // one assertThat(handlers.get(2)).isInstanceOf(CustomMeterObservationHandler.class); assertThat(((CustomMeterObservationHandler) handlers.get(2)).getName()) - .isEqualTo("customMeterObservationHandler1"); + .isEqualTo("customMeterObservationHandler1"); assertThat(context).doesNotHaveBean(TracingAwareMeterObservationHandler.class); assertThat(context).doesNotHaveBean(DefaultMeterObservationHandler.class); }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurerIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurerIntegrationTests.java index e9abbafae5..12ffa4d1ca 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurerIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryConfigurerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ObservationRegistryConfigurerIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)); @Test void customizersAreCalledInOrder() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/graphql/GraphQlObservationAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/graphql/GraphQlObservationAutoConfigurationTests.java index f5f1441076..2c29dfa66f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/graphql/GraphQlObservationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/graphql/GraphQlObservationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,14 +42,14 @@ import static org.mockito.Mockito.mock; class GraphQlObservationAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(TestObservationRegistry.class, TestObservationRegistry::create) - .withConfiguration(AutoConfigurations.of(GraphQlObservationAutoConfiguration.class)); + .withBean(TestObservationRegistry.class, TestObservationRegistry::create) + .withConfiguration(AutoConfigurations.of(GraphQlObservationAutoConfiguration.class)); @Test void backsOffWhenObservationRegistryIsMissing() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphQlObservationAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(GraphQlObservationInstrumentation.class)); + .withConfiguration(AutoConfigurations.of(GraphQlObservationAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(GraphQlObservationInstrumentation.class)); } @Test @@ -60,38 +60,38 @@ class GraphQlObservationAutoConfigurationTests { @Test void instrumentationBacksOffIfAlreadyPresent() { this.contextRunner.withUserConfiguration(InstrumentationConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(GraphQlObservationInstrumentation.class) - .hasBean("customInstrumentation")); + .run((context) -> assertThat(context).hasSingleBean(GraphQlObservationInstrumentation.class) + .hasBean("customInstrumentation")); } @Test void instrumentationUsesCustomConventionsIfAvailable() { this.contextRunner.withUserConfiguration(CustomConventionsConfiguration.class).run((context) -> { GraphQlObservationInstrumentation instrumentation = context - .getBean(GraphQlObservationInstrumentation.class); + .getBean(GraphQlObservationInstrumentation.class); assertThat(instrumentation).extracting("requestObservationConvention") - .isInstanceOf(CustomExecutionRequestObservationConvention.class); + .isInstanceOf(CustomExecutionRequestObservationConvention.class); assertThat(instrumentation).extracting("dataFetcherObservationConvention") - .isInstanceOf(CustomDataFetcherObservationConvention.class); + .isInstanceOf(CustomDataFetcherObservationConvention.class); }); } @Test void propagationInterceptorNotContributedWhenPropagatorIsMissing() { this.contextRunner.withUserConfiguration(WebGraphQlConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PropagationWebGraphQlInterceptor.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PropagationWebGraphQlInterceptor.class)); } @Test void propagationInterceptorNotContributedWhenNotWebApplication() { this.contextRunner.withUserConfiguration(TracingConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(PropagationWebGraphQlInterceptor.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PropagationWebGraphQlInterceptor.class)); } @Test void propagationInterceptorContributed() { this.contextRunner.withUserConfiguration(WebGraphQlConfiguration.class, TracingConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(PropagationWebGraphQlInterceptor.class)); + .run((context) -> assertThat(context).hasSingleBean(PropagationWebGraphQlInterceptor.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/ClientObservationConventionAdapterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/ClientObservationConventionAdapterTests.java index ea6929744c..cd73e29efb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/ClientObservationConventionAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/ClientObservationConventionAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,8 +47,8 @@ class ClientObservationConventionAdapterTests { TEST_METRIC_NAME, new DefaultWebClientExchangeTagsProvider()); private final ClientRequest.Builder requestBuilder = ClientRequest - .create(HttpMethod.GET, URI.create("/resource/test")) - .attribute(WebClient.class.getName() + ".uriTemplate", "/resource/{name}"); + .create(HttpMethod.GET, URI.create("/resource/test")) + .attribute(WebClient.class.getName() + ".uriTemplate", "/resource/{name}"); private final ClientResponse response = ClientResponse.create(HttpStatus.OK).body("foo").build(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationTests.java index 5be2fdeff7..6116649a14 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,14 +62,14 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat class RestTemplateObservationConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(ObservationRegistry.class, TestObservationRegistry::create) - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, - RestTemplateAutoConfiguration.class, HttpClientObservationsAutoConfiguration.class)); + .withBean(ObservationRegistry.class, TestObservationRegistry::create) + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, + RestTemplateAutoConfiguration.class, HttpClientObservationsAutoConfiguration.class)); @Test void contributesCustomizerBean() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ObservationRestTemplateCustomizer.class) - .doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class)); + .doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class)); } @Test @@ -79,7 +79,7 @@ class RestTemplateObservationConfigurationTests { restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); TestObservationRegistryAssert.assertThat(registry) - .hasObservationWithNameEqualToIgnoringCase("http.client.requests"); + .hasObservationWithNameEqualToIgnoringCase("http.client.requests"); }); } @@ -87,26 +87,26 @@ class RestTemplateObservationConfigurationTests { void restTemplateCreatedWithBuilderUsesCustomConventionName() { final String observationName = "test.metric.name"; this.contextRunner.withPropertyValues("management.observations.http.client.requests.name=" + observationName) - .run((context) -> { - RestTemplate restTemplate = buildRestTemplate(context); - restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); - TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); - TestObservationRegistryAssert.assertThat(registry) - .hasObservationWithNameEqualToIgnoringCase(observationName); - }); + .run((context) -> { + RestTemplate restTemplate = buildRestTemplate(context); + restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); + TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); + TestObservationRegistryAssert.assertThat(registry) + .hasObservationWithNameEqualToIgnoringCase(observationName); + }); } @Test void restTemplateCreatedWithBuilderUsesCustomMetricName() { final String metricName = "test.metric.name"; this.contextRunner.withPropertyValues("management.metrics.web.client.request.metric-name=" + metricName) - .run((context) -> { - RestTemplate restTemplate = buildRestTemplate(context); - restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); - TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); - TestObservationRegistryAssert.assertThat(registry) - .hasObservationWithNameEqualToIgnoringCase(metricName); - }); + .run((context) -> { + RestTemplate restTemplate = buildRestTemplate(context); + restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); + TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); + TestObservationRegistryAssert.assertThat(registry) + .hasObservationWithNameEqualToIgnoringCase(metricName); + }); } @Test @@ -115,8 +115,10 @@ class RestTemplateObservationConfigurationTests { RestTemplate restTemplate = buildRestTemplate(context); restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); - TestObservationRegistryAssert.assertThat(registry).hasObservationWithNameEqualTo("http.client.requests") - .that().hasLowCardinalityKeyValue("project", "spring-boot"); + TestObservationRegistryAssert.assertThat(registry) + .hasObservationWithNameEqualTo("http.client.requests") + .that() + .hasLowCardinalityKeyValue("project", "spring-boot"); }); } @@ -126,40 +128,43 @@ class RestTemplateObservationConfigurationTests { RestTemplate restTemplate = buildRestTemplate(context); restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); - TestObservationRegistryAssert.assertThat(registry).hasObservationWithNameEqualTo("http.client.requests") - .that().hasLowCardinalityKeyValue("project", "spring-boot"); + TestObservationRegistryAssert.assertThat(registry) + .hasObservationWithNameEqualTo("http.client.requests") + .that() + .hasLowCardinalityKeyValue("project", "spring-boot"); }); } @Test void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) { - this.contextRunner.with(MetricsRun.simple()).withPropertyValues("management.metrics.web.client.max-uri-tags=2") - .run((context) -> { - RestTemplate restTemplate = context.getBean(RestTemplateBuilder.class).build(); - MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate); - for (int i = 0; i < 3; i++) { - server.expect(requestTo("/test/" + i)).andRespond(withStatus(HttpStatus.OK)); - } - for (int i = 0; i < 3; i++) { - restTemplate.getForObject("/test/" + i, String.class); - } - TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); - TestObservationRegistryAssert.assertThat(registry) - .hasNumberOfObservationsWithNameEqualTo("http.client.requests", 3); - MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); - assertThat(meterRegistry.find("http.client.requests").timers()).hasSize(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'http.client.requests'.") - .contains("Are you using 'uriVariables'?"); - }); + this.contextRunner.with(MetricsRun.simple()) + .withPropertyValues("management.metrics.web.client.max-uri-tags=2") + .run((context) -> { + RestTemplate restTemplate = context.getBean(RestTemplateBuilder.class).build(); + MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate); + for (int i = 0; i < 3; i++) { + server.expect(requestTo("/test/" + i)).andRespond(withStatus(HttpStatus.OK)); + } + for (int i = 0; i < 3; i++) { + restTemplate.getForObject("/test/" + i, String.class); + } + TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); + TestObservationRegistryAssert.assertThat(registry) + .hasNumberOfObservationsWithNameEqualTo("http.client.requests", 3); + MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); + assertThat(meterRegistry.find("http.client.requests").timers()).hasSize(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'http.client.requests'.") + .contains("Are you using 'uriVariables'?"); + }); } @Test void backsOffWhenRestTemplateBuilderIsMissing() { new ApplicationContextRunner().with(MetricsRun.simple()) - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, - HttpClientObservationsAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class) - .doesNotHaveBean(ObservationRestTemplateCustomizer.class)); + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, + HttpClientObservationsAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(DefaultRestTemplateExchangeTagsProvider.class) + .doesNotHaveBean(ObservationRestTemplateCustomizer.class)); } private RestTemplate buildRestTemplate(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationWithoutMetricsTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationWithoutMetricsTests.java index f591b04353..9d821b7f31 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationWithoutMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/RestTemplateObservationConfigurationWithoutMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,9 +48,9 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat class RestTemplateObservationConfigurationWithoutMetricsTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withBean(ObservationRegistry.class, TestObservationRegistry::create) - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, - RestTemplateAutoConfiguration.class, HttpClientObservationsAutoConfiguration.class)); + .withBean(ObservationRegistry.class, TestObservationRegistry::create) + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, + RestTemplateAutoConfiguration.class, HttpClientObservationsAutoConfiguration.class)); @Test void restTemplateCreatedWithBuilderIsInstrumented() { @@ -59,7 +59,7 @@ class RestTemplateObservationConfigurationWithoutMetricsTests { restTemplate.getForEntity("/projects/{project}", Void.class, "spring-boot"); TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); TestObservationRegistryAssert.assertThat(registry) - .hasObservationWithNameEqualToIgnoringCase("http.client.requests"); + .hasObservationWithNameEqualToIgnoringCase("http.client.requests"); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/WebClientObservationConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/WebClientObservationConfigurationTests.java index 9844942916..9a94712edc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/WebClientObservationConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/client/WebClientObservationConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,14 +63,14 @@ import static org.mockito.Mockito.mock; class WebClientObservationConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().with(MetricsRun.simple()) - .withBean(ObservationRegistry.class, TestObservationRegistry::create) - .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, - WebClientAutoConfiguration.class, HttpClientObservationsAutoConfiguration.class)); + .withBean(ObservationRegistry.class, TestObservationRegistry::create) + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, WebClientAutoConfiguration.class, + HttpClientObservationsAutoConfiguration.class)); @Test void contributesCustomizerBean() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ObservationWebClientCustomizer.class) - .doesNotHaveBean(DefaultWebClientExchangeTagsProvider.class)); + .doesNotHaveBean(DefaultWebClientExchangeTagsProvider.class)); } @Test @@ -84,8 +84,10 @@ class WebClientObservationConfigurationTests { @Test void shouldNotOverrideCustomTagsProvider() { - this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class).run((context) -> assertThat(context) - .getBeans(WebClientExchangeTagsProvider.class).hasSize(1).containsKey("customTagsProvider")); + this.contextRunner.withUserConfiguration(CustomTagsProviderConfig.class) + .run((context) -> assertThat(context).getBeans(WebClientExchangeTagsProvider.class) + .hasSize(1) + .containsKey("customTagsProvider")); } @Test @@ -95,10 +97,15 @@ class WebClientObservationConfigurationTests { WebClient.Builder builder = context.getBean(WebClient.Builder.class); WebClient webClient = mockWebClient(builder); TestObservationRegistryAssert.assertThat(registry).doesNotHaveAnyObservation(); - webClient.get().uri("https://example.org/projects/{project}", "spring-boot").retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); - TestObservationRegistryAssert.assertThat(registry).hasObservationWithNameEqualTo("http.client.requests") - .that().hasLowCardinalityKeyValue("project", "spring-boot"); + webClient.get() + .uri("https://example.org/projects/{project}", "spring-boot") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); + TestObservationRegistryAssert.assertThat(registry) + .hasObservationWithNameEqualTo("http.client.requests") + .that() + .hasLowCardinalityKeyValue("project", "spring-boot"); }); } @@ -107,13 +114,13 @@ class WebClientObservationConfigurationTests { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=2").run((context) -> { TestObservationRegistry registry = getInitializedRegistry(context); TestObservationRegistryAssert.assertThat(registry) - .hasNumberOfObservationsWithNameEqualTo("http.client.requests", 3); + .hasNumberOfObservationsWithNameEqualTo("http.client.requests", 3); MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); assertThat(meterRegistry.find("http.client.requests").timers()).hasSize(1); // MeterFilter.maximumAllowableTags() works with prefix matching. assertThat(meterRegistry.find("http.client.requests.active").longTaskTimers()).hasSize(1); assertThat(output).contains("Reached the maximum number of URI tags for 'http.client.requests'.") - .contains("Are you using 'uriVariables'?"); + .contains("Are you using 'uriVariables'?"); }); } @@ -122,11 +129,11 @@ class WebClientObservationConfigurationTests { this.contextRunner.withPropertyValues("management.metrics.web.client.max-uri-tags=5").run((context) -> { TestObservationRegistry registry = getInitializedRegistry(context); TestObservationRegistryAssert.assertThat(registry) - .hasNumberOfObservationsWithNameEqualTo("http.client.requests", 3); + .hasNumberOfObservationsWithNameEqualTo("http.client.requests", 3); MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); assertThat(meterRegistry.find("http.client.requests").timers()).hasSize(3); assertThat(output).doesNotContain("Reached the maximum number of URI tags for 'http.client.requests'.") - .doesNotContain("Are you using 'uriVariables'?"); + .doesNotContain("Are you using 'uriVariables'?"); }); } @@ -134,8 +141,11 @@ class WebClientObservationConfigurationTests { WebClient webClient = mockWebClient(context.getBean(WebClient.Builder.class)); TestObservationRegistry registry = context.getBean(TestObservationRegistry.class); for (int i = 0; i < 3; i++) { - webClient.get().uri("https://example.org/projects/" + i).retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); + webClient.get() + .uri("https://example.org/projects/" + i) + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); } return registry; } @@ -143,10 +153,15 @@ class WebClientObservationConfigurationTests { private void validateWebClient(WebClient.Builder builder, TestObservationRegistry registry) { WebClient webClient = mockWebClient(builder); TestObservationRegistryAssert.assertThat(registry).doesNotHaveAnyObservation(); - webClient.get().uri("https://example.org/projects/{project}", "spring-boot").retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); - TestObservationRegistryAssert.assertThat(registry).hasObservationWithNameEqualTo("http.client.requests").that() - .hasLowCardinalityKeyValue("uri", "/projects/{project}"); + webClient.get() + .uri("https://example.org/projects/{project}", "spring-boot") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); + TestObservationRegistryAssert.assertThat(registry) + .hasObservationWithNameEqualTo("http.client.requests") + .that() + .hasLowCardinalityKeyValue("uri", "/projects/{project}"); } private WebClient mockWebClient(WebClient.Builder builder) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/reactive/WebFluxObservationAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/reactive/WebFluxObservationAutoConfigurationTests.java index 8a148a8502..88609e23f6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/reactive/WebFluxObservationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/reactive/WebFluxObservationAutoConfigurationTests.java @@ -63,8 +63,9 @@ import static org.assertj.core.api.Assertions.assertThat; class WebFluxObservationAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class, - WebFluxObservationAutoConfiguration.class)); + .with(MetricsRun.simple()) + .withConfiguration( + AutoConfigurations.of(ObservationAutoConfiguration.class, WebFluxObservationAutoConfiguration.class)); @Test void shouldProvideWebFluxObservationFilter() { @@ -86,8 +87,9 @@ class WebFluxObservationAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomTagsProviderConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ServerHttpObservationFilter.class); assertThat(context).hasSingleBean(WebFluxTagsProvider.class); - assertThat(context).getBean(ServerHttpObservationFilter.class).extracting("observationConvention") - .isInstanceOf(ServerRequestObservationConventionAdapter.class); + assertThat(context).getBean(ServerHttpObservationFilter.class) + .extracting("observationConvention") + .isInstanceOf(ServerRequestObservationConventionAdapter.class); }); } @@ -96,8 +98,9 @@ class WebFluxObservationAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomTagsContributorConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ServerHttpObservationFilter.class); assertThat(context).hasSingleBean(WebFluxTagsContributor.class); - assertThat(context).getBean(ServerHttpObservationFilter.class).extracting("observationConvention") - .isInstanceOf(ServerRequestObservationConventionAdapter.class); + assertThat(context).getBean(ServerHttpObservationFilter.class) + .extracting("observationConvention") + .isInstanceOf(ServerRequestObservationConventionAdapter.class); }); } @@ -105,63 +108,65 @@ class WebFluxObservationAutoConfigurationTests { void shouldUseCustomConventionWhenAvailable() { this.contextRunner.withUserConfiguration(CustomConventionConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ServerHttpObservationFilter.class); - assertThat(context).getBean(ServerHttpObservationFilter.class).extracting("observationConvention") - .isInstanceOf(CustomConvention.class); + assertThat(context).getBean(ServerHttpObservationFilter.class) + .extracting("observationConvention") + .isInstanceOf(CustomConvention.class); }); } @Test void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebFluxAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebFluxAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } @Test @Deprecated(since = "3.0.0", forRemoval = true) void afterMaxUrisReachedFurtherUrisAreDeniedWhenUsingCustomMetricName(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebFluxAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2", - "management.metrics.web.server.request.metric-name=my.http.server.requests") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebFluxAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2", + "management.metrics.web.server.request.metric-name=my.http.server.requests") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); + }); } @Test void afterMaxUrisReachedFurtherUrisAreDeniedWhenUsingCustomObservationName(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebFluxAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2", - "management.observations.http.server.requests.name=my.http.server.requests") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebFluxAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2", + "management.observations.http.server.requests.name=my.http.server.requests") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); + }); } @Test void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebFluxAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSize(3); - assertThat(output) - .doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebFluxAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=5") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSize(3); + assertThat(output).doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } private MeterRegistry getInitializedMeterRegistry(AssertableReactiveWebApplicationContext context) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/servlet/WebMvcObservationAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/servlet/WebMvcObservationAutoConfigurationTests.java index 62ae700174..a8fe9bf9c9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/servlet/WebMvcObservationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/observation/web/servlet/WebMvcObservationAutoConfigurationTests.java @@ -70,14 +70,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class WebMvcObservationAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .with(MetricsRun.simple()).withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(WebMvcObservationAutoConfiguration.class)); + .with(MetricsRun.simple()) + .withConfiguration(AutoConfigurations.of(ObservationAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of(WebMvcObservationAutoConfiguration.class)); @Test void backsOffWhenMeterRegistryIsMissing() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebMvcObservationAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class)); + .withConfiguration(AutoConfigurations.of(WebMvcObservationAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class)); } @Test @@ -86,23 +87,24 @@ class WebMvcObservationAutoConfigurationTests { assertThat(context).doesNotHaveBean(DefaultWebMvcTagsProvider.class); assertThat(context).hasSingleBean(FilterRegistrationBean.class); assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) - .isInstanceOf(ServerHttpObservationFilter.class); + .isInstanceOf(ServerHttpObservationFilter.class); }); } @Test void adapterConventionWhenTagsProviderPresent() { this.contextRunner.withUserConfiguration(TagsProviderConfiguration.class) - .run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) - .extracting("observationConvention") - .isInstanceOf(ServerRequestObservationConventionAdapter.class)); + .run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) + .extracting("observationConvention") + .isInstanceOf(ServerRequestObservationConventionAdapter.class)); } @Test void customConventionWhenPresent() { this.contextRunner.withUserConfiguration(CustomConventionConfiguration.class) - .run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) - .extracting("observationConvention").isInstanceOf(CustomConvention.class)); + .run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) + .extracting("observationConvention") + .isInstanceOf(CustomConvention.class)); } @Test @@ -118,92 +120,93 @@ class WebMvcObservationAutoConfigurationTests { @Test void filterRegistrationBacksOffWithAnotherServerHttpObservationFilterRegistration() { this.contextRunner.withUserConfiguration(TestServerHttpObservationFilterRegistrationConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(FilterRegistrationBean.class); - assertThat(context.getBean(FilterRegistrationBean.class)) - .isSameAs(context.getBean("testServerHttpObservationFilter")); - }); + .run((context) -> { + assertThat(context).hasSingleBean(FilterRegistrationBean.class); + assertThat(context.getBean(FilterRegistrationBean.class)) + .isSameAs(context.getBean("testServerHttpObservationFilter")); + }); } @Test void filterRegistrationBacksOffWithAnotherServerHttpObservationFilter() { this.contextRunner.withUserConfiguration(TestServerHttpObservationFilterConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class) - .hasSingleBean(ServerHttpObservationFilter.class)); + .run((context) -> assertThat(context).doesNotHaveBean(FilterRegistrationBean.class) + .hasSingleBean(ServerHttpObservationFilter.class)); } @Test void filterRegistrationDoesNotBackOffWithOtherFilterRegistration() { this.contextRunner.withUserConfiguration(TestFilterRegistrationConfiguration.class) - .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcObservationFilter")); + .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcObservationFilter")); } @Test void filterRegistrationDoesNotBackOffWithOtherFilter() { this.contextRunner.withUserConfiguration(TestFilterConfiguration.class) - .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcObservationFilter")); + .run((context) -> assertThat(context).hasBean("testFilter").hasBean("webMvcObservationFilter")); } @Test void afterMaxUrisReachedFurtherUrisAreDenied(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } @Test @Deprecated(since = "3.0.0", forRemoval = true) void afterMaxUrisReachedFurtherUrisAreDeniedWhenUsingCustomMetricName(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2", - "management.metrics.web.server.request.metric-name=my.http.server.requests") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2", + "management.metrics.web.server.request.metric-name=my.http.server.requests") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); + }); } @Test void afterMaxUrisReachedFurtherUrisAreDeniedWhenUsingCustomObservationName(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=2", - "management.observations.http.server.requests.name=my.http.server.requests") - .run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); - assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=2", + "management.observations.http.server.requests.name=my.http.server.requests") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("my.http.server.requests").meters()).hasSizeLessThanOrEqualTo(2); + assertThat(output).contains("Reached the maximum number of URI tags for 'my.http.server.requests'"); + }); } @Test void shouldNotDenyNorLogIfMaxUrisIsNotReached(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestController.class) - .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, - ObservationAutoConfiguration.class, WebMvcAutoConfiguration.class)) - .withPropertyValues("management.metrics.web.server.max-uri-tags=5").run((context) -> { - MeterRegistry registry = getInitializedMeterRegistry(context); - assertThat(registry.get("http.server.requests").meters()).hasSize(3); - assertThat(output) - .doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); - }); + .withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class, ObservationAutoConfiguration.class, + WebMvcAutoConfiguration.class)) + .withPropertyValues("management.metrics.web.server.max-uri-tags=5") + .run((context) -> { + MeterRegistry registry = getInitializedMeterRegistry(context); + assertThat(registry.get("http.server.requests").meters()).hasSize(3); + assertThat(output).doesNotContain("Reached the maximum number of URI tags for 'http.server.requests'"); + }); } @Test void whenTagContributorsAreDefinedThenTagsProviderUsesThem() { this.contextRunner.withUserConfiguration(TagsContributorsConfiguration.class) - .run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) - .extracting("observationConvention") - .isInstanceOf(ServerRequestObservationConventionAdapter.class)); + .run((context) -> assertThat(context.getBean(FilterRegistrationBean.class).getFilter()) + .extracting("observationConvention") + .isInstanceOf(ServerRequestObservationConventionAdapter.class)); } private MeterRegistry getInitializedMeterRegistry(AssertableWebApplicationContext context) throws Exception { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java index b9686be21e..163f18bfbe 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/quartz/QuartzEndpointAutoConfigurationTests.java @@ -43,73 +43,75 @@ import static org.mockito.Mockito.mock; class QuartzEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(QuartzEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(QuartzEndpointAutoConfiguration.class)); @Test void endpointIsAutoConfigured() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoints.web.exposure.include=quartz") - .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=quartz") + .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class)); } @Test void endpointIsNotAutoConfiguredIfSchedulerIsNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=quartz") - .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); } @Test void endpointNotAutoConfiguredWhenNotExposed() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); } @Test void endpointCanBeDisabled() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoint.quartz.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); + .withPropertyValues("management.endpoint.quartz.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(QuartzEndpoint.class)); } @Test void endpointBacksOffWhenUserProvidedEndpointIsPresent() { this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class).hasBean("customEndpoint")); + .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class).hasBean("customEndpoint")); } @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", - "management.endpoints.jmx.exposure.include=quartz") - .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class) - .doesNotHaveBean(QuartzEndpointWebExtension.class)); + .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", + "management.endpoints.jmx.exposure.include=quartz") + .run((context) -> assertThat(context).hasSingleBean(QuartzEndpoint.class) + .doesNotHaveBean(QuartzEndpointWebExtension.class)); } @Test @SuppressWarnings("unchecked") void rolesCanBeConfiguredViaTheEnvironment() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoint.quartz.roles: test") - .withPropertyValues("management.endpoints.web.exposure.include=quartz") - .withSystemProperties("dbPassword=123456", "apiKey=123456").run((context) -> { - assertThat(context).hasSingleBean(QuartzEndpointWebExtension.class); - QuartzEndpointWebExtension endpoint = context.getBean(QuartzEndpointWebExtension.class); - Set roles = (Set) ReflectionTestUtils.getField(endpoint, "roles"); - assertThat(roles).contains("test"); - }); + .withPropertyValues("management.endpoint.quartz.roles: test") + .withPropertyValues("management.endpoints.web.exposure.include=quartz") + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .run((context) -> { + assertThat(context).hasSingleBean(QuartzEndpointWebExtension.class); + QuartzEndpointWebExtension endpoint = context.getBean(QuartzEndpointWebExtension.class); + Set roles = (Set) ReflectionTestUtils.getField(endpoint, "roles"); + assertThat(roles).contains("test"); + }); } @Test void showValuesCanBeConfiguredViaTheEnvironment() { this.contextRunner.withBean(Scheduler.class, () -> mock(Scheduler.class)) - .withPropertyValues("management.endpoint.quartz.show-values: WHEN_AUTHORIZED") - .withPropertyValues("management.endpoints.web.exposure.include=quartz") - .withSystemProperties("dbPassword=123456", "apiKey=123456").run((context) -> { - assertThat(context).hasSingleBean(QuartzEndpointWebExtension.class); - assertThat(context.getBean(QuartzEndpointWebExtension.class)).extracting("showValues") - .isEqualTo(Show.WHEN_AUTHORIZED); - }); + .withPropertyValues("management.endpoint.quartz.show-values: WHEN_AUTHORIZED") + .withPropertyValues("management.endpoints.web.exposure.include=quartz") + .withSystemProperties("dbPassword=123456", "apiKey=123456") + .run((context) -> { + assertThat(context).hasSingleBean(QuartzEndpointWebExtension.class); + assertThat(context.getBean(QuartzEndpointWebExtension.class)).extracting("showValues") + .isEqualTo(Show.WHEN_AUTHORIZED); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java index d10344b5e2..570103dd97 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/r2dbc/ConnectionFactoryHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,26 +34,26 @@ import static org.assertj.core.api.Assertions.assertThat; class ConnectionFactoryHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ConnectionFactoryHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ConnectionFactoryHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactoryHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactoryHealthIndicator.class)); } @Test void runWithNoConnectionFactoryShouldNotCreateIndicator() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withPropertyValues("management.health.r2dbc.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); + .withPropertyValues("management.health.r2dbc.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionFactoryHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java index e24e69d421..b1c8ed48b8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/scheduling/ScheduledTasksEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,12 +36,12 @@ import static org.assertj.core.api.Assertions.assertThat; class ScheduledTasksEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ScheduledTasksEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ScheduledTasksEndpointAutoConfiguration.class)); @Test void endpointIsAutoConfigured() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=scheduledtasks") - .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class)); } @Test @@ -52,13 +52,14 @@ class ScheduledTasksEndpointAutoConfigurationTests { @Test void endpointCanBeDisabled() { this.contextRunner.withPropertyValues("management.endpoint.scheduledtasks.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ScheduledTasksEndpoint.class)); } @Test void endpointBacksOffWhenUserProvidedEndpointIsPresent() { - this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class).run( - (context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class).hasBean("customEndpoint")); + this.contextRunner.withUserConfiguration(CustomEndpointConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ScheduledTasksEndpoint.class) + .hasBean("customEndpoint")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java index 935c49ac6f..f6e3088ac3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequestTests.java @@ -132,8 +132,8 @@ class EndpointRequestTests { @Test void excludeByClassShouldNotMatchExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excluding(FooEndpoint.class, - BazServletEndpoint.class); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() + .excluding(FooEndpoint.class, BazServletEndpoint.class); List> endpoints = new ArrayList<>(); endpoints.add(mockEndpoint(EndpointId.of("foo"), "foo")); endpoints.add(mockEndpoint(EndpointId.of("bar"), "bar")); @@ -151,8 +151,9 @@ class EndpointRequestTests { @Test void excludeByClassShouldNotMatchLinksIfExcluded() { - ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks() - .excluding(FooEndpoint.class); + ServerWebExchangeMatcher matcher = EndpointRequest.toAnyEndpoint() + .excludingLinks() + .excluding(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo/"); assertMatcher(matcher).doesNotMatch("/actuator"); @@ -289,7 +290,8 @@ class EndpointRequestTests { private void matches(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Matches " + getRequestPath(exchange)).isTrue(); + .as("Matches " + getRequestPath(exchange)) + .isTrue(); } void doesNotMatch(String path) { @@ -300,7 +302,8 @@ class EndpointRequestTests { private void doesNotMatch(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Does not match " + getRequestPath(exchange)).isFalse(); + .as("Does not match " + getRequestPath(exchange)) + .isFalse(); } private TestHttpWebHandlerAdapter webHandler() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java index 9355cabce0..48fa6e6263 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -66,12 +66,12 @@ import static org.mockito.Mockito.mock; class ReactiveManagementWebSecurityAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, - HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class, - WebFluxAutoConfiguration.class, EnvironmentEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - ReactiveSecurityAutoConfiguration.class, ReactiveUserDetailsServiceAutoConfiguration.class, - ReactiveManagementWebSecurityAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HealthContributorAutoConfiguration.class, + HealthEndpointAutoConfiguration.class, InfoEndpointAutoConfiguration.class, + WebFluxAutoConfiguration.class, EnvironmentEndpointAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + ReactiveSecurityAutoConfiguration.class, ReactiveUserDetailsServiceAutoConfiguration.class, + ReactiveManagementWebSecurityAutoConfiguration.class)); @Test void permitAllForHealth() { @@ -105,9 +105,9 @@ class ReactiveManagementWebSecurityAutoConfigurationTests { @Test void backOffIfReactiveOAuth2ResourceServerAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") - .run((context) -> assertThat(context) - .doesNotHaveBean(ReactiveManagementWebSecurityAutoConfiguration.class)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") + .run((context) -> assertThat(context) + .doesNotHaveBean(ReactiveManagementWebSecurityAutoConfiguration.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java index b1db7b8d97..0f12497dd5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/AbstractEndpointRequestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,8 +68,12 @@ abstract class AbstractEndpointRequestIntegrationTests { getContextRunner().withPropertyValues("spring.security.user.password=password").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/actuator/e2").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/e2").header("Authorization", getBasicAuth()).exchange().expectStatus() - .isOk(); + webTestClient.get() + .uri("/actuator/e2") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); }); } @@ -78,8 +82,11 @@ abstract class AbstractEndpointRequestIntegrationTests { getContextRunner().run((context) -> { WebTestClient webTestClient = getWebTestClient(context); webTestClient.get().uri("/actuator").exchange().expectStatus().isOk(); - webTestClient.get().uri("/actuator/").exchange().expectStatus() - .isEqualTo(expectedStatusWithTrailingSlash()); + webTestClient.get() + .uri("/actuator/") + .exchange() + .expectStatus() + .isEqualTo(expectedStatusWithTrailingSlash()); }); } @@ -89,10 +96,10 @@ abstract class AbstractEndpointRequestIntegrationTests { protected final WebApplicationContextRunner getContextRunner() { return createContextRunner().withPropertyValues("management.endpoints.web.exposure.include=*") - .withUserConfiguration(BaseConfiguration.class, SecurityConfiguration.class).withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, SecurityAutoConfiguration.class, - UserDetailsServiceAutoConfiguration.class, EndpointAutoConfiguration.class, - WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class)); + .withUserConfiguration(BaseConfiguration.class, SecurityConfiguration.class) + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, SecurityAutoConfiguration.class, + UserDetailsServiceAutoConfiguration.class, EndpointAutoConfiguration.class, + WebEndpointAutoConfiguration.class, ManagementContextAutoConfiguration.class)); } @@ -100,9 +107,12 @@ abstract class AbstractEndpointRequestIntegrationTests { protected WebTestClient getWebTestClient(AssertableWebApplicationContext context) { int port = context.getSourceApplicationContext(AnnotationConfigServletWebServerApplicationContext.class) - .getWebServer().getPort(); - return WebTestClient.bindToServer().baseUrl("http://localhost:" + port).responseTimeout(Duration.ofMinutes(5)) - .build(); + .getWebServer() + .getPort(); + return WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } String getBasicAuth() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java index 2fc10e076b..d290c7b873 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/JerseyEndpointRequestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,8 +43,11 @@ class JerseyEndpointRequestIntegrationTests extends AbstractEndpointRequestInteg void toLinksWhenApplicationPathSetShouldMatch() { getContextRunner().withPropertyValues("spring.jersey.application-path=/admin").run((context) -> { WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/").exchange().expectStatus() - .isEqualTo(expectedStatusWithTrailingSlash()); + webTestClient.get() + .uri("/admin/actuator/") + .exchange() + .expectStatus() + .isEqualTo(expectedStatusWithTrailingSlash()); webTestClient.get().uri("/admin/actuator").exchange().expectStatus().isOk(); }); } @@ -60,42 +63,65 @@ class JerseyEndpointRequestIntegrationTests extends AbstractEndpointRequestInteg @Test void toAnyEndpointWhenApplicationPathSetShouldMatch() { getContextRunner() - .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/e2").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/e2") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.security.user.password=password", - "management.endpoints.web.exposure.include=se1").run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1/list").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointWhenApplicationPathSetShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.jersey.application-path=/admin", - "spring.security.user.password=password", "management.endpoints.web.exposure.include=se1") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1/list").header("Authorization", getBasicAuth()) - .exchange().expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.jersey.application-path=/admin", "spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Override @@ -106,9 +132,9 @@ class JerseyEndpointRequestIntegrationTests extends AbstractEndpointRequestInteg @Override protected WebApplicationContextRunner createContextRunner() { return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .withUserConfiguration(JerseyEndpointConfiguration.class) - .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .withUserConfiguration(JerseyEndpointConfiguration.class) + .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)); } @Configuration diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java index bcea77524f..94f85b9cfb 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/ManagementWebSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -126,21 +126,21 @@ class ManagementWebSecurityAutoConfigurationTests { @Test void backOffIfOAuth2ResourceServerAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") - .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) - .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://authserver") + .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) + .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); } @Test void backOffIfSaml2RelyingPartyAutoConfigurationPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) - .withPropertyValues( - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.url=https://simplesaml-for-spring-saml/SSOService.php", - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.sign-request=false", - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.entity-id=https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php", - "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.verification.credentials[0].certificate-location=classpath:saml/certificate-location") - .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) - .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); + .withPropertyValues( + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.url=https://simplesaml-for-spring-saml/SSOService.php", + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.sign-request=false", + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.entity-id=https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php", + "spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.verification.credentials[0].certificate-location=classpath:saml/certificate-location") + .run((context) -> assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class) + .doesNotHaveBean(MANAGEMENT_SECURITY_FILTER_CHAIN_BEAN)); } @Test @@ -149,9 +149,10 @@ class ManagementWebSecurityAutoConfigurationTests { SecurityFilterChain testSecurityFilterChain = context.getBean("testSecurityFilterChain", SecurityFilterChain.class); SecurityFilterChain testRemoteDevToolsSecurityFilterChain = context - .getBean("testRemoteDevToolsSecurityFilterChain", SecurityFilterChain.class); + .getBean("testRemoteDevToolsSecurityFilterChain", SecurityFilterChain.class); List orderedSecurityFilterChains = context.getBeanProvider(SecurityFilterChain.class) - .orderedStream().toList(); + .orderedStream() + .toList(); assertThat(orderedSecurityFilterChains).containsExactly(testRemoteDevToolsSecurityFilterChain, testSecurityFilterChain); assertThat(context).doesNotHaveBean(ManagementWebSecurityAutoConfiguration.class); @@ -193,7 +194,8 @@ class ManagementWebSecurityAutoConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { return http.securityMatcher("/**") - .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()).build(); + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java index eb16e1a558..b2d270d43e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/MvcEndpointRequestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,50 +58,73 @@ class MvcEndpointRequestIntegrationTests extends AbstractEndpointRequestIntegrat @Test void toAnyEndpointWhenServletPathSetShouldMatch() { getContextRunner() - .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/e2").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/e2").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/e2") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.security.user.password=password", - "management.endpoints.web.exposure.include=se1").run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/actuator/se1/list").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Test void toAnyEndpointWhenServletPathSetShouldMatchServletEndpoint() { - getContextRunner().withPropertyValues("spring.mvc.servlet.path=/admin", - "spring.security.user.password=password", "management.endpoints.web.exposure.include=se1") - .run((context) -> { - WebTestClient webTestClient = getWebTestClient(context); - webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1").header("Authorization", getBasicAuth()).exchange() - .expectStatus().isOk(); - webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); - webTestClient.get().uri("/admin/actuator/se1/list").header("Authorization", getBasicAuth()) - .exchange().expectStatus().isOk(); - }); + getContextRunner() + .withPropertyValues("spring.mvc.servlet.path=/admin", "spring.security.user.password=password", + "management.endpoints.web.exposure.include=se1") + .run((context) -> { + WebTestClient webTestClient = getWebTestClient(context); + webTestClient.get().uri("/admin/actuator/se1").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + webTestClient.get().uri("/admin/actuator/se1/list").exchange().expectStatus().isUnauthorized(); + webTestClient.get() + .uri("/admin/actuator/se1/list") + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); + }); } @Override protected WebApplicationContextRunner createContextRunner() { return new WebApplicationContextRunner(AnnotationConfigServletWebServerApplicationContext::new) - .withUserConfiguration(WebMvcEndpointConfiguration.class) - .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class)); + .withUserConfiguration(WebMvcEndpointConfiguration.class) + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java index 951252fb35..c10a3c24a7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/security/servlet/SecurityRequestMatchersManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,22 +40,21 @@ import static org.assertj.core.api.Assertions.assertThat; class SecurityRequestMatchersManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)); @Test void configurationConditionalOnWebApplication() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) - .withUserConfiguration(TestMvcConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) + .withUserConfiguration(TestMvcConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); } @Test void configurationConditionalOnRequestMatcherClass() { this.contextRunner - .withClassLoader( - new FilteredClassLoader("org.springframework.security.web.util.matcher.RequestMatcher")) - .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.security.web.util.matcher.RequestMatcher")) + .run((context) -> assertThat(context).doesNotHaveBean(RequestMatcherProvider.class)); } @Test @@ -70,39 +69,39 @@ class SecurityRequestMatchersManagementContextConfigurationTests { @Test void registersRequestMatcherForJerseyProviderIfJerseyPresentAndMvcAbsent() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .withUserConfiguration(TestJerseyConfiguration.class).run((context) -> { - AntPathRequestMatcherProvider matcherProvider = context - .getBean(AntPathRequestMatcherProvider.class); - RequestMatcher requestMatcher = matcherProvider.getRequestMatcher("/example"); - assertThat(requestMatcher).extracting("pattern").isEqualTo("/admin/example"); - }); + .withUserConfiguration(TestJerseyConfiguration.class) + .run((context) -> { + AntPathRequestMatcherProvider matcherProvider = context.getBean(AntPathRequestMatcherProvider.class); + RequestMatcher requestMatcher = matcherProvider.getRequestMatcher("/example"); + assertThat(requestMatcher).extracting("pattern").isEqualTo("/admin/example"); + }); } @Test void mvcRequestMatcherProviderConditionalOnDispatcherServletClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Test void mvcRequestMatcherProviderConditionalOnDispatcherServletPathBean() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Test void jerseyRequestMatcherProviderConditionalOnResourceConfigClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.glassfish.jersey.server.ResourceConfig")) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Test void jerseyRequestMatcherProviderConditionalOnJerseyApplicationPathBean() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) - .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); + .withConfiguration(AutoConfigurations.of(SecurityRequestMatchersManagementContextConfiguration.class)) + .withClassLoader(new FilteredClassLoader("org.springframework.web.servlet.DispatcherServlet")) + .run((context) -> assertThat(context).doesNotHaveBean(AntPathRequestMatcherProvider.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java index 6f30148711..576fe6bbae 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/session/SessionsEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,13 +36,13 @@ import static org.mockito.Mockito.mock; class SessionsEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionsEndpointAutoConfiguration.class)) - .withUserConfiguration(SessionConfiguration.class); + .withConfiguration(AutoConfigurations.of(SessionsEndpointAutoConfiguration.class)) + .withUserConfiguration(SessionConfiguration.class); @Test void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=sessions") - .run((context) -> assertThat(context).hasSingleBean(SessionsEndpoint.class)); + .run((context) -> assertThat(context).hasSingleBean(SessionsEndpoint.class)); } @Test @@ -53,7 +53,7 @@ class SessionsEndpointAutoConfigurationTests { @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.sessions.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SessionsEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java index 163731311d..a7a15a1ccc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/startup/StartupEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class StartupEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(StartupEndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(StartupEndpointAutoConfiguration.class)); @Test void runShouldNotHaveStartupEndpoint() { @@ -44,7 +44,7 @@ class StartupEndpointAutoConfigurationTests { @Test void runWhenMissingAppStartupShouldNotHaveStartupEndpoint() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=startup") - .run((context) -> assertThat(context).doesNotHaveBean(StartupEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(StartupEndpoint.class)); } @Test @@ -54,8 +54,8 @@ class StartupEndpointAutoConfigurationTests { context.setApplicationStartup(new BufferingApplicationStartup(1)); return context; }).withConfiguration(AutoConfigurations.of(StartupEndpointAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include=startup") - .run((context) -> assertThat(context).hasSingleBean(StartupEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=startup") + .run((context) -> assertThat(context).hasSingleBean(StartupEndpoint.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java index a43fcebe23..20b28b81b6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/system/DiskSpaceHealthContributorAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class DiskSpaceHealthContributorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DiskSpaceHealthContributorAutoConfiguration.class, - HealthContributorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(DiskSpaceHealthContributorAutoConfiguration.class, + HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { @@ -46,8 +46,10 @@ class DiskSpaceHealthContributorAutoConfigurationTests { @Test void thresholdMustBePositive() { this.contextRunner.withPropertyValues("management.health.diskspace.threshold=-10MB") - .run((context) -> assertThat(context).hasFailed().getFailure().rootCause() - .hasMessage("threshold must be greater than or equal to 0")); + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .rootCause() + .hasMessage("threshold must be greater than or equal to 0")); } @Test @@ -62,13 +64,13 @@ class DiskSpaceHealthContributorAutoConfigurationTests { @Test void runWhenPathDoesNotExistShouldCreateIndicator() { this.contextRunner.withPropertyValues("management.health.diskspace.path=does/not/exist") - .run((context) -> assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class)); + .run((context) -> assertThat(context).hasSingleBean(DiskSpaceHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.diskspace.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(DiskSpaceHealthIndicator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(DiskSpaceHealthIndicator.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BaggagePropagationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BaggagePropagationIntegrationTests.java index 24deee892c..e98e108330 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BaggagePropagationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BaggagePropagationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -136,9 +136,9 @@ class BaggagePropagationIntegrationTests { @Override public ApplicationContextRunner get() { return new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BraveAutoConfiguration.class)).withPropertyValues( - "management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", - "management.tracing.baggage.correlation.fields=country-code,bp"); + .withConfiguration(AutoConfigurations.of(BraveAutoConfiguration.class)) + .withPropertyValues("management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", + "management.tracing.baggage.correlation.fields=country-code,bp"); } }, @@ -146,10 +146,9 @@ class BaggagePropagationIntegrationTests { @Override public ApplicationContextRunner get() { return new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OpenTelemetryAutoConfiguration.class)) - .withPropertyValues( - "management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", - "management.tracing.baggage.correlation.fields=country-code,bp"); + .withConfiguration(AutoConfigurations.of(OpenTelemetryAutoConfiguration.class)) + .withPropertyValues("management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", + "management.tracing.baggage.correlation.fields=country-code,bp"); } }, @@ -157,10 +156,10 @@ class BaggagePropagationIntegrationTests { @Override public ApplicationContextRunner get() { return new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BraveAutoConfiguration.class)) - .withPropertyValues("management.tracing.propagation.type=B3", - "management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", - "management.tracing.baggage.correlation.fields=country-code,bp"); + .withConfiguration(AutoConfigurations.of(BraveAutoConfiguration.class)) + .withPropertyValues("management.tracing.propagation.type=B3", + "management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", + "management.tracing.baggage.correlation.fields=country-code,bp"); } }, @@ -168,10 +167,10 @@ class BaggagePropagationIntegrationTests { @Override public ApplicationContextRunner get() { return new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OpenTelemetryAutoConfiguration.class)) - .withPropertyValues("management.tracing.propagation.type=B3", - "management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", - "management.tracing.baggage.correlation.fields=country-code,bp"); + .withConfiguration(AutoConfigurations.of(OpenTelemetryAutoConfiguration.class)) + .withPropertyValues("management.tracing.propagation.type=B3", + "management.tracing.baggage.remote-fields=x-vcap-request-id,country-code,bp", + "management.tracing.baggage.correlation.fields=country-code,bp"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfigurationTests.java index 5fdb3624fd..0f7d2e547b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/BraveAutoConfigurationTests.java @@ -60,7 +60,7 @@ import static org.mockito.Mockito.mock; class BraveAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BraveAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BraveAutoConfiguration.class)); @Test void shouldSupplyDefaultBeans() { @@ -115,13 +115,13 @@ class BraveAutoConfigurationTests { @Test void shouldNotSupplyBeansIfBraveIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("brave")) - .run((context) -> assertThat(context).doesNotHaveBean(BraveAutoConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BraveAutoConfiguration.class)); } @Test void shouldNotSupplyBeansIfMicrometerIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("io.micrometer")) - .run((context) -> assertThat(context).doesNotHaveBean(BraveAutoConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BraveAutoConfiguration.class)); } @Test @@ -145,13 +145,13 @@ class BraveAutoConfigurationTests { @Test void shouldNotSupplyBeansIfTracingIsDisabled() { this.contextRunner.withPropertyValues("management.tracing.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(BraveAutoConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BraveAutoConfiguration.class)); } @Test void shouldNotSupplyCorrelationScopeDecoratorIfBaggageDisabled() { this.contextRunner.withPropertyValues("management.tracing.baggage.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean("correlationScopeDecorator")); + .run((context) -> assertThat(context).doesNotHaveBean("correlationScopeDecorator")); } @Test @@ -165,40 +165,45 @@ class BraveAutoConfigurationTests { @Test void shouldSupplyB3WithoutBaggageIfBaggageDisabledAndB3Picked() { - this.contextRunner.withPropertyValues("management.tracing.baggage.enabled=false", - "management.tracing.propagation.type=B3").run((context) -> { - assertThat(context).hasBean("propagationFactory"); - assertThat(context.getBean(Factory.class)).hasToString("B3Propagation"); - assertThat(context).doesNotHaveBean(BaggagePropagation.FactoryBuilder.class); - }); + this.contextRunner + .withPropertyValues("management.tracing.baggage.enabled=false", "management.tracing.propagation.type=B3") + .run((context) -> { + assertThat(context).hasBean("propagationFactory"); + assertThat(context.getBean(Factory.class)).hasToString("B3Propagation"); + assertThat(context).doesNotHaveBean(BaggagePropagation.FactoryBuilder.class); + }); } @Test void shouldNotApplyCorrelationFieldsIfBaggageCorrelationDisabled() { - this.contextRunner.withPropertyValues("management.tracing.baggage.correlation.enabled=false", - "management.tracing.baggage.correlation.fields=alpha,bravo").run((context) -> { - ScopeDecorator scopeDecorator = context.getBean(ScopeDecorator.class); - assertThat(scopeDecorator) - .extracting("fields", InstanceOfAssertFactories.array(SingleCorrelationField[].class)) - .hasSize(2); - }); + this.contextRunner + .withPropertyValues("management.tracing.baggage.correlation.enabled=false", + "management.tracing.baggage.correlation.fields=alpha,bravo") + .run((context) -> { + ScopeDecorator scopeDecorator = context.getBean(ScopeDecorator.class); + assertThat(scopeDecorator) + .extracting("fields", InstanceOfAssertFactories.array(SingleCorrelationField[].class)) + .hasSize(2); + }); } @Test void shouldApplyCorrelationFieldsIfBaggageCorrelationEnabled() { - this.contextRunner.withPropertyValues("management.tracing.baggage.correlation.enabled=true", - "management.tracing.baggage.correlation.fields=alpha,bravo").run((context) -> { - ScopeDecorator scopeDecorator = context.getBean(ScopeDecorator.class); - assertThat(scopeDecorator) - .extracting("fields", InstanceOfAssertFactories.array(SingleCorrelationField[].class)) - .hasSize(4); - }); + this.contextRunner + .withPropertyValues("management.tracing.baggage.correlation.enabled=true", + "management.tracing.baggage.correlation.fields=alpha,bravo") + .run((context) -> { + ScopeDecorator scopeDecorator = context.getBean(ScopeDecorator.class); + assertThat(scopeDecorator) + .extracting("fields", InstanceOfAssertFactories.array(SingleCorrelationField[].class)) + .hasSize(4); + }); } @Test void shouldSupplyMdcCorrelationScopeDecoratorIfBaggageCorrelationDisabled() { this.contextRunner.withPropertyValues("management.tracing.baggage.correlation.enabled=false") - .run((context) -> assertThat(context).hasBean("mdcCorrelationScopeDecoratorBuilder")); + .run((context) -> assertThat(context).hasBean("mdcCorrelationScopeDecoratorBuilder")); } @Test @@ -228,9 +233,9 @@ class BraveAutoConfigurationTests { this.contextRunner.withUserConfiguration(SpanHandlerConfiguration.class).run((context) -> { Tracing tracing = context.getBean(Tracing.class); assertThat(tracing).extracting("tracer.spanHandler.delegate.handlers") - .asInstanceOf(InstanceOfAssertFactories.array(SpanHandler[].class)) - .extracting((handler) -> (Class) handler.getClass()) - .containsExactly(CompositeSpanHandler.class, AdditionalSpanHandler.class); + .asInstanceOf(InstanceOfAssertFactories.array(SpanHandler[].class)) + .extracting((handler) -> (Class) handler.getClass()) + .containsExactly(CompositeSpanHandler.class, AdditionalSpanHandler.class); }); } @@ -238,14 +243,17 @@ class BraveAutoConfigurationTests { void compositeSpanHandlerUsesFilterPredicateAndReportersInOrder() { this.contextRunner.withUserConfiguration(CompositeSpanHandlerComponentsConfiguration.class).run((context) -> { CompositeSpanHandlerComponentsConfiguration components = context - .getBean(CompositeSpanHandlerComponentsConfiguration.class); + .getBean(CompositeSpanHandlerComponentsConfiguration.class); CompositeSpanHandler composite = context.getBean(CompositeSpanHandler.class); - assertThat(composite).extracting("spanFilters").asList().containsExactly(components.filter1, - components.filter2); - assertThat(composite).extracting("filters").asList().containsExactly(components.predicate2, - components.predicate1); - assertThat(composite).extracting("reporters").asList().containsExactly(components.reporter1, - components.reporter3, components.reporter2); + assertThat(composite).extracting("spanFilters") + .asList() + .containsExactly(components.filter1, components.filter2); + assertThat(composite).extracting("filters") + .asList() + .containsExactly(components.predicate2, components.predicate1); + assertThat(composite).extracting("reporters") + .asList() + .containsExactly(components.reporter1, components.reporter3, components.reporter2); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/MicrometerTracingAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/MicrometerTracingAutoConfigurationTests.java index 0684828fe5..6f3c4a373d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/MicrometerTracingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/MicrometerTracingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,32 +43,34 @@ import static org.mockito.Mockito.mock; class MicrometerTracingAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MicrometerTracingAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MicrometerTracingAutoConfiguration.class)); @Test void shouldSupplyBeans() { this.contextRunner.withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(DefaultTracingObservationHandler.class); - assertThat(context).hasSingleBean(PropagatingReceiverTracingObservationHandler.class); - assertThat(context).hasSingleBean(PropagatingSenderTracingObservationHandler.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(DefaultTracingObservationHandler.class); + assertThat(context).hasSingleBean(PropagatingReceiverTracingObservationHandler.class); + assertThat(context).hasSingleBean(PropagatingSenderTracingObservationHandler.class); + }); } @Test @SuppressWarnings("rawtypes") void shouldSupplyBeansInCorrectOrder() { this.contextRunner.withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) - .run((context) -> { - List tracingObservationHandlers = context - .getBeanProvider(TracingObservationHandler.class).orderedStream().toList(); - assertThat(tracingObservationHandlers).hasSize(3); - assertThat(tracingObservationHandlers.get(0)) - .isInstanceOf(PropagatingReceiverTracingObservationHandler.class); - assertThat(tracingObservationHandlers.get(1)) - .isInstanceOf(PropagatingSenderTracingObservationHandler.class); - assertThat(tracingObservationHandlers.get(2)).isInstanceOf(DefaultTracingObservationHandler.class); - }); + .run((context) -> { + List tracingObservationHandlers = context + .getBeanProvider(TracingObservationHandler.class) + .orderedStream() + .toList(); + assertThat(tracingObservationHandlers).hasSize(3); + assertThat(tracingObservationHandlers.get(0)) + .isInstanceOf(PropagatingReceiverTracingObservationHandler.class); + assertThat(tracingObservationHandlers.get(1)) + .isInstanceOf(PropagatingSenderTracingObservationHandler.class); + assertThat(tracingObservationHandlers.get(2)).isInstanceOf(DefaultTracingObservationHandler.class); + }); } @Test @@ -112,11 +114,12 @@ class MicrometerTracingAutoConfigurationTests { @Test void shouldNotSupplyBeansIfTracingIsDisabled() { this.contextRunner.withUserConfiguration(TracerConfiguration.class, PropagatorConfiguration.class) - .withPropertyValues("management.tracing.enabled=false").run((context) -> { - assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); - assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); - assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); - }); + .withPropertyValues("management.tracing.enabled=false") + .run((context) -> { + assertThat(context).doesNotHaveBean(DefaultTracingObservationHandler.class); + assertThat(context).doesNotHaveBean(PropagatingReceiverTracingObservationHandler.class); + assertThat(context).doesNotHaveBean(PropagatingSenderTracingObservationHandler.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfigurationTests.java index 351496970e..091d9cac2d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/OpenTelemetryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ import static org.mockito.Mockito.mock; class OpenTelemetryAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OpenTelemetryAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(OpenTelemetryAutoConfiguration.class)); @Test void shouldSupplyBeans() { @@ -159,13 +159,13 @@ class OpenTelemetryAutoConfigurationTests { @Test void shouldNotSupplySlf4jBaggageEventListenerWhenBaggageCorrelationDisabled() { this.contextRunner.withPropertyValues("management.tracing.baggage.correlation.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(Slf4JBaggageEventListener.class)); + .run((context) -> assertThat(context).doesNotHaveBean(Slf4JBaggageEventListener.class)); } @Test void shouldNotSupplySlf4JBaggageEventListenerWhenBaggageDisabled() { this.contextRunner.withPropertyValues("management.tracing.baggage.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(Slf4JBaggageEventListener.class)); + .run((context) -> assertThat(context).doesNotHaveBean(Slf4JBaggageEventListener.class)); } @Test @@ -178,12 +178,13 @@ class OpenTelemetryAutoConfigurationTests { @Test void shouldSupplyB3PropagationIfPropagationPropertySetAndBaggageDisabled() { - this.contextRunner.withPropertyValues("management.tracing.propagation.type=B3", - "management.tracing.baggage.enabled=false").run((context) -> { - assertThat(context).hasSingleBean(B3Propagator.class); - assertThat(context).hasBean("b3TextMapPropagator"); - assertThat(context).doesNotHaveBean(W3CTraceContextPropagator.class); - }); + this.contextRunner + .withPropertyValues("management.tracing.propagation.type=B3", "management.tracing.baggage.enabled=false") + .run((context) -> { + assertThat(context).hasSingleBean(B3Propagator.class); + assertThat(context).hasBean("b3TextMapPropagator"); + assertThat(context).doesNotHaveBean(W3CTraceContextPropagator.class); + }); } @Test @@ -191,7 +192,7 @@ class OpenTelemetryAutoConfigurationTests { this.contextRunner.withPropertyValues("management.tracing.baggage.remote-fields=foo").run((context) -> { assertThat(context).hasBean("w3cTextMapPropagatorWithBaggage"); Collection allFields = context.getBean("w3cTextMapPropagatorWithBaggage", TextMapPropagator.class) - .fields(); + .fields(); assertThat(allFields).containsExactly("traceparent", "tracestate", "baggage", "foo"); }); } @@ -199,7 +200,7 @@ class OpenTelemetryAutoConfigurationTests { @Test void shouldSupplyW3CPropagationWithoutBaggageWhenDisabled() { this.contextRunner.withPropertyValues("management.tracing.baggage.enabled=false") - .run((context) -> assertThat(context).hasBean("w3cTextMapPropagatorWithoutBaggage")); + .run((context) -> assertThat(context).hasBean("w3cTextMapPropagatorWithoutBaggage")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/prometheus/PrometheusExemplarsAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/prometheus/PrometheusExemplarsAutoConfigurationTests.java index 68c3ffb5cf..2d2f9d35a5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/prometheus/PrometheusExemplarsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/prometheus/PrometheusExemplarsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,36 +45,37 @@ import static org.mockito.Mockito.mock; class PrometheusExemplarsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("management.tracing.sampling.probability=1.0", - "management.metrics.distribution.percentiles-histogram.all=true") - .with(MetricsRun.limitedTo(PrometheusMetricsExportAutoConfiguration.class)) - .withConfiguration(AutoConfigurations.of(PrometheusExemplarsAutoConfiguration.class, - ObservationAutoConfiguration.class, BraveAutoConfiguration.class, - MicrometerTracingAutoConfiguration.class)); + .withPropertyValues("management.tracing.sampling.probability=1.0", + "management.metrics.distribution.percentiles-histogram.all=true") + .with(MetricsRun.limitedTo(PrometheusMetricsExportAutoConfiguration.class)) + .withConfiguration( + AutoConfigurations.of(PrometheusExemplarsAutoConfiguration.class, ObservationAutoConfiguration.class, + BraveAutoConfiguration.class, MicrometerTracingAutoConfiguration.class)); @Test void shouldNotSupplyBeansIfTracingIsDisabled() { this.contextRunner.withPropertyValues("management.tracing.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class)); } @Test void shouldNotSupplyBeansIfPrometheusSupportIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("io.prometheus.client.exemplars")) - .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class)); } @Test void shouldNotSupplyBeansIfMicrometerTracingIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("io.micrometer.tracing")) - .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpanContextSupplier.class)); } @Test void shouldSupplyCustomBeans() { this.contextRunner.withUserConfiguration(CustomConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(SpanContextSupplier.class) - .getBean(SpanContextSupplier.class).isSameAs(CustomConfiguration.SUPPLIER)); + .run((context) -> assertThat(context).hasSingleBean(SpanContextSupplier.class) + .getBean(SpanContextSupplier.class) + .isSameAs(CustomConfiguration.SUPPLIER)); } @Test @@ -85,8 +86,9 @@ class PrometheusExemplarsAutoConfigurationTests { Observation.start("test.observation", observationRegistry).stop(); PrometheusMeterRegistry prometheusMeterRegistry = context.getBean(PrometheusMeterRegistry.class); String openMetricsOutput = prometheusMeterRegistry.scrape(TextFormat.CONTENT_TYPE_OPENMETRICS_100); - assertThat(openMetricsOutput).contains("test_observation_seconds_bucket").containsOnlyOnce("trace_id=") - .containsOnlyOnce("span_id="); + assertThat(openMetricsOutput).contains("test_observation_seconds_bucket") + .containsOnlyOnce("trace_id=") + .containsOnlyOnce("span_id="); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/wavefront/WavefrontTracingAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/wavefront/WavefrontTracingAutoConfigurationTests.java index 95ed8646fd..a75d692772 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/wavefront/WavefrontTracingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/wavefront/WavefrontTracingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -72,46 +72,48 @@ class WavefrontTracingAutoConfigurationTests { @Test void shouldNotSupplyBeansIfMicrometerReporterWavefrontIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("io.micrometer.tracing.reporter.wavefront")) - .withUserConfiguration(WavefrontSenderConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean(WavefrontSpanHandler.class); - assertThat(context).doesNotHaveBean(SpanMetrics.class); - assertThat(context).doesNotHaveBean(WavefrontBraveSpanHandler.class); - assertThat(context).doesNotHaveBean(WavefrontOtelSpanExporter.class); - }); + .withUserConfiguration(WavefrontSenderConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(WavefrontSpanHandler.class); + assertThat(context).doesNotHaveBean(SpanMetrics.class); + assertThat(context).doesNotHaveBean(WavefrontBraveSpanHandler.class); + assertThat(context).doesNotHaveBean(WavefrontOtelSpanExporter.class); + }); } @Test void shouldNotSupplyBeansIfTracingIsDisabled() { this.contextRunner.withPropertyValues("management.tracing.enabled=false") - .withUserConfiguration(WavefrontSenderConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean(WavefrontSpanHandler.class); - assertThat(context).doesNotHaveBean(SpanMetrics.class); - assertThat(context).doesNotHaveBean(WavefrontBraveSpanHandler.class); - assertThat(context).doesNotHaveBean(WavefrontOtelSpanExporter.class); - }); + .withUserConfiguration(WavefrontSenderConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(WavefrontSpanHandler.class); + assertThat(context).doesNotHaveBean(SpanMetrics.class); + assertThat(context).doesNotHaveBean(WavefrontBraveSpanHandler.class); + assertThat(context).doesNotHaveBean(WavefrontOtelSpanExporter.class); + }); } @Test void shouldSupplyMeterRegistrySpanMetricsIfMeterRegistryIsAvailable() { this.contextRunner.withUserConfiguration(WavefrontSenderConfiguration.class, MeterRegistryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(SpanMetrics.class); - assertThat(context).hasSingleBean(MeterRegistrySpanMetrics.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(SpanMetrics.class); + assertThat(context).hasSingleBean(MeterRegistrySpanMetrics.class); + }); } @Test void shouldNotSupplyWavefrontBraveSpanHandlerIfBraveIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("brave")) - .withUserConfiguration(WavefrontSenderConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(WavefrontBraveSpanHandler.class)); + .withUserConfiguration(WavefrontSenderConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(WavefrontBraveSpanHandler.class)); } @Test void shouldNotSupplyWavefrontOtelSpanExporterIfOtelIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("io.opentelemetry.sdk.trace")) - .withUserConfiguration(WavefrontSenderConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(WavefrontOtelSpanExporter.class)); + .withUserConfiguration(WavefrontSenderConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(WavefrontOtelSpanExporter.class)); } @Test @@ -128,45 +130,46 @@ class WavefrontTracingAutoConfigurationTests { @Test void shouldUseSpringApplicationNameForServiceName() { this.contextRunner.withUserConfiguration(WavefrontSenderConfiguration.class) - .withPropertyValues("spring.application.name=super-service").run((context) -> { - ApplicationTags applicationTags = context.getBean(ApplicationTags.class); - assertThat(applicationTags.getApplication()).isEqualTo("unnamed_application"); - assertThat(applicationTags.getService()).isEqualTo("super-service"); - }); + .withPropertyValues("spring.application.name=super-service") + .run((context) -> { + ApplicationTags applicationTags = context.getBean(ApplicationTags.class); + assertThat(applicationTags.getApplication()).isEqualTo("unnamed_application"); + assertThat(applicationTags.getService()).isEqualTo("super-service"); + }); } @Test void shouldHonorConfigProperties() { this.contextRunner.withUserConfiguration(WavefrontSenderConfiguration.class) - .withPropertyValues("spring.application.name=ignored", - "management.wavefront.application.name=super-application", - "management.wavefront.application.service-name=super-service", - "management.wavefront.application.cluster-name=super-cluster", - "management.wavefront.application.shard-name=super-shard") - .run((context) -> { - ApplicationTags applicationTags = context.getBean(ApplicationTags.class); - assertThat(applicationTags.getApplication()).isEqualTo("super-application"); - assertThat(applicationTags.getService()).isEqualTo("super-service"); - assertThat(applicationTags.getCluster()).isEqualTo("super-cluster"); - assertThat(applicationTags.getShard()).isEqualTo("super-shard"); - }); + .withPropertyValues("spring.application.name=ignored", + "management.wavefront.application.name=super-application", + "management.wavefront.application.service-name=super-service", + "management.wavefront.application.cluster-name=super-cluster", + "management.wavefront.application.shard-name=super-shard") + .run((context) -> { + ApplicationTags applicationTags = context.getBean(ApplicationTags.class); + assertThat(applicationTags.getApplication()).isEqualTo("super-application"); + assertThat(applicationTags.getService()).isEqualTo("super-service"); + assertThat(applicationTags.getCluster()).isEqualTo("super-cluster"); + assertThat(applicationTags.getShard()).isEqualTo("super-shard"); + }); } @Test void shouldBackOffOnCustomBeans() { this.contextRunner.withUserConfiguration(WavefrontSenderConfiguration.class, CustomConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("customApplicationTags"); - assertThat(context).hasSingleBean(ApplicationTags.class); - assertThat(context).hasBean("customWavefrontSpanHandler"); - assertThat(context).hasSingleBean(WavefrontSpanHandler.class); - assertThat(context).hasBean("customSpanMetrics"); - assertThat(context).hasSingleBean(SpanMetrics.class); - assertThat(context).hasBean("customWavefrontBraveSpanHandler"); - assertThat(context).hasSingleBean(WavefrontBraveSpanHandler.class); - assertThat(context).hasBean("customWavefrontOtelSpanExporter"); - assertThat(context).hasSingleBean(WavefrontOtelSpanExporter.class); - }); + .run((context) -> { + assertThat(context).hasBean("customApplicationTags"); + assertThat(context).hasSingleBean(ApplicationTags.class); + assertThat(context).hasBean("customWavefrontSpanHandler"); + assertThat(context).hasSingleBean(WavefrontSpanHandler.class); + assertThat(context).hasBean("customSpanMetrics"); + assertThat(context).hasSingleBean(SpanMetrics.class); + assertThat(context).hasBean("customWavefrontBraveSpanHandler"); + assertThat(context).hasSingleBean(WavefrontBraveSpanHandler.class); + assertThat(context).hasBean("customWavefrontOtelSpanExporter"); + assertThat(context).hasSingleBean(WavefrontOtelSpanExporter.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationIntegrationTests.java index ec876489c5..b47588d2d3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,25 +48,25 @@ class ZipkinAutoConfigurationIntegrationTests { @Test void zipkinsUseOfRestTemplateDoesNotCauseACycle() { configure(new WebApplicationContextRunner()) - .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void zipkinsUseOfWebClientDoesNotCauseACycle() { configure(new ReactiveWebApplicationContextRunner()) - .withConfiguration(AutoConfigurations.of(WebClientAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withConfiguration(AutoConfigurations.of(WebClientAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } , C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider> AbstractApplicationContextRunner configure( AbstractApplicationContextRunner runner) { return runner - .withConfiguration(AutoConfigurations.of(MicrometerTracingAutoConfiguration.class, - ObservationAutoConfiguration.class, BraveAutoConfiguration.class, ZipkinAutoConfiguration.class, - HttpClientObservationsAutoConfiguration.class, MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(URLConnectionSender.class)); + .withConfiguration(AutoConfigurations.of(MicrometerTracingAutoConfiguration.class, + ObservationAutoConfiguration.class, BraveAutoConfiguration.class, ZipkinAutoConfiguration.class, + HttpClientObservationsAutoConfiguration.class, MetricsAutoConfiguration.class, + SimpleMetricsExportAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(URLConnectionSender.class)); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationTests.java index a21b97573b..f1c33fc406 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ZipkinAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ZipkinAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ZipkinAutoConfiguration.class)); @Test void shouldSupplyBeans() { @@ -47,7 +47,7 @@ class ZipkinAutoConfigurationTests { @Test void shouldNotSupplyBeansIfZipkinReporterIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("zipkin2.reporter")) - .run((context) -> assertThat(context).doesNotHaveBean(BytesEncoder.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BytesEncoder.class)); } @Test @@ -61,7 +61,7 @@ class ZipkinAutoConfigurationTests { @Test void shouldNotSupplyBeansIfTracingIsDisabled() { this.contextRunner.withPropertyValues("management.tracing.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(BytesEncoder.class)); + .run((context) -> assertThat(context).doesNotHaveBean(BytesEncoder.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsBraveConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsBraveConfigurationTests.java index 2771ec7de8..735cd00d0c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsBraveConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsBraveConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,12 +40,12 @@ import static org.mockito.Mockito.mock; class ZipkinConfigurationsBraveConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BraveConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BraveConfiguration.class)); @Test void shouldSupplyBeans() { this.contextRunner.withUserConfiguration(ReporterConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ZipkinSpanHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(ZipkinSpanHandler.class)); } @Test @@ -56,27 +56,27 @@ class ZipkinConfigurationsBraveConfigurationTests { @Test void shouldNotSupplyIfZipkinReporterBraveIsNotOnClasspath() { this.contextRunner.withClassLoader(new FilteredClassLoader("zipkin2.reporter.brave")) - .withUserConfiguration(ReporterConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ZipkinSpanHandler.class)); + .withUserConfiguration(ReporterConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(ZipkinSpanHandler.class)); } @Test void shouldBackOffOnCustomBeans() { this.contextRunner.withUserConfiguration(ReporterConfiguration.class, CustomConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("customZipkinSpanHandler"); - assertThat(context).hasSingleBean(ZipkinSpanHandler.class); - }); + .run((context) -> { + assertThat(context).hasBean("customZipkinSpanHandler"); + assertThat(context).hasSingleBean(ZipkinSpanHandler.class); + }); } @Test void shouldSupplyZipkinSpanHandlerWithCustomSpanHandler() { this.contextRunner.withUserConfiguration(ReporterConfiguration.class, CustomSpanHandlerConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("customSpanHandler"); - assertThat(context).hasSingleBean(ZipkinSpanHandler.class); - }); + .run((context) -> { + assertThat(context).hasBean("customSpanHandler"); + assertThat(context).hasSingleBean(ZipkinSpanHandler.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsOpenTelemetryConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsOpenTelemetryConfigurationTests.java index 14ba3e413d..c3ef5f99c3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsOpenTelemetryConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsOpenTelemetryConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,12 +41,12 @@ import static org.assertj.core.api.Assertions.assertThat; class ZipkinConfigurationsOpenTelemetryConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BaseConfiguration.class, OpenTelemetryConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BaseConfiguration.class, OpenTelemetryConfiguration.class)); @Test void shouldSupplyBeans() { this.contextRunner.withUserConfiguration(SenderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ZipkinSpanExporter.class)); + .run((context) -> assertThat(context).hasSingleBean(ZipkinSpanExporter.class)); } @Test @@ -57,8 +57,8 @@ class ZipkinConfigurationsOpenTelemetryConfigurationTests { @Test void shouldNotSupplyZipkinSpanExporterIfNotOnClasspath() { this.contextRunner.withClassLoader(new FilteredClassLoader("io.opentelemetry.exporter.zipkin")) - .withUserConfiguration(SenderConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ZipkinSpanExporter.class)); + .withUserConfiguration(SenderConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(ZipkinSpanExporter.class)); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsReporterConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsReporterConfigurationTests.java index a94c44ee4f..4f5bb4c8e2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsReporterConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsReporterConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,12 +41,12 @@ import static org.mockito.Mockito.mock; class ZipkinConfigurationsReporterConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BaseConfiguration.class, ReporterConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BaseConfiguration.class, ReporterConfiguration.class)); @Test void shouldSupplyBeans() { this.contextRunner.withUserConfiguration(SenderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Reporter.class)); + .run((context) -> assertThat(context).hasSingleBean(Reporter.class)); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsSenderConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsSenderConfigurationTests.java index 8be392a7b6..3dfeeb37af 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsSenderConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinConfigurationsSenderConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,13 +51,13 @@ import static org.mockito.Mockito.mock; class ZipkinConfigurationsSenderConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SenderConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SenderConfiguration.class)); private final ReactiveWebApplicationContextRunner reactiveContextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SenderConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SenderConfiguration.class)); private final WebApplicationContextRunner servletContextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SenderConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SenderConfiguration.class)); @Test void shouldSupplyBeans() { @@ -71,63 +71,69 @@ class ZipkinConfigurationsSenderConfigurationTests { @Test void shouldPreferWebClientSenderIfWebApplicationIsReactiveAndUrlSenderIsNotAvailable() { this.reactiveContextRunner.withUserConfiguration(RestTemplateConfiguration.class, WebClientConfiguration.class) - .withClassLoader(new FilteredClassLoader("zipkin2.reporter.urlconnection")).run((context) -> { - assertThat(context).doesNotHaveBean(URLConnectionSender.class); - assertThat(context).hasSingleBean(Sender.class); - assertThat(context).hasSingleBean(ZipkinWebClientSender.class); - then(context.getBean(ZipkinWebClientBuilderCustomizer.class)).should() - .customize(ArgumentMatchers.any()); - }); + .withClassLoader(new FilteredClassLoader("zipkin2.reporter.urlconnection")) + .run((context) -> { + assertThat(context).doesNotHaveBean(URLConnectionSender.class); + assertThat(context).hasSingleBean(Sender.class); + assertThat(context).hasSingleBean(ZipkinWebClientSender.class); + then(context.getBean(ZipkinWebClientBuilderCustomizer.class)).should() + .customize(ArgumentMatchers.any()); + }); } @Test void shouldPreferWebClientSenderIfWebApplicationIsServletAndUrlSenderIsNotAvailable() { this.servletContextRunner.withUserConfiguration(RestTemplateConfiguration.class, WebClientConfiguration.class) - .withClassLoader(new FilteredClassLoader("zipkin2.reporter.urlconnection")).run((context) -> { - assertThat(context).doesNotHaveBean(URLConnectionSender.class); - assertThat(context).hasSingleBean(Sender.class); - assertThat(context).hasSingleBean(ZipkinWebClientSender.class); - }); + .withClassLoader(new FilteredClassLoader("zipkin2.reporter.urlconnection")) + .run((context) -> { + assertThat(context).doesNotHaveBean(URLConnectionSender.class); + assertThat(context).hasSingleBean(Sender.class); + assertThat(context).hasSingleBean(ZipkinWebClientSender.class); + }); } @Test void shouldPreferWebClientInNonWebApplicationAndUrlConnectionSenderIsNotAvailable() { this.contextRunner.withUserConfiguration(RestTemplateConfiguration.class, WebClientConfiguration.class) - .withClassLoader(new FilteredClassLoader("zipkin2.reporter.urlconnection")).run((context) -> { - assertThat(context).doesNotHaveBean(URLConnectionSender.class); - assertThat(context).hasSingleBean(Sender.class); - assertThat(context).hasSingleBean(ZipkinWebClientSender.class); - }); + .withClassLoader(new FilteredClassLoader("zipkin2.reporter.urlconnection")) + .run((context) -> { + assertThat(context).doesNotHaveBean(URLConnectionSender.class); + assertThat(context).hasSingleBean(Sender.class); + assertThat(context).hasSingleBean(ZipkinWebClientSender.class); + }); } @Test void willUseRestTemplateInNonWebApplicationIfUrlConnectionSenderAndWebClientAreNotAvailable() { this.contextRunner.withUserConfiguration(RestTemplateConfiguration.class) - .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)).run((context) -> { - assertThat(context).doesNotHaveBean(URLConnectionSender.class); - assertThat(context).hasSingleBean(Sender.class); - assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); - }); + .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(URLConnectionSender.class); + assertThat(context).hasSingleBean(Sender.class); + assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); + }); } @Test void willUseRestTemplateInServletWebApplicationIfUrlConnectionSenderAndWebClientNotAvailable() { this.servletContextRunner.withUserConfiguration(RestTemplateConfiguration.class) - .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)).run((context) -> { - assertThat(context).doesNotHaveBean(URLConnectionSender.class); - assertThat(context).hasSingleBean(Sender.class); - assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); - }); + .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(URLConnectionSender.class); + assertThat(context).hasSingleBean(Sender.class); + assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); + }); } @Test void willUseRestTemplateInReactiveWebApplicationIfUrlConnectionSenderAndWebClientAreNotAvailable() { this.reactiveContextRunner.withUserConfiguration(RestTemplateConfiguration.class) - .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)).run((context) -> { - assertThat(context).doesNotHaveBean(URLConnectionSender.class); - assertThat(context).hasSingleBean(Sender.class); - assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); - }); + .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(URLConnectionSender.class); + assertThat(context).hasSingleBean(Sender.class); + assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); + }); } @Test @@ -152,17 +158,17 @@ class ZipkinConfigurationsSenderConfigurationTests { try (MockWebServer mockWebServer = new MockWebServer()) { mockWebServer.enqueue(new MockResponse().setResponseCode(204)); this.reactiveContextRunner - .withPropertyValues("management.zipkin.tracing.endpoint=" + mockWebServer.url("/")) - .withUserConfiguration(RestTemplateConfiguration.class) - .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)) - .run((context) -> { - assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); - ZipkinRestTemplateSender sender = context.getBean(ZipkinRestTemplateSender.class); - sender.sendSpans("spans".getBytes(StandardCharsets.UTF_8)).execute(); - RecordedRequest recordedRequest = mockWebServer.takeRequest(1, TimeUnit.SECONDS); - assertThat(recordedRequest).isNotNull(); - assertThat(recordedRequest.getHeaders().get("x-dummy")).isEqualTo("dummy"); - }); + .withPropertyValues("management.zipkin.tracing.endpoint=" + mockWebServer.url("/")) + .withUserConfiguration(RestTemplateConfiguration.class) + .withClassLoader(new FilteredClassLoader(URLConnectionSender.class, WebClient.class)) + .run((context) -> { + assertThat(context).hasSingleBean(ZipkinRestTemplateSender.class); + ZipkinRestTemplateSender sender = context.getBean(ZipkinRestTemplateSender.class); + sender.sendSpans("spans".getBytes(StandardCharsets.UTF_8)).execute(); + RecordedRequest recordedRequest = mockWebServer.takeRequest(1, TimeUnit.SECONDS); + assertThat(recordedRequest).isNotNull(); + assertThat(recordedRequest.getHeaders().get("x-dummy")).isEqualTo("dummy"); + }); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinRestTemplateSenderTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinRestTemplateSenderTests.java index e28c6df279..ec945ac3da 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinRestTemplateSenderTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinRestTemplateSenderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,15 +67,18 @@ class ZipkinRestTemplateSenderTests extends ZipkinHttpSenderTests { @Test void checkShouldSendEmptySpanList() { - this.mockServer.expect(requestTo(ZIPKIN_URL)).andExpect(method(HttpMethod.POST)) - .andExpect(content().string("[]")).andRespond(withStatus(HttpStatus.ACCEPTED)); + this.mockServer.expect(requestTo(ZIPKIN_URL)) + .andExpect(method(HttpMethod.POST)) + .andExpect(content().string("[]")) + .andRespond(withStatus(HttpStatus.ACCEPTED)); assertThat(this.sut.check()).isEqualTo(CheckResult.OK); } @Test void checkShouldNotRaiseException() { - this.mockServer.expect(requestTo(ZIPKIN_URL)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + this.mockServer.expect(requestTo(ZIPKIN_URL)) + .andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); CheckResult result = this.sut.check(); assertThat(result.ok()).isFalse(); assertThat(result.error()).hasMessageContaining("500 Internal Server Error"); @@ -84,17 +87,20 @@ class ZipkinRestTemplateSenderTests extends ZipkinHttpSenderTests { @ParameterizedTest @ValueSource(booleans = { true, false }) void sendSpansShouldSendSpansToZipkin(boolean async) throws IOException { - this.mockServer.expect(requestTo(ZIPKIN_URL)).andExpect(method(HttpMethod.POST)) - .andExpect(content().contentType("application/json")).andExpect(content().string("[span1,span2]")) - .andRespond(withStatus(HttpStatus.ACCEPTED)); + this.mockServer.expect(requestTo(ZIPKIN_URL)) + .andExpect(method(HttpMethod.POST)) + .andExpect(content().contentType("application/json")) + .andExpect(content().string("[span1,span2]")) + .andRespond(withStatus(HttpStatus.ACCEPTED)); makeRequest(List.of(toByteArray("span1"), toByteArray("span2")), async); } @ParameterizedTest @ValueSource(booleans = { true, false }) void sendSpansShouldHandleHttpFailures(boolean async) { - this.mockServer.expect(requestTo(ZIPKIN_URL)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + this.mockServer.expect(requestTo(ZIPKIN_URL)) + .andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); if (async) { CallbackResult callbackResult = makeAsyncRequest(Collections.emptyList()); assertThat(callbackResult.success()).isFalse(); @@ -102,7 +108,7 @@ class ZipkinRestTemplateSenderTests extends ZipkinHttpSenderTests { } else { assertThatThrownBy(() -> makeSyncRequest(Collections.emptyList())) - .hasMessageContaining("500 Internal Server Error"); + .hasMessageContaining("500 Internal Server Error"); } } @@ -112,10 +118,13 @@ class ZipkinRestTemplateSenderTests extends ZipkinHttpSenderTests { String uncompressed = "a".repeat(10000); // This is gzip compressed 10000 times 'a' byte[] compressed = Base64.getDecoder() - .decode("H4sIAAAAAAAA/+3BMQ0AAAwDIKFLj/k3UR8NcA8AAAAAAAAAAAADUsAZfeASJwAA"); - this.mockServer.expect(requestTo(ZIPKIN_URL)).andExpect(method(HttpMethod.POST)) - .andExpect(header("Content-Encoding", "gzip")).andExpect(content().contentType("application/json")) - .andExpect(content().bytes(compressed)).andRespond(withStatus(HttpStatus.ACCEPTED)); + .decode("H4sIAAAAAAAA/+3BMQ0AAAwDIKFLj/k3UR8NcA8AAAAAAAAAAAADUsAZfeASJwAA"); + this.mockServer.expect(requestTo(ZIPKIN_URL)) + .andExpect(method(HttpMethod.POST)) + .andExpect(header("Content-Encoding", "gzip")) + .andExpect(content().contentType("application/json")) + .andExpect(content().bytes(compressed)) + .andRespond(withStatus(HttpStatus.ACCEPTED)); makeRequest(List.of(toByteArray(uncompressed)), async); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSenderTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSenderTests.java index cdfef2425b..dc19d987ca 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSenderTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/tracing/zipkin/ZipkinWebClientSenderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -113,7 +113,7 @@ class ZipkinWebClientSenderTests extends ZipkinHttpSenderTests { } else { assertThatThrownBy(() -> makeSyncRequest(Collections.emptyList())) - .hasMessageContaining("500 Internal Server Error"); + .hasMessageContaining("500 Internal Server Error"); } requestAssertions((request) -> assertThat(request.getMethod()).isEqualTo("POST")); @@ -125,7 +125,7 @@ class ZipkinWebClientSenderTests extends ZipkinHttpSenderTests { String uncompressed = "a".repeat(10000); // This is gzip compressed 10000 times 'a' byte[] compressed = Base64.getDecoder() - .decode("H4sIAAAAAAAA/+3BMQ0AAAwDIKFLj/k3UR8NcA8AAAAAAAAAAAADUsAZfeASJwAA"); + .decode("H4sIAAAAAAAA/+3BMQ0AAAwDIKFLj/k3UR8NcA8AAAAAAAAAAAADUsAZfeASJwAA"); mockBackEnd.enqueue(new MockResponse()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontAutoConfigurationTests.java index 702f675241..f5229a7c61 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class WavefrontAutoConfigurationTests { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WavefrontAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WavefrontAutoConfiguration.class)); @Test void wavefrontApplicationTagsWhenHasUserBeanBacksOff() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontPropertiesTests.java index b5bcbd1e21..02d1ce3b77 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class WavefrontPropertiesTests { sut.setApiToken(null); assertThat(sut.getEffectiveUri()).isEqualTo(URI.create("http://localhost:2878")); assertThatThrownBy(sut::getApiTokenOrThrow).isInstanceOf(InvalidConfigurationPropertyValueException.class) - .hasMessageContaining("management.wavefront.api-token"); + .hasMessageContaining("management.wavefront.api-token"); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontSenderConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontSenderConfigurationTests.java index 3a67b51c24..a75203e4fe 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontSenderConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/wavefront/WavefrontSenderConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,12 +40,12 @@ import static org.mockito.Mockito.mock; class WavefrontSenderConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WavefrontSenderConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WavefrontSenderConfiguration.class)); @Test void shouldNotFailIfWavefrontIsMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader("com.wavefront")) - .run(((context) -> assertThat(context).doesNotHaveBean(WavefrontSender.class))); + .run(((context) -> assertThat(context).doesNotHaveBean(WavefrontSender.class))); } @Test @@ -59,9 +59,9 @@ class WavefrontSenderConfigurationTests { WavefrontProperties properties = new WavefrontProperties(); WavefrontSender sender = context.getBean(WavefrontSender.class); assertThat(sender) - .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) - .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()) - .isEqualTo(properties.getSender().getMaxQueueSize())); + .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) + .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()) + .isEqualTo(properties.getSender().getMaxQueueSize())); assertThat(sender).hasFieldOrPropertyWithValue("batchSize", properties.getSender().getBatchSize()); assertThat(sender).hasFieldOrPropertyWithValue("messageSizeBytes", (int) properties.getSender().getMessageSize().toBytes()); @@ -70,22 +70,23 @@ class WavefrontSenderConfigurationTests { @Test void configureWavefrontSender() { - this.contextRunner.withPropertyValues("management.wavefront.api-token=abcde", - "management.wavefront.sender.batch-size=50", "management.wavefront.sender.max-queue-size=100", - "management.wavefront.sender.message-size=1KB").run((context) -> { - WavefrontSender sender = context.getBean(WavefrontSender.class); - assertThat(sender).hasFieldOrPropertyWithValue("batchSize", 50); - assertThat(sender) - .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) - .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()).isEqualTo(100)); - assertThat(sender).hasFieldOrPropertyWithValue("messageSizeBytes", 1024); - }); + this.contextRunner + .withPropertyValues("management.wavefront.api-token=abcde", "management.wavefront.sender.batch-size=50", + "management.wavefront.sender.max-queue-size=100", "management.wavefront.sender.message-size=1KB") + .run((context) -> { + WavefrontSender sender = context.getBean(WavefrontSender.class); + assertThat(sender).hasFieldOrPropertyWithValue("batchSize", 50); + assertThat(sender) + .extracting("metricsBuffer", as(InstanceOfAssertFactories.type(LinkedBlockingQueue.class))) + .satisfies((queue) -> assertThat(queue.remainingCapacity() + queue.size()).isEqualTo(100)); + assertThat(sender).hasFieldOrPropertyWithValue("messageSizeBytes", 1024); + }); } @Test void allowsWavefrontSenderToBeCustomized() { this.contextRunner.withUserConfiguration(CustomSenderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(WavefrontSender.class).hasBean("customSender")); + .run((context) -> assertThat(context).hasSingleBean(WavefrontSender.class).hasBean("customSender")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java index 46a2b05fb1..865e966ecc 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java @@ -34,7 +34,7 @@ class ManagementContextConfigurationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultManagementContextConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultManagementContextConfiguration.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", true); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesAutoConfigurationTests.java index 7ae1dc4149..5f88a821e5 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HttpExchangesAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpExchangesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpExchangesAutoConfiguration.class)); @Test void autoConfigurationIsDisabledByDefault() { @@ -63,37 +63,38 @@ class HttpExchangesAutoConfigurationTests { @Test void usesUserProvidedWebFilterWhenReactiveContext() { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpExchangesAutoConfiguration.class)) - .withUserConfiguration(CustomHttpExchangesRepositoryConfiguration.class) - .withUserConfiguration(CustomWebFilterConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(HttpExchangesWebFilter.class); - assertThat(context.getBean(HttpExchangesWebFilter.class)) - .isInstanceOf(CustomHttpExchangesWebFilter.class); - }); + .withConfiguration(AutoConfigurations.of(HttpExchangesAutoConfiguration.class)) + .withUserConfiguration(CustomHttpExchangesRepositoryConfiguration.class) + .withUserConfiguration(CustomWebFilterConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(HttpExchangesWebFilter.class); + assertThat(context.getBean(HttpExchangesWebFilter.class)) + .isInstanceOf(CustomHttpExchangesWebFilter.class); + }); } @Test void configuresServletFilter() { this.contextRunner.withUserConfiguration(CustomHttpExchangesRepositoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(HttpExchangesFilter.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpExchangesFilter.class)); } @Test void usesUserProvidedServletFilter() { this.contextRunner.withUserConfiguration(CustomHttpExchangesRepositoryConfiguration.class) - .withUserConfiguration(CustomFilterConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(HttpExchangesFilter.class); - assertThat(context.getBean(HttpExchangesFilter.class)) - .isInstanceOf(CustomHttpExchangesFilter.class); - }); + .withUserConfiguration(CustomFilterConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(HttpExchangesFilter.class); + assertThat(context.getBean(HttpExchangesFilter.class)).isInstanceOf(CustomHttpExchangesFilter.class); + }); } @Test void backsOffWhenNotRecording() { this.contextRunner.withUserConfiguration(CustomHttpExchangesRepositoryConfiguration.class) - .withPropertyValues("management.httpexchanges.recording.enabled=false") - .run((context) -> assertThat(context).doesNotHaveBean(InMemoryHttpExchangeRepository.class) - .doesNotHaveBean(HttpExchangesFilter.class)); + .withPropertyValues("management.httpexchanges.recording.enabled=false") + .run((context) -> assertThat(context).doesNotHaveBean(InMemoryHttpExchangeRepository.class) + .doesNotHaveBean(HttpExchangesFilter.class)); } static class CustomHttpExchangesRepository implements HttpExchangeRepository { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesEndpointAutoConfigurationTests.java index 98a692e2a9..f4099dc915 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/exchanges/HttpExchangesEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,28 +41,28 @@ class HttpExchangesEndpointAutoConfigurationTests { @Test void runWhenRepositoryBeanAvailableShouldHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpExchangeRepositoryConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=httpexchanges") - .run((context) -> assertThat(context).hasSingleBean(HttpExchangesEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=httpexchanges") + .run((context) -> assertThat(context).hasSingleBean(HttpExchangesEndpoint.class)); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpExchangeRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(HttpExchangesEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HttpExchangesEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withUserConfiguration(HttpExchangeRepositoryConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=httpexchanges") - .withPropertyValues("management.endpoint.httpexchanges.enabled:false") - .run((context) -> assertThat(context).doesNotHaveBean(HttpExchangesEndpoint.class)); + .withPropertyValues("management.endpoints.web.exposure.include=httpexchanges") + .withPropertyValues("management.endpoint.httpexchanges.enabled:false") + .run((context) -> assertThat(context).doesNotHaveBean(HttpExchangesEndpoint.class)); } @Test void endpointBacksOffWhenRepositoryIsNotAvailable() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=httpexchanges") - .run((context) -> assertThat(context).doesNotHaveBean(HttpExchangesEndpoint.class)); + .run((context) -> assertThat(context).doesNotHaveBean(HttpExchangesEndpoint.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java index cca272741d..92a0704cff 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseyChildManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,20 +44,20 @@ import static org.mockito.Mockito.mock; class JerseyChildManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(JerseyChildManagementContextConfiguration.class); + .withUserConfiguration(JerseyChildManagementContextConfiguration.class); @Test void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test @@ -88,7 +88,7 @@ class JerseyChildManagementContextConfigurationTests { assertThat(context).hasSingleBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class); ManagementContextResourceConfigCustomizer customizer = context - .getBean(ManagementContextResourceConfigCustomizer.class); + .getBean(ManagementContextResourceConfigCustomizer.class); then(customizer).should().customize(config); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java index e8c8120d35..a9f28fd75e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/jersey/JerseySameManagementContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,20 +44,20 @@ import static org.mockito.Mockito.mock; class JerseySameManagementContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); @Test void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) - .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test @@ -98,7 +98,7 @@ class JerseySameManagementContextConfigurationTests { assertThat(context).hasSingleBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class); ManagementContextResourceConfigCustomizer customizer = context - .getBean(ManagementContextResourceConfigCustomizer.class); + .getBean(ManagementContextResourceConfigCustomizer.class); then(customizer).should().customize(config); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java index 36f70d28a6..eec4f9671b 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/mappings/MappingsEndpointAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,30 +43,31 @@ class MappingsEndpointAutoConfigurationTests { @Test void whenEndpointIsUnavailableThenEndpointAndDescriptionProvidersAreNotCreated() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) - .run((context) -> { - assertThat(context).doesNotHaveBean(MappingsEndpoint.class); - assertThat(context).doesNotHaveBean(MappingDescriptionProvider.class); - }); + .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(MappingsEndpoint.class); + assertThat(context).doesNotHaveBean(MappingDescriptionProvider.class); + }); } @Test void whenEndpointIsAvailableThenEndpointAndDescriptionProvidersAreCreated() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, - JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, - WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, - WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) - .withPropertyValues("management.endpoints.web.exposure.include=mappings").run((context) -> { - assertThat(context).hasSingleBean(MappingsEndpoint.class); - assertThat(context.getBeansOfType(MappingDescriptionProvider.class)).hasSize(3); - }); + .withConfiguration(AutoConfigurations.of(MappingsEndpointAutoConfiguration.class, + JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + WebMvcAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + EndpointAutoConfiguration.class, WebEndpointAutoConfiguration.class, + WebMvcEndpointManagementContextConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) + .withPropertyValues("management.endpoints.web.exposure.include=mappings") + .run((context) -> { + assertThat(context).hasSingleBean(MappingsEndpoint.class); + assertThat(context.getBeansOfType(MappingDescriptionProvider.class)).hasSize(3); + }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java index e785ca9d56..3f656f517c 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/reactive/ReactiveManagementChildContextConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,14 +57,13 @@ class ReactiveManagementChildContextConfigurationIntegrationTests { private final ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ReactiveWebServerFactoryAutoConfiguration.class, - ReactiveManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, HttpHandlerAutoConfiguration.class, - WebFluxAutoConfiguration.class)) - .withUserConfiguration(SucceedingEndpoint.class) - .withInitializer(new ServerPortInfoApplicationContextInitializer()).withPropertyValues( - "server.port=0", "management.server.port=0", "management.endpoints.web.exposure.include=*"); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ReactiveWebServerFactoryAutoConfiguration.class, ReactiveManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, HttpHandlerAutoConfiguration.class, + WebFluxAutoConfiguration.class)) + .withUserConfiguration(SucceedingEndpoint.class) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0", "management.server.port=0", "management.endpoints.web.exposure.include=*"); @TempDir Path temp; @@ -72,8 +71,11 @@ class ReactiveManagementChildContextConfigurationIntegrationTests { @Test void endpointsAreBeneathActuatorByDefault() { this.runner.withPropertyValues("management.server.port:0").run(withWebTestClient((client) -> { - String body = client.get().uri("actuator/success").accept(MediaType.APPLICATION_JSON) - .exchangeToMono((response) -> response.bodyToMono(String.class)).block(); + String body = client.get() + .uri("actuator/success") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono((response) -> response.bodyToMono(String.class)) + .block(); assertThat(body).isEqualTo("Success"); })); } @@ -81,23 +83,26 @@ class ReactiveManagementChildContextConfigurationIntegrationTests { @Test void whenManagementServerBasePathIsConfiguredThenEndpointsAreBeneathThatPath() { this.runner.withPropertyValues("management.server.port:0", "management.server.base-path:/manage") - .run(withWebTestClient((client) -> { - String body = client.get().uri("manage/actuator/success").accept(MediaType.APPLICATION_JSON) - .exchangeToMono((response) -> response.bodyToMono(String.class)).block(); - assertThat(body).isEqualTo("Success"); - })); + .run(withWebTestClient((client) -> { + String body = client.get() + .uri("manage/actuator/success") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono((response) -> response.bodyToMono(String.class)) + .block(); + assertThat(body).isEqualTo("Success"); + })); } @Test // gh-32941 void whenManagementServerPortLoadedFromConfigTree() { this.runner.withInitializer(this::addConfigTreePropertySource) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } private void addConfigTreePropertySource(ConfigurableApplicationContext applicationContext) { try { - applicationContext.getEnvironment().setConversionService( - (ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); + applicationContext.getEnvironment() + .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); Path configtree = this.temp.resolve("configtree"); Path file = configtree.resolve("management/server/port"); file.toFile().getParentFile().mkdirs(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializerAotTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializerAotTests.java index 306a871049..cd6401d2a3 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializerAotTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializerAotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,10 +60,9 @@ class ChildManagementContextInitializerAotTests { void aotContributedInitializerStartsManagementContext(CapturedOutput output) { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class)); contextRunner.withPropertyValues("server.port=0", "management.server.port=0").prepare((context) -> { TestGenerationContext generationContext = new TestGenerationContext(TestTarget.class); ClassName className = new ApplicationContextAotGenerator().processAheadOfTime( @@ -74,11 +73,11 @@ class ChildManagementContextInitializerAotTests { ServletWebServerApplicationContext freshApplicationContext = new ServletWebServerApplicationContext(); TestPropertyValues.of("server.port=0", "management.server.port=0").applyTo(freshApplicationContext); ApplicationContextInitializer initializer = compiled - .getInstance(ApplicationContextInitializer.class, className.toString()); + .getInstance(ApplicationContextInitializer.class, className.toString()); initializer.initialize(freshApplicationContext); assertThat(output).satisfies(numberOfOccurrences("Tomcat started on port", 0)); TestPropertyValues.of(AotDetector.AOT_ENABLED + "=true") - .applyToSystemProperties(freshApplicationContext::refresh); + .applyToSystemProperties(freshApplicationContext::refresh); assertThat(output).satisfies(numberOfOccurrences("Tomcat started on port", 2)); }); }); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java index 6f920fe9ff..1d4e7c7319 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -48,25 +48,24 @@ class ManagementContextAutoConfigurationTests { void childManagementContextShouldStartForEmbeddedServer(CapturedOutput output) { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class)); contextRunner.withPropertyValues("server.port=0", "management.server.port=0") - .run((context) -> assertThat(output).satisfies(numberOfOccurrences("Tomcat started on port", 2))); + .run((context) -> assertThat(output).satisfies(numberOfOccurrences("Tomcat started on port", 2))); } @Test void givenSamePortManagementServerWhenManagementServerAddressIsConfiguredThenContextRefreshFails() { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, + DispatcherServletAutoConfiguration.class)); contextRunner.withPropertyValues("server.port=0", "management.server.address=127.0.0.1") - .run((context) -> assertThat(context).getFailure() - .hasMessageStartingWith("Management-specific server address cannot be configured")); + .run((context) -> assertThat(context).getFailure() + .hasMessageStartingWith("Management-specific server address cannot be configured")); } private Consumer numberOfOccurrences(String substring, int expectedCount) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java index e95aa81e53..1fb05aecc2 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,33 +42,35 @@ class ManagementContextConfigurationImportSelectorTests { @Test void selectImportsShouldOrderResult() { String[] imports = new TestManagementContextConfigurationsImportSelector(C.class, A.class, D.class, B.class) - .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); assertThat(imports).containsExactly(A.class.getName(), B.class.getName(), C.class.getName(), D.class.getName()); } @Test void selectImportsFiltersChildOnlyConfigurationWhenUsingSameContext() { String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, - A.class).selectImports(AnnotationMetadata.introspect(EnableSameContext.class)); + A.class) + .selectImports(AnnotationMetadata.introspect(EnableSameContext.class)); assertThat(imports).containsExactlyInAnyOrder(SameOnly.class.getName(), A.class.getName()); } @Test void selectImportsFiltersSameOnlyConfigurationWhenUsingChildContext() { String[] imports = new TestManagementContextConfigurationsImportSelector(ChildOnly.class, SameOnly.class, - A.class).selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + A.class) + .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); assertThat(imports).containsExactlyInAnyOrder(ChildOnly.class.getName(), A.class.getName()); } @Test void selectImportsLoadsFromResources() { String[] imports = new ManagementContextConfigurationImportSelector() - .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); + .selectImports(AnnotationMetadata.introspect(EnableChildContext.class)); Set expected = new HashSet<>(); ImportCandidates - .load(ManagementContextConfiguration.class, - ManagementContextConfigurationImportSelectorTests.class.getClassLoader()) - .forEach(expected::add); + .load(ManagementContextConfiguration.class, + ManagementContextConfigurationImportSelectorTests.class.getClassLoader()) + .forEach(expected::add); // Remove JerseySameManagementContextConfiguration, as it specifies // ManagementContextType.SAME and we asked for ManagementContextType.CHILD expected.remove( diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java index 363ab9def3..929ef877f6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/CompositeHandlerExceptionResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ class CompositeHandlerExceptionResolverTests { void resolverShouldDelegateToOtherResolversInContext() { load(TestConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context - .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); + .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); ModelAndView resolved = resolver.resolveException(this.request, this.response, null, new HttpRequestMethodNotSupportedException("POST")); assertThat(resolved.getViewName()).isEqualTo("test-view"); @@ -61,7 +61,7 @@ class CompositeHandlerExceptionResolverTests { void resolverShouldAddDefaultResolverIfNonePresent() { load(BaseConfiguration.class); CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context - .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); + .getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME); HttpRequestMethodNotSupportedException exception = new HttpRequestMethodNotSupportedException("POST"); ModelAndView resolved = resolver.resolveException(this.request, this.response, null, exception); assertThat(resolved).isNotNull(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java index f83d146cb5..c750ca4b83 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/MockServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -65,8 +65,9 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory implements WebServer { MockServletWebServer(ServletContextInitializer[] initializers, int port) { - super(Arrays.stream(initializers).map((initializer) -> (Initializer) initializer::onStartup) - .toArray(Initializer[]::new), port); + super(Arrays.stream(initializers) + .map((initializer) -> (Initializer) initializer::onStartup) + .toArray(Initializer[]::new), port); } @Override diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java index 106a4558f2..4dfd5c0732 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,17 +71,15 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { private final WebApplicationContextRunner runner = new WebApplicationContextRunner( AnnotationConfigServletWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - ServletManagementContextAutoConfiguration.class, WebEndpointAutoConfiguration.class, - EndpointAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - ErrorMvcAutoConfiguration.class)) - .withUserConfiguration(SucceedingEndpoint.class, FailingEndpoint.class, - FailingControllerEndpoint.class) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withPropertyValues("server.port=0", "management.server.port=0", - "management.endpoints.web.exposure.include=*", "server.error.include-exception=true", - "server.error.include-message=always", "server.error.include-binding-errors=always"); + .withConfiguration(AutoConfigurations.of(ManagementContextAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, ServletManagementContextAutoConfiguration.class, + WebEndpointAutoConfiguration.class, EndpointAutoConfiguration.class, + DispatcherServletAutoConfiguration.class, ErrorMvcAutoConfiguration.class)) + .withUserConfiguration(SucceedingEndpoint.class, FailingEndpoint.class, FailingControllerEndpoint.class) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withPropertyValues("server.port=0", "management.server.port=0", "management.endpoints.web.exposure.include=*", + "server.error.include-exception=true", "server.error.include-message=always", + "server.error.include-binding-errors=always"); @TempDir Path temp; @@ -89,8 +87,11 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test // gh-17938 void errorEndpointIsUsedWithEndpoint() { this.runner.run(withWebTestClient((client) -> { - Map body = client.get().uri("actuator/fail").accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); + Map body = client.get() + .uri("actuator/fail") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); assertThat(body).hasEntrySatisfying("exception", (value) -> assertThat(value).asString().contains("IllegalStateException")); assertThat(body).hasEntrySatisfying("message", @@ -101,21 +102,27 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test void errorPageAndErrorControllerIncludeDetails() { this.runner.withPropertyValues("server.error.include-stacktrace=always", "server.error.include-message=always") - .run(withWebTestClient((client) -> { - Map body = client.get().uri("actuator/fail").accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); - assertThat(body).hasEntrySatisfying("message", - (value) -> assertThat(value).asString().contains("Epic Fail")); - assertThat(body).hasEntrySatisfying("trace", (value) -> assertThat(value).asString() - .contains("java.lang.IllegalStateException: Epic Fail")); - })); + .run(withWebTestClient((client) -> { + Map body = client.get() + .uri("actuator/fail") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); + assertThat(body).hasEntrySatisfying("message", + (value) -> assertThat(value).asString().contains("Epic Fail")); + assertThat(body).hasEntrySatisfying("trace", + (value) -> assertThat(value).asString().contains("java.lang.IllegalStateException: Epic Fail")); + })); } @Test void errorEndpointIsUsedWithRestControllerEndpoint() { this.runner.run(withWebTestClient((client) -> { - Map body = client.get().uri("actuator/failController").accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); + Map body = client.get() + .uri("actuator/failController") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); assertThat(body).hasEntrySatisfying("exception", (value) -> assertThat(value).asString().contains("IllegalStateException")); assertThat(body).hasEntrySatisfying("message", @@ -126,9 +133,12 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test void errorEndpointIsUsedWithRestControllerEndpointOnBindingError() { this.runner.run(withWebTestClient((client) -> { - Map body = client.post().uri("actuator/failController") - .bodyValue(Collections.singletonMap("content", "")).accept(MediaType.APPLICATION_JSON) - .exchangeToMono(toResponseBody()).block(); + Map body = client.post() + .uri("actuator/failController") + .bodyValue(Collections.singletonMap("content", "")) + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono(toResponseBody()) + .block(); assertThat(body).hasEntrySatisfying("exception", (value) -> assertThat(value).asString().contains("MethodArgumentNotValidException")); assertThat(body).hasEntrySatisfying("message", @@ -140,8 +150,11 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test void whenManagementServerBasePathIsConfiguredThenEndpointsAreBeneathThatPath() { this.runner.withPropertyValues("management.server.base-path:/manage").run(withWebTestClient((client) -> { - String body = client.get().uri("manage/actuator/success").accept(MediaType.APPLICATION_JSON) - .exchangeToMono((response) -> response.bodyToMono(String.class)).block(); + String body = client.get() + .uri("manage/actuator/success") + .accept(MediaType.APPLICATION_JSON) + .exchangeToMono((response) -> response.bodyToMono(String.class)) + .block(); assertThat(body).isEqualTo("Success"); })); } @@ -149,13 +162,13 @@ class WebMvcEndpointChildContextConfigurationIntegrationTests { @Test // gh-32941 void whenManagementServerPortLoadedFromConfigTree() { this.runner.withInitializer(this::addConfigTreePropertySource) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } private void addConfigTreePropertySource(ConfigurableApplicationContext applicationContext) { try { - applicationContext.getEnvironment().setConversionService( - (ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); + applicationContext.getEnvironment() + .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); Path configtree = this.temp.resolve("configtree"); Path file = configtree.resolve("management/server/port"); file.toFile().getParentFile().mkdirs(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java index a4e8a30864..0eaf303edf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/servlet/WebMvcEndpointChildContextConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -36,36 +36,37 @@ import static org.assertj.core.api.Assertions.assertThat; class WebMvcEndpointChildContextConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withAllowBeanDefinitionOverriding(true); + .withAllowBeanDefinitionOverriding(true); @Test void contextShouldConfigureRequestContextFilter() { this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(OrderedRequestContextFilter.class)); + .run((context) -> assertThat(context).hasSingleBean(OrderedRequestContextFilter.class)); } @Test void contextShouldNotConfigureRequestContextFilterWhenPresent() { this.contextRunner.withUserConfiguration(ExistingConfig.class, WebMvcEndpointChildContextConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(RequestContextFilter.class); - assertThat(context).hasBean("testRequestContextFilter"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RequestContextFilter.class); + assertThat(context).hasBean("testRequestContextFilter"); + }); } @Test void contextShouldNotConfigureRequestContextFilterWhenRequestContextListenerPresent() { - this.contextRunner.withUserConfiguration(RequestContextListenerConfig.class, - WebMvcEndpointChildContextConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(RequestContextListener.class); - assertThat(context).doesNotHaveBean(OrderedRequestContextFilter.class); - }); + this.contextRunner + .withUserConfiguration(RequestContextListenerConfig.class, WebMvcEndpointChildContextConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(RequestContextListener.class); + assertThat(context).doesNotHaveBean(OrderedRequestContextFilter.class); + }); } @Test void contextShouldConfigureDispatcherServletPathWithRootPath() { this.contextRunner.withUserConfiguration(WebMvcEndpointChildContextConfiguration.class) - .run((context) -> assertThat(context.getBean(DispatcherServletPath.class).getPath()).isEqualTo("/")); + .run((context) -> assertThat(context.getBean(DispatcherServletPath.class).getPath()).isEqualTo("/")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java index 2ce4a058b2..386da31a9b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ public class RabbitHealthIndicator extends AbstractHealthIndicator { private String getVersion() { return this.rabbitTemplate - .execute((channel) -> channel.getConnection().getServerProperties().get("version").toString()); + .execute((channel) -> channel.getConnection().getServerProperties().get("version").toString()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java index 5491a81026..478b098a3b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cache/CachesEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -109,14 +109,22 @@ public class CachesEndpoint { private List getCacheEntries(Predicate cacheNamePredicate, Predicate cacheManagerNamePredicate) { - return this.cacheManagers.keySet().stream().filter(cacheManagerNamePredicate) - .flatMap((cacheManagerName) -> getCacheEntries(cacheManagerName, cacheNamePredicate).stream()).toList(); + return this.cacheManagers.keySet() + .stream() + .filter(cacheManagerNamePredicate) + .flatMap((cacheManagerName) -> getCacheEntries(cacheManagerName, cacheNamePredicate).stream()) + .toList(); } private List getCacheEntries(String cacheManagerName, Predicate cacheNamePredicate) { CacheManager cacheManager = this.cacheManagers.get(cacheManagerName); - return cacheManager.getCacheNames().stream().filter(cacheNamePredicate).map(cacheManager::getCache) - .filter(Objects::nonNull).map((cache) -> new CacheEntryDescriptor(cache, cacheManagerName)).toList(); + return cacheManager.getCacheNames() + .stream() + .filter(cacheNamePredicate) + .map(cacheManager::getCache) + .filter(Objects::nonNull) + .map((cache) -> new CacheEntryDescriptor(cache, cacheManagerName)) + .toList(); } private CacheEntryDescriptor extractUniqueCacheEntry(String cache, List entries) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java index cbbe397085..85ab6f420b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -189,8 +189,8 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext private void applyConfigurationPropertiesFilter(JsonMapper.Builder builder) { builder.annotationIntrospector(new ConfigurationPropertiesAnnotationIntrospector()); - builder.filterProvider( - new SimpleFilterProvider().setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); + builder + .filterProvider(new SimpleFilterProvider().setDefaultFilter(new ConfigurationPropertiesPropertyFilter())); } /** @@ -199,16 +199,18 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext */ private void applySerializationModifier(JsonMapper.Builder builder) { SerializerFactory factory = BeanSerializerFactory.instance - .withSerializerModifier(new GenericSerializerModifier()); + .withSerializerModifier(new GenericSerializerModifier()); builder.serializerFactory(factory); } private ContextConfigurationPropertiesDescriptor describeBeans(ObjectMapper mapper, ApplicationContext context, Predicate beanFilterPredicate, boolean showUnsanitized) { Map beans = ConfigurationPropertiesBean.getAll(context); - Map descriptors = beans.values().stream() - .filter(beanFilterPredicate).collect(Collectors.toMap(ConfigurationPropertiesBean::getName, - (bean) -> describeBean(mapper, bean, showUnsanitized))); + Map descriptors = beans.values() + .stream() + .filter(beanFilterPredicate) + .collect(Collectors.toMap(ConfigurationPropertiesBean::getName, + (bean) -> describeBean(mapper, bean, showUnsanitized))); return new ContextConfigurationPropertiesDescriptor(descriptors, (context.getParent() != null) ? context.getParent().getId() : null); } @@ -508,9 +510,10 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext names = new String[parameters.length]; } for (int i = 0; i < parameters.length; i++) { - String name = MergedAnnotations.from(parameters[i]).get(Name.class) - .getValue(MergedAnnotation.VALUE, String.class) - .orElse((names[i] != null) ? names[i] : parameters[i].getName()); + String name = MergedAnnotations.from(parameters[i]) + .get(Name.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse((names[i] != null) ? names[i] : parameters[i].getName()); if (name.equals(writer.getName())) { return true; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java index 9e4cdc0332..7fa8698319 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -61,8 +61,10 @@ public class ConfigurationPropertiesReportEndpointWebExtension { boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles); ConfigurationPropertiesDescriptor configurationProperties = this.delegate.getConfigurationProperties(prefix, showUnsanitized); - boolean foundMatchingBeans = configurationProperties.getContexts().values().stream() - .anyMatch((context) -> !context.getBeans().isEmpty()); + boolean foundMatchingBeans = configurationProperties.getContexts() + .values() + .stream() + .anyMatch((context) -> !context.getBeans().isEmpty()); return (foundMatchingBeans) ? new WebEndpointResponse<>(configurationProperties, WebEndpointResponse.STATUS_OK) : new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java index 486f796096..dcd40a5bbe 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/couchbase/CouchbaseHealth.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,8 +42,13 @@ class CouchbaseHealth { void applyTo(Builder builder) { builder = isCouchbaseUp(this.diagnostics) ? builder.up() : builder.down(); builder.withDetail("sdk", this.diagnostics.sdk()); - builder.withDetail("endpoints", this.diagnostics.endpoints().values().stream().flatMap(Collection::stream) - .map(this::describe).toList()); + builder.withDetail("endpoints", + this.diagnostics.endpoints() + .values() + .stream() + .flatMap(Collection::stream) + .map(this::describe) + .toList()); } private boolean isCouchbaseUp(DiagnosticsResult diagnostics) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/data/redis/RedisReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/data/redis/RedisReactiveHealthIndicator.java index e8d54423a2..4567e1325e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/data/redis/RedisReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/data/redis/RedisReactiveHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,12 +54,12 @@ public class RedisReactiveHealthIndicator extends AbstractReactiveHealthIndicato private Mono getConnection() { return Mono.fromSupplier(this.connectionFactory::getReactiveConnection) - .subscribeOn(Schedulers.boundedElastic()); + .subscribeOn(Schedulers.boundedElastic()); } private Mono doHealthCheck(Health.Builder builder, ReactiveRedisConnection connection) { return getHealth(builder, connection).onErrorResume((ex) -> Mono.just(builder.down(ex).build())) - .flatMap((health) -> connection.closeLater().thenReturn(health)); + .flatMap((health) -> connection.closeLater().thenReturn(health)); } private Mono getHealth(Health.Builder builder, ReactiveRedisConnection connection) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java index 9c053d306d..91fa1fa403 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,7 @@ public abstract class AbstractDiscoveredEndpoint extends Ab @Override public String toString() { ToStringCreator creator = new ToStringCreator(this).append("discoverer", this.discoverer.getClass().getName()) - .append("endpointBean", this.endpointBean.getClass().getName()); + .append("endpointBean", this.endpointBean.getClass().getName()); appendFields(creator); return creator.toString(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java index cfc7a0f184..6138b7e138 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ public abstract class AbstractDiscoveredOperation implements Operation { @Override public String toString() { ToStringCreator creator = new ToStringCreator(this).append("operationMethod", this.operationMethod) - .append("invoker", this.invoker); + .append("invoker", this.invoker); appendFields(creator); return creator.toString(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java index aa6b1aff66..2e4836b3d3 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationsFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -70,14 +70,17 @@ abstract class DiscoveredOperationsFactory { Collection createOperations(EndpointId id, Object target) { return MethodIntrospector - .selectMethods(target.getClass(), (MetadataLookup) (method) -> createOperation(id, target, method)) - .values(); + .selectMethods(target.getClass(), (MetadataLookup) (method) -> createOperation(id, target, method)) + .values(); } private O createOperation(EndpointId endpointId, Object target, Method method) { - return OPERATION_TYPES.entrySet().stream() - .map((entry) -> createOperation(endpointId, target, method, entry.getKey(), entry.getValue())) - .filter(Objects::nonNull).findFirst().orElse(null); + return OPERATION_TYPES.entrySet() + .stream() + .map((entry) -> createOperation(endpointId, target, method, entry.getKey(), entry.getValue())) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } private O createOperation(EndpointId endpointId, Object target, Method method, OperationType operationType, diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java index 96b11e1873..e7faed17b4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -148,7 +148,7 @@ public abstract class EndpointDiscoverer, O exten private void addExtensionBeans(Collection endpointBeans) { Map byId = endpointBeans.stream() - .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); + .collect(Collectors.toMap(EndpointBean::getId, Function.identity())); String[] beanNames = BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(this.applicationContext, EndpointExtension.class); for (String beanName : beanNames) { @@ -190,8 +190,10 @@ public abstract class EndpointDiscoverer, O exten EndpointId id = endpointBean.getId(); addOperations(indexed, id, endpointBean.getBean(), false); if (endpointBean.getExtensions().size() > 1) { - String extensionBeans = endpointBean.getExtensions().stream().map(ExtensionBean::getBeanName) - .collect(Collectors.joining(", ")); + String extensionBeans = endpointBean.getExtensions() + .stream() + .map(ExtensionBean::getBeanName) + .collect(Collectors.joining(", ")); throw new IllegalStateException("Found multiple extensions for the endpoint bean " + endpointBean.getBeanName() + " (" + extensionBeans + ")"); } @@ -222,12 +224,16 @@ public abstract class EndpointDiscoverer, O exten } private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMap indexed) { - List duplicates = indexed.entrySet().stream().filter((entry) -> entry.getValue().size() > 1) - .map(Map.Entry::getKey).toList(); + List duplicates = indexed.entrySet() + .stream() + .filter((entry) -> entry.getValue().size() > 1) + .map(Map.Entry::getKey) + .toList(); if (!duplicates.isEmpty()) { Set extensions = endpointBean.getExtensions(); - String extensionBeanNames = extensions.stream().map(ExtensionBean::getBeanName) - .collect(Collectors.joining(", ")); + String extensionBeanNames = extensions.stream() + .map(ExtensionBean::getBeanName) + .collect(Collectors.joining(", ")); throw new IllegalStateException("Unable to map duplicate endpoint operations: " + duplicates.toString() + " to " + endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")")); @@ -296,8 +302,10 @@ public abstract class EndpointDiscoverer, O exten @SuppressWarnings("unchecked") private boolean isFilterMatch(EndpointFilter filter, E endpoint) { - return LambdaSafe.callback(EndpointFilter.class, filter, endpoint).withLogger(EndpointDiscoverer.class) - .invokeAnd((f) -> f.match(endpoint)).get(); + return LambdaSafe.callback(EndpointFilter.class, filter, endpoint) + .withLogger(EndpointDiscoverer.class) + .invokeAnd((f) -> f.match(endpoint)) + .get(); } private E getFilterEndpoint(EndpointBean endpointBean) { @@ -409,7 +417,7 @@ public abstract class EndpointDiscoverer, O exten EndpointBean(Environment environment, String beanName, Class beanType, Supplier beanSupplier) { MergedAnnotation annotation = MergedAnnotations.from(beanType, SearchStrategy.TYPE_HIERARCHY) - .get(Endpoint.class); + .get(Endpoint.class); String id = annotation.getString("id"); Assert.state(StringUtils.hasText(id), () -> "No @Endpoint id attribute specified for " + beanType.getName()); @@ -430,8 +438,10 @@ public abstract class EndpointDiscoverer, O exten } private Class getFilter(Class type) { - return MergedAnnotations.from(type, SearchStrategy.TYPE_HIERARCHY).get(FilteredEndpoint.class) - .getValue(MergedAnnotation.VALUE, Class.class).orElse(null); + return MergedAnnotations.from(type, SearchStrategy.TYPE_HIERARCHY) + .get(FilteredEndpoint.class) + .getValue(MergedAnnotation.VALUE, Class.class) + .orElse(null); } String getBeanName() { @@ -480,10 +490,12 @@ public abstract class EndpointDiscoverer, O exten this.beanType = beanType; this.beanSupplier = beanSupplier; MergedAnnotation extensionAnnotation = MergedAnnotations - .from(beanType, SearchStrategy.TYPE_HIERARCHY).get(EndpointExtension.class); + .from(beanType, SearchStrategy.TYPE_HIERARCHY) + .get(EndpointExtension.class); Class endpointType = extensionAnnotation.getClass("endpoint"); MergedAnnotation endpointAnnotation = MergedAnnotations - .from(endpointType, SearchStrategy.TYPE_HIERARCHY).get(Endpoint.class); + .from(endpointType, SearchStrategy.TYPE_HIERARCHY) + .get(Endpoint.class); Assert.state(endpointAnnotation.isPresent(), () -> "Extension " + endpointType.getName() + " does not specify an endpoint"); this.endpointId = EndpointId.of(environment, endpointAnnotation.getString("id")); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java index 53899dffa8..eda0604578 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/FilteredEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -39,6 +39,7 @@ import org.springframework.boot.actuate.endpoint.EndpointFilter; * boolean enableByDefault() default true; * * } + * * @author Phillip Webb * @since 2.0.0 * @see DiscovererEndpointFilter diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java index 5a277da4b7..7f8f3960b4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvoker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -75,8 +75,10 @@ public class ReflectiveOperationInvoker implements OperationInvoker { } private void validateRequiredParameters(InvocationContext context) { - Set missing = this.operationMethod.getParameters().stream() - .filter((parameter) -> isMissing(context, parameter)).collect(Collectors.toSet()); + Set missing = this.operationMethod.getParameters() + .stream() + .filter((parameter) -> isMissing(context, parameter)) + .collect(Collectors.toSet()); if (!missing.isEmpty()) { throw new MissingParametersException(missing); } @@ -93,8 +95,10 @@ public class ReflectiveOperationInvoker implements OperationInvoker { } private Object[] resolveArguments(InvocationContext context) { - return this.operationMethod.getParameters().stream().map((parameter) -> resolveArgument(parameter, context)) - .toArray(); + return this.operationMethod.getParameters() + .stream() + .map((parameter) -> resolveArgument(parameter, context)) + .toArray(); } private Object resolveArgument(OperationParameter parameter, InvocationContext context) { @@ -108,8 +112,9 @@ public class ReflectiveOperationInvoker implements OperationInvoker { @Override public String toString() { - return new ToStringCreator(this).append("target", this.target).append("method", this.operationMethod) - .toString(); + return new ToStringCreator(this).append("target", this.target) + .append("method", this.operationMethod) + .toString(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java index 5bd2031ad7..fc6a95ad1f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -115,8 +115,10 @@ public class EndpointMBean implements DynamicMBean { private Object invoke(JmxOperation operation, Object[] params) throws MBeanException, ReflectionException { try { - String[] parameterNames = operation.getParameters().stream().map(JmxOperationParameter::getName) - .toArray(String[]::new); + String[] parameterNames = operation.getParameters() + .stream() + .map(JmxOperationParameter::getName) + .toArray(String[]::new); Map arguments = getArguments(parameterNames, params); InvocationContext context = new InvocationContext(SecurityContext.NONE, arguments); Object result = operation.invoke(context); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java index 39ff94db1f..235d78b9fc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JacksonJmxOperationResponseMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -41,8 +41,8 @@ public class JacksonJmxOperationResponseMapper implements JmxOperationResponseMa public JacksonJmxOperationResponseMapper(ObjectMapper objectMapper) { this.objectMapper = (objectMapper != null) ? objectMapper : new ObjectMapper(); this.listType = this.objectMapper.getTypeFactory().constructParametricType(List.class, Object.class); - this.mapType = this.objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, - Object.class); + this.mapType = this.objectMapper.getTypeFactory() + .constructParametricType(Map.class, String.class, Object.class); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java index 32e948fb01..95a5024731 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/DiscoveredJmxOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -83,8 +83,9 @@ class DiscoveredJmxOperation extends AbstractDiscoveredOperation implements JmxO Method method = operationMethod.getMethod(); ManagedOperationParameter[] managed = jmxAttributeSource.getManagedOperationParameters(method); if (managed.length == 0) { - Stream parameters = operationMethod.getParameters().stream() - .map(DiscoveredJmxOperationParameter::new); + Stream parameters = operationMethod.getParameters() + .stream() + .map(DiscoveredJmxOperationParameter::new); return parameters.toList(); } return mergeParameters(operationMethod.getParameters(), managed); @@ -121,8 +122,10 @@ class DiscoveredJmxOperation extends AbstractDiscoveredOperation implements JmxO @Override protected void appendFields(ToStringCreator creator) { - creator.append("name", this.name).append("outputType", this.outputType).append("description", this.description) - .append("parameters", this.parameters); + creator.append("name", this.name) + .append("outputType", this.outputType) + .append("description", this.description) + .append("parameters", this.parameters); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java index bb7d11f7b1..e8803cc26e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -90,8 +90,8 @@ public class ControllerEndpointDiscoverer extends EndpointDiscoverer parameter.getAnnotation(Selector.class) == null); + .anyMatch((parameter) -> parameter.getAnnotation(Selector.class) == null); } private WebEndpointHttpMethod determineHttpMethod(OperationType operationType) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java index 1ed8af92cb..cf27addf3a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/jersey/JerseyEndpointResourceFactory.java @@ -84,8 +84,10 @@ public class JerseyEndpointResourceFactory { Collection endpoints, EndpointMediaTypes endpointMediaTypes, EndpointLinksResolver linksResolver, boolean shouldRegisterLinks) { List resources = new ArrayList<>(); - endpoints.stream().flatMap((endpoint) -> endpoint.getOperations().stream()) - .map((operation) -> createResource(endpointMapping, operation)).forEach(resources::add); + endpoints.stream() + .flatMap((endpoint) -> endpoint.getOperations().stream()) + .map((operation) -> createResource(endpointMapping, operation)) + .forEach(resources::add); if (shouldRegisterLinks) { Resource resource = createEndpointLinksResource(endpointMapping.getPath(), endpointMediaTypes, linksResolver); @@ -108,21 +110,23 @@ public class JerseyEndpointResourceFactory { protected Resource getResource(EndpointMapping endpointMapping, WebOperation operation, WebOperationRequestPredicate requestPredicate, String path, WebServerNamespace serverNamespace, JerseyRemainingPathSegmentProvider remainingPathSegmentProvider) { - Builder resourceBuilder = Resource.builder().path(endpointMapping.getPath()) - .path(endpointMapping.createSubPath(path)); + Builder resourceBuilder = Resource.builder() + .path(endpointMapping.getPath()) + .path(endpointMapping.createSubPath(path)); resourceBuilder.addMethod(requestPredicate.getHttpMethod().name()) - .consumes(StringUtils.toStringArray(requestPredicate.getConsumes())) - .produces(StringUtils.toStringArray(requestPredicate.getProduces())) - .handledBy(new OperationInflector(operation, !requestPredicate.getConsumes().isEmpty(), serverNamespace, - remainingPathSegmentProvider)); + .consumes(StringUtils.toStringArray(requestPredicate.getConsumes())) + .produces(StringUtils.toStringArray(requestPredicate.getProduces())) + .handledBy(new OperationInflector(operation, !requestPredicate.getConsumes().isEmpty(), serverNamespace, + remainingPathSegmentProvider)); return resourceBuilder.build(); } private Resource createEndpointLinksResource(String endpointPath, EndpointMediaTypes endpointMediaTypes, EndpointLinksResolver linksResolver) { Builder resourceBuilder = Resource.builder().path(endpointPath); - resourceBuilder.addMethod("GET").produces(StringUtils.toStringArray(endpointMediaTypes.getProduced())) - .handledBy(new EndpointLinksInflector(linksResolver)); + resourceBuilder.addMethod("GET") + .produces(StringUtils.toStringArray(endpointMediaTypes.getProduced())) + .handledBy(new EndpointLinksInflector(linksResolver)); return resourceBuilder.build(); } @@ -172,7 +176,7 @@ public class JerseyEndpointResourceFactory { try { JerseySecurityContext securityContext = new JerseySecurityContext(data.getSecurityContext()); OperationArgumentResolver serverNamespaceArgumentResolver = OperationArgumentResolver - .of(WebServerNamespace.class, () -> this.serverNamespace); + .of(WebServerNamespace.class, () -> this.serverNamespace); InvocationContext invocationContext = new InvocationContext(securityContext, arguments, serverNamespaceArgumentResolver, new ProducibleOperationArgumentResolver(() -> data.getHeaders().get("Accept"))); @@ -193,7 +197,7 @@ public class JerseyEndpointResourceFactory { private Map extractPathParameters(ContainerRequestContext requestContext) { Map pathParameters = extract(requestContext.getUriInfo().getPathParameters()); String matchAllRemainingPathSegmentsVariable = this.operation.getRequestPredicate() - .getMatchAllRemainingPathSegmentsVariable(); + .getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { String remainingPathSegments = getRemainingPathSegments(requestContext, pathParameters, matchAllRemainingPathSegmentsVariable); @@ -244,8 +248,9 @@ public class JerseyEndpointResourceFactory { return Response.status(Status.OK).entity(convertIfNecessary(response)).build(); } return Response.status(webEndpointResponse.getStatus()) - .header("Content-Type", webEndpointResponse.getContentType()) - .entity(convertIfNecessary(webEndpointResponse.getBody())).build(); + .header("Content-Type", webEndpointResponse.getContentType()) + .entity(convertIfNecessary(webEndpointResponse.getBody())) + .build(); } private Object convertIfNecessary(Object body) { @@ -322,7 +327,7 @@ public class JerseyEndpointResourceFactory { @Override public Response apply(ContainerRequestContext request) { Map links = this.linksResolver - .resolveLinks(request.getUriInfo().getAbsolutePath().toString()); + .resolveLinks(request.getUriInfo().getAbsolutePath().toString()); Map> entity = OperationResponseBody.of(Collections.singletonMap("_links", links)); return Response.ok(entity).build(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java index d51f055e75..fc1d38061e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMapping.java @@ -186,8 +186,10 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi String path = this.endpointMapping.getPath(); String linksPath = StringUtils.hasLength(path) ? path : "/"; String[] produces = StringUtils.toStringArray(this.endpointMediaTypes.getProduced()); - RequestMappingInfo mapping = RequestMappingInfo.paths(linksPath).methods(RequestMethod.GET).produces(produces) - .build(); + RequestMappingInfo mapping = RequestMappingInfo.paths(linksPath) + .methods(RequestMethod.GET) + .produces(produces) + .build(); LinksHandler linksHandler = getLinksHandler(); registerMapping(mapping, linksHandler, ReflectionUtils.findMethod(linksHandler.getClass(), "links", ServerWebExchange.class)); @@ -305,8 +307,8 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi Mono springSecurityContext() { return ReactiveSecurityContextHolder.getContext() - .map((securityContext) -> new ReactiveSecurityContext(securityContext.getAuthentication())) - .switchIfEmpty(Mono.just(new ReactiveSecurityContext(null))); + .map((securityContext) -> new ReactiveSecurityContext(securityContext.getAuthentication())) + .switchIfEmpty(Mono.just(new ReactiveSecurityContext(null))); } Mono emptySecurityContext() { @@ -317,29 +319,30 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi public Mono> handle(ServerWebExchange exchange, Map body) { Map arguments = getArguments(exchange, body); OperationArgumentResolver serverNamespaceArgumentResolver = OperationArgumentResolver - .of(WebServerNamespace.class, () -> WebServerNamespace - .from(WebServerApplicationContext.getServerNamespace(exchange.getApplicationContext()))); + .of(WebServerNamespace.class, () -> WebServerNamespace + .from(WebServerApplicationContext.getServerNamespace(exchange.getApplicationContext()))); return this.securityContextSupplier.get() - .map((securityContext) -> new InvocationContext(securityContext, arguments, - serverNamespaceArgumentResolver, - new ProducibleOperationArgumentResolver( - () -> exchange.getRequest().getHeaders().get("Accept")))) - .flatMap((invocationContext) -> handleResult((Publisher) this.invoker.invoke(invocationContext), - exchange.getRequest().getMethod())); + .map((securityContext) -> new InvocationContext(securityContext, arguments, + serverNamespaceArgumentResolver, + new ProducibleOperationArgumentResolver( + () -> exchange.getRequest().getHeaders().get("Accept")))) + .flatMap((invocationContext) -> handleResult((Publisher) this.invoker.invoke(invocationContext), + exchange.getRequest().getMethod())); } private Map getArguments(ServerWebExchange exchange, Map body) { Map arguments = new LinkedHashMap<>(getTemplateVariables(exchange)); String matchAllRemainingPathSegmentsVariable = this.operation.getRequestPredicate() - .getMatchAllRemainingPathSegmentsVariable(); + .getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { arguments.put(matchAllRemainingPathSegmentsVariable, getRemainingPathSegments(exchange)); } if (body != null) { arguments.putAll(body); } - exchange.getRequest().getQueryParams() - .forEach((name, values) -> arguments.put(name, (values.size() != 1) ? values : values.get(0))); + exchange.getRequest() + .getQueryParams() + .forEach((name, values) -> arguments.put(name, (values.size() != 1) ? values : values.get(0))); return arguments; } @@ -347,7 +350,8 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi PathPattern pathPattern = exchange.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); if (pathPattern.hasPatternSyntax()) { String remainingSegments = pathPattern - .extractPathWithinPattern(exchange.getRequest().getPath().pathWithinApplication()).value(); + .extractPathWithinPattern(exchange.getRequest().getPath().pathWithinApplication()) + .value(); return tokenizePathSegments(remainingSegments); } return tokenizePathSegments(pathPattern.toString()); @@ -371,11 +375,12 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi if (result instanceof Flux) { result = ((Flux) result).collectList(); } - return Mono.from(result).map(this::toResponseEntity) - .onErrorMap(InvalidEndpointRequestException.class, - (ex) -> new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getReason())) - .defaultIfEmpty(new ResponseEntity<>( - (httpMethod != HttpMethod.GET) ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND)); + return Mono.from(result) + .map(this::toResponseEntity) + .onErrorMap(InvalidEndpointRequestException.class, + (ex) -> new ResponseStatusException(HttpStatus.BAD_REQUEST, ex.getReason())) + .defaultIfEmpty(new ResponseEntity<>( + (httpMethod != HttpMethod.GET) ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND)); } private ResponseEntity toResponseEntity(Object response) { @@ -384,8 +389,9 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi } MediaType contentType = (webEndpointResponse.getContentType() != null) ? new MediaType(webEndpointResponse.getContentType()) : null; - return ResponseEntity.status(webEndpointResponse.getStatus()).contentType(contentType) - .body(webEndpointResponse.getBody()); + return ResponseEntity.status(webEndpointResponse.getStatus()) + .contentType(contentType) + .body(webEndpointResponse.getBody()); } @Override @@ -485,8 +491,9 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi @Override public boolean isUserInRole(String role) { String authority = (!role.startsWith(ROLE_PREFIX)) ? ROLE_PREFIX + role : role; - return AuthorityAuthorizationManager.hasAuthority(authority).check(this::getAuthentication, null) - .isGranted(); + return AuthorityAuthorizationManager.hasAuthority(authority) + .check(this::getAuthentication, null) + .isGranted(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java index ef7583bc41..e326a9bada 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -92,7 +92,8 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi patterns = Collections.singleton(getPathPatternParser().parse("")); } String[] endpointMappedPatterns = patterns.stream() - .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)).toArray(String[]::new); + .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)) + .toArray(String[]::new); return mapping.mutate().paths(endpointMappedPatterns).build(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java index 8acbbcb85e..b9e898097f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -86,8 +86,9 @@ public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandle @ResponseBody @Reflective public Map> links(ServerWebExchange exchange) { - String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).replaceQuery(null) - .toUriString(); + String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()) + .replaceQuery(null) + .toUriString(); Map links = WebFluxEndpointHandlerMapping.this.linksResolver.resolveLinks(requestUri); return OperationResponseBody.of(Collections.singletonMap("_links", links)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java index 0c75b3cb23..9be3223ee6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMapping.java @@ -196,18 +196,22 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin } private RequestMappingInfo createRequestMappingInfo(WebOperationRequestPredicate predicate, String path) { - return RequestMappingInfo.paths(this.endpointMapping.createSubPath(path)).options(this.builderConfig) - .methods(RequestMethod.valueOf(predicate.getHttpMethod().name())) - .consumes(predicate.getConsumes().toArray(new String[0])) - .produces(predicate.getProduces().toArray(new String[0])).build(); + return RequestMappingInfo.paths(this.endpointMapping.createSubPath(path)) + .options(this.builderConfig) + .methods(RequestMethod.valueOf(predicate.getHttpMethod().name())) + .consumes(predicate.getConsumes().toArray(new String[0])) + .produces(predicate.getProduces().toArray(new String[0])) + .build(); } private void registerLinksMapping() { String path = this.endpointMapping.getPath(); String linksPath = (StringUtils.hasLength(path)) ? this.endpointMapping.createSubPath("/") : "/"; - RequestMappingInfo mapping = RequestMappingInfo.paths(linksPath).methods(RequestMethod.GET) - .produces(this.endpointMediaTypes.getProduced().toArray(new String[0])).options(this.builderConfig) - .build(); + RequestMappingInfo mapping = RequestMappingInfo.paths(linksPath) + .methods(RequestMethod.GET) + .produces(this.endpointMediaTypes.getProduced().toArray(new String[0])) + .options(this.builderConfig) + .build(); LinksHandler linksHandler = getLinksHandler(); registerMapping(mapping, linksHandler, ReflectionUtils.findMethod(linksHandler.getClass(), "links", HttpServletRequest.class, HttpServletResponse.class)); @@ -306,12 +310,12 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin ProducibleOperationArgumentResolver producibleOperationArgumentResolver = new ProducibleOperationArgumentResolver( () -> headers.get("Accept")); OperationArgumentResolver serverNamespaceArgumentResolver = OperationArgumentResolver - .of(WebServerNamespace.class, () -> { - WebApplicationContext applicationContext = WebApplicationContextUtils - .getRequiredWebApplicationContext(request.getServletContext()); - return WebServerNamespace - .from(WebServerApplicationContext.getServerNamespace(applicationContext)); - }); + .of(WebServerNamespace.class, () -> { + WebApplicationContext applicationContext = WebApplicationContextUtils + .getRequiredWebApplicationContext(request.getServletContext()); + return WebServerNamespace + .from(WebServerApplicationContext.getServerNamespace(applicationContext)); + }); InvocationContext invocationContext = new InvocationContext(securityContext, arguments, serverNamespaceArgumentResolver, producibleOperationArgumentResolver); return handleResult(this.operation.invoke(invocationContext), HttpMethod.valueOf(request.getMethod())); @@ -329,15 +333,16 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin private Map getArguments(HttpServletRequest request, Map body) { Map arguments = new LinkedHashMap<>(getTemplateVariables(request)); String matchAllRemainingPathSegmentsVariable = this.operation.getRequestPredicate() - .getMatchAllRemainingPathSegmentsVariable(); + .getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { arguments.put(matchAllRemainingPathSegmentsVariable, getRemainingPathSegments(request)); } if (body != null && HttpMethod.POST.name().equals(request.getMethod())) { arguments.putAll(body); } - request.getParameterMap().forEach( - (name, values) -> arguments.put(name, (values.length != 1) ? Arrays.asList(values) : values[0])); + request.getParameterMap() + .forEach((name, values) -> arguments.put(name, + (values.length != 1) ? Arrays.asList(values) : values[0])); return arguments; } @@ -380,8 +385,9 @@ public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappin } MediaType contentType = (response.getContentType() != null) ? new MediaType(response.getContentType()) : null; - return ResponseEntity.status(response.getStatus()).contentType(contentType) - .body(convertIfNecessary(response.getBody())); + return ResponseEntity.status(response.getStatus()) + .contentType(contentType) + .body(convertIfNecessary(response.getBody())); } private Object convertIfNecessary(Object body) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java index 859ad2b816..3da646413d 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -93,7 +93,8 @@ public class ControllerEndpointHandlerMapping extends RequestMappingHandlerMappi patterns = Collections.singleton(getPatternParser().parse("")); } String[] endpointMappedPatterns = patterns.stream() - .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)).toArray(String[]::new); + .map((pattern) -> getEndpointMappedPattern(endpoint, pattern)) + .toArray(String[]::new); return mapping.mutate().paths(endpointMappedPatterns).build(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java index 49997e12ee..d60e5abddc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/SkipPathExtensionContentNegotiation.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -32,7 +32,7 @@ final class SkipPathExtensionContentNegotiation implements HandlerInterceptor { @SuppressWarnings("deprecation") private static final String SKIP_ATTRIBUTE = org.springframework.web.accept.PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + .getName() + ".SKIP"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java index 961abc93c3..1dabd2f4a0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -86,7 +86,7 @@ public class WebMvcEndpointHandlerMapping extends AbstractWebMvcEndpointHandlerM @Reflective public Map> links(HttpServletRequest request, HttpServletResponse response) { Map links = WebMvcEndpointHandlerMapping.this.linksResolver - .resolveLinks(request.getRequestURL().toString()); + .resolveLinks(request.getRequestURL().toString()); return OperationResponseBody.of(Collections.singletonMap("_links", links)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java index 0d01c3aac4..1358f6f063 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -144,8 +144,9 @@ public class EnvironmentEndpoint { private PropertySourceDescriptor describeSource(String sourceName, EnumerablePropertySource source, Predicate namePredicate, boolean showUnsanitized) { Map properties = new LinkedHashMap<>(); - Stream.of(source.getPropertyNames()).filter(namePredicate) - .forEach((name) -> properties.put(name, describeValueOf(name, source, showUnsanitized))); + Stream.of(source.getPropertyNames()) + .filter(namePredicate) + .forEach((name) -> properties.put(name, describeValueOf(name, source, showUnsanitized))); return new PropertySourceDescriptor(sourceName, properties); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java index 00f1aa3aab..0922fb2455 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/flyway/FlywayEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ public class FlywayEndpoint { while (target != null) { Map flywayBeans = new HashMap<>(); target.getBeansOfType(Flyway.class) - .forEach((name, flyway) -> flywayBeans.put(name, new FlywayDescriptor(flyway.info().all()))); + .forEach((name, flyway) -> flywayBeans.put(name, new FlywayDescriptor(flyway.info().all()))); ApplicationContext parent = target.getParent(); contextFlywayBeans.put(target.getId(), new ContextFlywayBeansDescriptor(flywayBeans, (parent != null) ? parent.getId() : null)); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java index 26765672ca..87e3deb493 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointGroups.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -78,9 +78,10 @@ public interface HealthEndpointGroups { default Set getAllWithAdditionalPath(WebServerNamespace namespace) { Assert.notNull(namespace, "Namespace must not be null"); Set filteredGroups = new LinkedHashSet<>(); - getNames().stream().map(this::get).filter( - (group) -> group.getAdditionalPath() != null && group.getAdditionalPath().hasNamespace(namespace)) - .forEach(filteredGroups::add); + getNames().stream() + .map(this::get) + .filter((group) -> group.getAdditionalPath() != null && group.getAdditionalPath().hasNamespace(namespace)) + .forEach(filteredGroups::add); return filteredGroups; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java index 7ae4e11793..b15aa92059 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpointSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -193,7 +193,7 @@ abstract class HealthEndpointSupport { protected final CompositeHealth getCompositeHealth(ApiVersion apiVersion, Map components, StatusAggregator statusAggregator, boolean showComponents, Set groupNames) { Status status = statusAggregator - .getAggregateStatus(components.values().stream().map(this::getStatus).collect(Collectors.toSet())); + .getAggregateStatus(components.values().stream().map(this::getStatus).collect(Collectors.toSet())); Map instances = showComponents ? components : null; if (groupNames != null) { return new SystemHealth(apiVersion, status, instances, groupNames); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java index f5c10c89f5..e8ed933cbb 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapter.java @@ -43,8 +43,10 @@ abstract class NamedContributorsMapAdapter implements NamedContributors Assert.notNull(map, "Map must not be null"); Assert.notNull(valueAdapter, "ValueAdapter must not be null"); map.keySet().forEach(this::validateKey); - this.map = Collections.unmodifiableMap(map.entrySet().stream().collect(LinkedHashMap::new, - (result, entry) -> result.put(entry.getKey(), adapt(entry.getValue(), valueAdapter)), Map::putAll)); + this.map = Collections.unmodifiableMap(map.entrySet() + .stream() + .collect(LinkedHashMap::new, + (result, entry) -> result.put(entry.getKey(), adapt(entry.getValue(), valueAdapter)), Map::putAll)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java index 74e4de2ee7..df4f296502 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -101,9 +101,11 @@ public class ReactiveHealthEndpointWebExtension protected Mono aggregateContributions(ApiVersion apiVersion, Map> contributions, StatusAggregator statusAggregator, boolean showComponents, Set groupNames) { - return Flux.fromIterable(contributions.entrySet()).flatMap(NamedHealthComponent::create) - .collectMap(NamedHealthComponent::getName, NamedHealthComponent::getHealth).map((components) -> this - .getCompositeHealth(apiVersion, components, statusAggregator, showComponents, groupNames)); + return Flux.fromIterable(contributions.entrySet()) + .flatMap(NamedHealthComponent::create) + .collectMap(NamedHealthComponent::getName, NamedHealthComponent::getHealth) + .map((components) -> this.getCompositeHealth(apiVersion, components, statusAggregator, showComponents, + groupNames)); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java index 4f63d06cab..1261e80b47 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/InfoPropertiesInfoContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -91,7 +91,7 @@ public abstract class InfoPropertiesInfoContributor im */ protected Map extractContent(PropertySource propertySource) { return new Binder(ConfigurationPropertySources.from(propertySource)).bind("", STRING_OBJECT_MAP) - .orElseGet(LinkedHashMap::new); + .orElseGet(LinkedHashMap::new); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java index 2b784460af..3c8f961d53 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/jms/JmsHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,7 @@ public class JmsHealthIndicator extends AbstractHealthIndicator { try { if (!this.latch.await(5, TimeUnit.SECONDS)) { JmsHealthIndicator.this.logger - .warn("Connection failed to start within 5 seconds and will be closed."); + .warn("Connection failed to start within 5 seconds and will be closed."); closeConnection(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java index ba709128ac..a7474dd188 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ public class LiquibaseEndpoint { Map liquibaseBeans = new HashMap<>(); DatabaseFactory factory = DatabaseFactory.getInstance(); target.getBeansOfType(SpringLiquibase.class) - .forEach((name, liquibase) -> liquibaseBeans.put(name, createReport(liquibase, factory))); + .forEach((name, liquibase) -> liquibaseBeans.put(name, createReport(liquibase, factory))); ApplicationContext parent = target.getParent(); contextBeans.put(target.getId(), new ContextLiquibaseBeansDescriptor(liquibaseBeans, (parent != null) ? parent.getId() : null)); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java index 995e384621..b120533b2d 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -154,9 +154,9 @@ public class HeapDumpWebEndpoint { protected HotSpotDiagnosticMXBeanHeapDumper() { try { Class diagnosticMXBeanClass = ClassUtils - .resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null); + .resolveClassName("com.sun.management.HotSpotDiagnosticMXBean", null); this.diagnosticMXBean = ManagementFactory - .getPlatformMXBean((Class) diagnosticMXBeanClass); + .getPlatformMXBean((Class) diagnosticMXBeanClass); this.dumpHeapMethod = ReflectionUtils.findMethod(diagnosticMXBeanClass, "dumpHeap", String.class, Boolean.TYPE); } @@ -285,7 +285,7 @@ public class HeapDumpWebEndpoint { } catch (IOException ex) { TemporaryFileSystemResource.this.logger - .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); + .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java index 1ebabacf8f..bd677ce400 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -114,8 +114,12 @@ public class MetricsEndpoint { private Collection findFirstMatchingMeters(CompositeMeterRegistry composite, String name, Iterable tags) { - return composite.getRegistries().stream().map((registry) -> findFirstMatchingMeters(registry, name, tags)) - .filter((matching) -> !matching.isEmpty()).findFirst().orElse(Collections.emptyList()); + return composite.getRegistries() + .stream() + .map((registry) -> findFirstMatchingMeters(registry, name, tags)) + .filter((matching) -> !matching.isEmpty()) + .findFirst() + .orElse(Collections.emptyList()); } private Map getSamples(Collection meters) { @@ -125,8 +129,9 @@ public class MetricsEndpoint { } private void mergeMeasurements(Map samples, Meter meter) { - meter.measure().forEach((measurement) -> samples.merge(measurement.getStatistic(), measurement.getValue(), - mergeFunction(measurement.getStatistic()))); + meter.measure() + .forEach((measurement) -> samples.merge(measurement.getStatistic(), measurement.getValue(), + mergeFunction(measurement.getStatistic()))); } private BiFunction mergeFunction(Statistic statistic) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java index b5dea5a746..3950bbd43e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -72,9 +72,11 @@ public class CacheMetricsRegistrar { private MeterBinder getMeterBinder(Cache cache, Tags tags) { Tags cacheTags = tags.and(getAdditionalTags(cache)); return LambdaSafe.callbacks(CacheMeterBinderProvider.class, this.binderProviders, cache) - .withLogger(CacheMetricsRegistrar.class) - .invokeAnd((binderProvider) -> binderProvider.getMeterBinder(cache, cacheTags)).filter(Objects::nonNull) - .findFirst().orElse(null); + .withLogger(CacheMetricsRegistrar.class) + .invokeAnd((binderProvider) -> binderProvider.getMeterBinder(cache, cacheTags)) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java index a6ffd9413c..ce331b3cc0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,8 +56,8 @@ public class HazelcastCacheMeterBinderProvider implements CacheMeterBinderProvid try { Method nativeCacheAccessor = ReflectionUtils.findMethod(HazelcastCache.class, "getNativeCache"); Object nativeCache = ReflectionUtils.invokeMethod(nativeCacheAccessor, cache); - return HazelcastCacheMetrics.class.getConstructor(Object.class, Iterable.class).newInstance(nativeCache, - tags); + return HazelcastCacheMetrics.class.getConstructor(Object.class, Iterable.class) + .newInstance(nativeCache, tags); } catch (Exception ex) { throw new IllegalStateException("Failed to create MeterBinder for Hazelcast", ex); @@ -72,8 +72,9 @@ public class HazelcastCacheMeterBinderProvider implements CacheMeterBinderProvid Method getNativeCacheMethod = ReflectionUtils.findMethod(HazelcastCache.class, "getNativeCache"); Assert.state(getNativeCacheMethod != null, "Unable to find 'getNativeCache' method"); Constructor constructor = HazelcastCacheMetrics.class.getConstructor(Object.class, Iterable.class); - hints.reflection().registerMethod(getNativeCacheMethod, ExecutableMode.INVOKE) - .registerConstructor(constructor, ExecutableMode.INVOKE); + hints.reflection() + .registerMethod(getNativeCacheMethod, ExecutableMode.INVOKE) + .registerConstructor(constructor, ExecutableMode.INVOKE); } catch (NoSuchMethodException ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java index 45a026bb4e..a9469484d6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,15 +69,20 @@ public class RedisCacheMetrics extends CacheMeterBinder { @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { FunctionCounter.builder("cache.removals", this.cache, (cache) -> cache.getStatistics().getDeletes()) - .tags(getTagsWithCacheName()).description("Cache removals").register(registry); + .tags(getTagsWithCacheName()) + .description("Cache removals") + .register(registry); FunctionCounter.builder("cache.gets", this.cache, (cache) -> cache.getStatistics().getPending()) - .tags(getTagsWithCacheName()).tag("result", "pending").description("The number of pending requests") - .register(registry); + .tags(getTagsWithCacheName()) + .tag("result", "pending") + .description("The number of pending requests") + .register(registry); TimeGauge - .builder("cache.lock.duration", this.cache, TimeUnit.NANOSECONDS, - (cache) -> cache.getStatistics().getLockWaitDuration(TimeUnit.NANOSECONDS)) - .tags(getTagsWithCacheName()).description("The time the cache has spent waiting on a lock") - .register(registry); + .builder("cache.lock.duration", this.cache, TimeUnit.NANOSECONDS, + (cache) -> cache.getStatistics().getLockWaitDuration(TimeUnit.NANOSECONDS)) + .tags(getTagsWithCacheName()) + .description("The time the cache has spent waiting on a lock") + .register(registry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java index a30257d960..f0c66981cc 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/data/MetricsRepositoryMethodInvocationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,8 +69,10 @@ public class MetricsRepositoryMethodInvocationListener implements RepositoryMeth Iterable tags = this.tagsProvider.repositoryTags(invocation); long duration = invocation.getDuration(TimeUnit.NANOSECONDS); AutoTimer.apply(this.autoTimer, this.metricName, annotations, - (builder) -> builder.description("Duration of repository invocations").tags(tags) - .register(this.registrySupplier.get()).record(duration, TimeUnit.NANOSECONDS)); + (builder) -> builder.description("Duration of repository invocations") + .tags(tags) + .register(this.registrySupplier.get()) + .record(duration, TimeUnit.NANOSECONDS)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java index 3ebdccd0ff..caf29f30ff 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -88,7 +88,9 @@ public class DataSourcePoolMetrics implements MeterBinder { Function function) { if (function.apply(this.dataSource) != null) { Gauge.builder("jdbc.connections." + metricName, this.dataSource, (m) -> function.apply(m).doubleValue()) - .tags(this.tags).description(description).register(registry); + .tags(this.tags) + .description(description) + .register(registry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java index 845ceae8ee..36a499fc0f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/r2dbc/ConnectionPoolMetrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -50,22 +50,21 @@ public class ConnectionPoolMetrics implements MeterBinder { this.pool.getMetrics().ifPresent((poolMetrics) -> { bindConnectionPoolMetric(registry, Gauge.builder(metricKey("acquired"), poolMetrics, PoolMetrics::acquiredSize) - .description("Size of successfully acquired connections which are in active use.")); + .description("Size of successfully acquired connections which are in active use.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("allocated"), poolMetrics, PoolMetrics::allocatedSize) - .description("Size of allocated connections in the pool which are in active use or idle.")); + .description("Size of allocated connections in the pool which are in active use or idle.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("idle"), poolMetrics, PoolMetrics::idleSize) - .description("Size of idle connections in the pool.")); + .description("Size of idle connections in the pool.")); bindConnectionPoolMetric(registry, - Gauge.builder(metricKey("pending"), poolMetrics, PoolMetrics::pendingAcquireSize).description( - "Size of pending to acquire connections from the underlying connection factory.")); + Gauge.builder(metricKey("pending"), poolMetrics, PoolMetrics::pendingAcquireSize) + .description("Size of pending to acquire connections from the underlying connection factory.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("max.allocated"), poolMetrics, PoolMetrics::getMaxAllocatedSize) - .description("Maximum size of allocated connections that this pool allows.")); + .description("Maximum size of allocated connections that this pool allows.")); bindConnectionPoolMetric(registry, Gauge.builder(metricKey("max.pending"), poolMetrics, PoolMetrics::getMaxPendingAcquireSize) - .description( - "Maximum size of pending state to acquire connections that this pool allows.")); + .description("Maximum size of pending state to acquire connections that this pool allows.")); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java index 12e900763a..7f5a4df7c1 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -116,8 +116,10 @@ public class StartupTimeMetricsListener implements SmartApplicationListener { SpringApplication springApplication) { if (timeTaken != null) { Iterable tags = createTagsFrom(springApplication); - TimeGauge.builder(name, timeTaken::toMillis, TimeUnit.MILLISECONDS).tags(tags).description(description) - .register(this.meterRegistry); + TimeGauge.builder(name, timeTaken::toMillis, TimeUnit.MILLISECONDS) + .tags(tags) + .description(description) + .register(this.meterRegistry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizer.java index 49f2601b94..647cf9be07 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ public class ObservationWebClientCustomizer implements WebClientCustomizer { @Override public void customize(WebClient.Builder webClientBuilder) { webClientBuilder.observationRegistry(this.observationRegistry) - .observationConvention(this.observationConvention); + .observationConvention(this.observationConvention); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java index aec1250275..42eaaf5e66 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthDetailsHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -38,8 +38,9 @@ class Neo4jHealthDetailsHandler { void addHealthDetails(Builder builder, Neo4jHealthDetails healthDetails) { ResultSummary summary = healthDetails.getSummary(); ServerInfo serverInfo = summary.server(); - builder.up().withDetail("server", healthDetails.getVersion() + "@" + serverInfo.address()).withDetail("edition", - healthDetails.getEdition()); + builder.up() + .withDetail("server", healthDetails.getVersion() + "@" + serverInfo.address()) + .withDetail("edition", healthDetails.getEdition()); DatabaseInfo databaseInfo = summary.database(); if (StringUtils.hasText(databaseInfo.name())) { builder.withDetail("database", databaseInfo.name()); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java index 1cab0e246c..86fa156fb3 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,9 @@ public class Neo4jHealthIndicator extends AbstractHealthIndicator { /** * The default session config to use while connecting. */ - static final SessionConfig DEFAULT_SESSION_CONFIG = SessionConfig.builder().withDefaultAccessMode(AccessMode.WRITE) - .build(); + static final SessionConfig DEFAULT_SESSION_CONFIG = SessionConfig.builder() + .withDefaultAccessMode(AccessMode.WRITE) + .build(); private final Driver driver; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java index 55cb876892..d959dc3b30 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,12 +57,12 @@ public final class Neo4jReactiveHealthIndicator extends AbstractReactiveHealthIn @Override protected Mono doHealthCheck(Health.Builder builder) { return runHealthCheckQuery() - .doOnError(SessionExpiredException.class, - (ex) -> logger.warn(Neo4jHealthIndicator.MESSAGE_SESSION_EXPIRED)) - .retryWhen(Retry.max(1).filter(SessionExpiredException.class::isInstance)).map((healthDetails) -> { - this.healthDetailsHandler.addHealthDetails(builder, healthDetails); - return builder.build(); - }); + .doOnError(SessionExpiredException.class, (ex) -> logger.warn(Neo4jHealthIndicator.MESSAGE_SESSION_EXPIRED)) + .retryWhen(Retry.max(1).filter(SessionExpiredException.class::isInstance)) + .map((healthDetails) -> { + this.healthDetailsHandler.addHealthDetails(builder, healthDetails); + return builder.build(); + }); } Mono runHealthCheckQuery() { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java index de40cb092f..0e0b64cd32 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/quartz/QuartzEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,8 +66,8 @@ import org.springframework.util.Assert; public class QuartzEndpoint { private static final Comparator TRIGGER_COMPARATOR = Comparator - .comparing(Trigger::getNextFireTime, Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(Comparator.comparingInt(Trigger::getPriority).reversed()); + .comparing(Trigger::getNextFireTime, Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(Comparator.comparingInt(Trigger::getPriority).reversed()); private final Scheduler scheduler; @@ -98,8 +98,10 @@ public class QuartzEndpoint { public QuartzGroupsDescriptor quartzJobGroups() throws SchedulerException { Map result = new LinkedHashMap<>(); for (String groupName : this.scheduler.getJobGroupNames()) { - List jobs = this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName)).stream() - .map((key) -> key.getName()).toList(); + List jobs = this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName)) + .stream() + .map((key) -> key.getName()) + .toList(); result.put(groupName, Collections.singletonMap("jobs", jobs)); } return new QuartzGroupsDescriptor(result); @@ -116,8 +118,11 @@ public class QuartzEndpoint { for (String groupName : this.scheduler.getTriggerGroupNames()) { Map groupDetails = new LinkedHashMap<>(); groupDetails.put("paused", pausedTriggerGroups.contains(groupName)); - groupDetails.put("triggers", this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(groupName)) - .stream().map((key) -> key.getName()).toList()); + groupDetails.put("triggers", + this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(groupName)) + .stream() + .map((key) -> key.getName()) + .toList()); result.put(groupName, groupDetails); } return new QuartzGroupsDescriptor(result); @@ -570,9 +575,12 @@ public class QuartzEndpoint { private final TriggerType type; private static TriggerDescriptor of(Trigger trigger) { - return DESCRIBERS.entrySet().stream().filter((entry) -> entry.getKey().isInstance(trigger)) - .map((entry) -> entry.getValue().apply(trigger)).findFirst() - .orElse(new CustomTriggerDescriptor(trigger)); + return DESCRIBERS.entrySet() + .stream() + .filter((entry) -> entry.getKey().isInstance(trigger)) + .map((entry) -> entry.getValue().apply(trigger)) + .findFirst() + .orElse(new CustomTriggerDescriptor(trigger)); } protected TriggerDescriptor(Trigger trigger, TriggerType type) { @@ -721,7 +729,7 @@ public class QuartzEndpoint { protected void appendSummary(Map content) { content.put("interval", getIntervalDuration(this.trigger.getRepeatInterval(), this.trigger.getRepeatIntervalUnit()) - .toMillis()); + .toMillis()); putIfNoNull(content, "daysOfWeek", this.trigger.getDaysOfWeek()); putIfNoNull(content, "startTimeOfDay", getLocalTime(this.trigger.getStartTimeOfDay())); putIfNoNull(content, "endTimeOfDay", getLocalTime(this.trigger.getEndTimeOfDay())); @@ -752,7 +760,7 @@ public class QuartzEndpoint { protected void appendSummary(Map content) { content.put("interval", getIntervalDuration(this.trigger.getRepeatInterval(), this.trigger.getRepeatIntervalUnit()) - .toMillis()); + .toMillis()); putIfNoNull(content, "timeZone", this.trigger.getTimeZone()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java index 55417c7f4e..d1c3d942cb 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -70,8 +70,8 @@ public class ConnectionFactoryHealthIndicator extends AbstractReactiveHealthIndi @Override protected final Mono doHealthCheck(Builder builder) { - return validate(builder).defaultIfEmpty(builder.build()).onErrorResume(Exception.class, - (ex) -> Mono.just(builder.down(ex).build())); + return validate(builder).defaultIfEmpty(builder.build()) + .onErrorResume(Exception.class, (ex) -> Mono.just(builder.down(ex).build())); } private Mono validate(Builder builder) { @@ -84,7 +84,8 @@ public class ConnectionFactoryHealthIndicator extends AbstractReactiveHealthIndi builder.withDetail("validationQuery", this.validationQuery); Mono connectionValidation = Mono.usingWhen(this.connectionFactory.create(), (conn) -> Flux.from(conn.createStatement(this.validationQuery).execute()) - .flatMap((it) -> it.map(this::extractResult)).next(), + .flatMap((it) -> it.map(this::extractResult)) + .next(), Connection::close, (o, throwable) -> o.close(), Connection::close); return connectionValidation.map((result) -> builder.up().withDetail("result", result).build()); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java index 05b56708f3..bdfd42bb43 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,9 +67,11 @@ public class ScheduledTasksEndpoint { @ReadOperation public ScheduledTasksDescriptor scheduledTasks() { Map> descriptionsByType = this.scheduledTaskHolders.stream() - .flatMap((holder) -> holder.getScheduledTasks().stream()).map(ScheduledTask::getTask) - .map(TaskDescriptor::of).filter(Objects::nonNull) - .collect(Collectors.groupingBy(TaskDescriptor::getType)); + .flatMap((holder) -> holder.getScheduledTasks().stream()) + .map(ScheduledTask::getTask) + .map(TaskDescriptor::of) + .filter(Objects::nonNull) + .collect(Collectors.groupingBy(TaskDescriptor::getType)); return new ScheduledTasksDescriptor(descriptionsByType); } @@ -130,8 +132,12 @@ public class ScheduledTasksEndpoint { private final RunnableDescriptor runnable; private static TaskDescriptor of(Task task) { - return DESCRIBERS.entrySet().stream().filter((entry) -> entry.getKey().isInstance(task)) - .map((entry) -> entry.getValue().apply(task)).findFirst().orElse(null); + return DESCRIBERS.entrySet() + .stream() + .filter((entry) -> entry.getKey().isInstance(task)) + .map((entry) -> entry.getValue().apply(task)) + .findFirst() + .orElse(null); } private static TaskDescriptor describeTriggerTask(TriggerTask triggerTask) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/startup/StartupEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/startup/StartupEndpoint.java index a713fa7b5d..d0155812ee 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/startup/StartupEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/startup/StartupEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -93,23 +93,25 @@ public class StartupEndpoint { static class StartupEndpointRuntimeHints implements RuntimeHintsRegistrar { private static final TypeReference DEFAULT_TAG = TypeReference - .of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep$DefaultTag"); + .of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep$DefaultTag"); private static final TypeReference BUFFERED_STARTUP_STEP = TypeReference - .of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep"); + .of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep"); private static final TypeReference FLIGHT_RECORDER_TAG = TypeReference - .of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep$FlightRecorderTag"); + .of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep$FlightRecorderTag"); private static final TypeReference FLIGHT_RECORDER_STARTUP_STEP = TypeReference - .of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep"); + .of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep"); @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - hints.reflection().registerType(DEFAULT_TAG, (typeHint) -> typeHint.onReachableType(BUFFERED_STARTUP_STEP) + hints.reflection() + .registerType(DEFAULT_TAG, (typeHint) -> typeHint.onReachableType(BUFFERED_STARTUP_STEP) + .withMembers(MemberCategory.INVOKE_PUBLIC_METHODS)); + hints.reflection() + .registerType(FLIGHT_RECORDER_TAG, (typeHint) -> typeHint.onReachableType(FLIGHT_RECORDER_STARTUP_STEP) .withMembers(MemberCategory.INVOKE_PUBLIC_METHODS)); - hints.reflection().registerType(FLIGHT_RECORDER_TAG, (typeHint) -> typeHint - .onReachableType(FLIGHT_RECORDER_STARTUP_STEP).withMembers(MemberCategory.INVOKE_PUBLIC_METHODS)); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java index 88dde19756..e18dca9753 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,9 +68,11 @@ public class DiskSpaceHealthIndicator extends AbstractHealthIndicator { this.path.getAbsolutePath(), diskFreeInBytes, this.threshold)); builder.down(); } - builder.withDetail("total", this.path.getTotalSpace()).withDetail("free", diskFreeInBytes) - .withDetail("threshold", this.threshold.toBytes()).withDetail("path", this.path.getAbsolutePath()) - .withDetail("exists", this.path.exists()); + builder.withDetail("total", this.path.getTotalSpace()) + .withDetail("free", diskFreeInBytes) + .withDetail("threshold", this.threshold.toBytes()) + .withDetail("path", this.path.getAbsolutePath()) + .withDetail("exists", this.path.exists()); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilter.java index fb8f8558e2..25662726a7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,7 +73,7 @@ public class HttpExchangesWebFilter implements WebFilter, Ordered { Mono principal = exchange.getPrincipal().cast(Object.class).defaultIfEmpty(NONE); Mono session = exchange.getSession().cast(Object.class).defaultIfEmpty(NONE); return Mono.zip(PrincipalAndSession::new, principal, session) - .flatMap((principalAndSession) -> filter(exchange, chain, principalAndSession)); + .flatMap((principalAndSession) -> filter(exchange, chain, principalAndSession)); } private Mono filter(ServerWebExchange exchange, WebFilterChain chain, diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java index 9a691929bb..8d26258e04 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -61,8 +61,8 @@ import org.springframework.web.util.pattern.PathPattern; public class DispatcherHandlersMappingDescriptionProvider implements MappingDescriptionProvider { private static final List> descriptionProviders = Arrays - .asList(new RequestMappingInfoHandlerMappingDescriptionProvider(), - new UrlHandlerMappingDescriptionProvider(), new RouterFunctionMappingDescriptionProvider()); + .asList(new RequestMappingInfoHandlerMappingDescriptionProvider(), new UrlHandlerMappingDescriptionProvider(), + new RouterFunctionMappingDescriptionProvider()); @Override public String getMappingName() { @@ -73,7 +73,7 @@ public class DispatcherHandlersMappingDescriptionProvider implements MappingDesc public Map> describeMappings(ApplicationContext context) { Map> mappings = new HashMap<>(); context.getBeansOfType(DispatcherHandler.class) - .forEach((name, handler) -> mappings.put(name, describeMappings(handler))); + .forEach((name, handler) -> mappings.put(name, describeMappings(handler))); return mappings; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java index 2e2baa5fd2..30085afb6b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/reactive/RequestMappingConditionsDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,17 +48,32 @@ public class RequestMappingConditionsDescription { private final List produces; RequestMappingConditionsDescription(RequestMappingInfo requestMapping) { - this.consumes = requestMapping.getConsumesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).toList(); - this.headers = requestMapping.getHeadersCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).toList(); + this.consumes = requestMapping.getConsumesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .toList(); + this.headers = requestMapping.getHeadersCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .toList(); this.methods = requestMapping.getMethodsCondition().getMethods(); - this.params = requestMapping.getParamsCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).toList(); - this.patterns = requestMapping.getPatternsCondition().getPatterns().stream().map(PathPattern::getPatternString) - .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); - this.produces = requestMapping.getProducesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).toList(); + this.params = requestMapping.getParamsCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .toList(); + this.patterns = requestMapping.getPatternsCondition() + .getPatterns() + .stream() + .map(PathPattern::getPatternString) + .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); + this.produces = requestMapping.getProducesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .toList(); } public List getConsumes() { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java index 148676e92a..e5b1c36b4f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -95,8 +95,10 @@ final class DispatcherServletHandlerMappings { } private Optional findContext() { - return Stream.of(this.webServer.getTomcat().getHost().findChildren()).filter(Context.class::isInstance) - .map(Context.class::cast).findFirst(); + return Stream.of(this.webServer.getTomcat().getHost().findChildren()) + .filter(Context.class::isInstance) + .map(Context.class::cast) + .findFirst(); } private void initializeServlet(Context context, String name) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java index 8415d39e69..ffb48304ee 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -192,8 +192,8 @@ public class DispatcherServletsMappingDescriptionProvider implements MappingDesc public List describe(Iterable handlerMapping) { List descriptions = new ArrayList<>(); for (Object delegate : handlerMapping) { - descriptions.addAll( - DispatcherServletsMappingDescriptionProvider.describe(delegate, this.descriptionProviders)); + descriptions + .addAll(DispatcherServletsMappingDescriptionProvider.describe(delegate, this.descriptionProviders)); } return descriptions; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java index 1a80baaa1a..7a5d68c6a7 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,8 +44,12 @@ public class FiltersMappingDescriptionProvider implements MappingDescriptionProv @Override public List describeMappings(ApplicationContext context) { if (context instanceof WebApplicationContext webApplicationContext) { - return webApplicationContext.getServletContext().getFilterRegistrations().values().stream() - .map(FilterRegistrationMappingDescription::new).toList(); + return webApplicationContext.getServletContext() + .getFilterRegistrations() + .values() + .stream() + .map(FilterRegistrationMappingDescription::new) + .toList(); } return Collections.emptyList(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java index 93a9526506..131a9c7d55 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/RequestMappingConditionsDescription.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,16 +46,28 @@ public class RequestMappingConditionsDescription { private final List produces; RequestMappingConditionsDescription(RequestMappingInfo requestMapping) { - this.consumes = requestMapping.getConsumesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).toList(); - this.headers = requestMapping.getHeadersCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).toList(); + this.consumes = requestMapping.getConsumesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .toList(); + this.headers = requestMapping.getHeadersCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .toList(); this.methods = requestMapping.getMethodsCondition().getMethods(); - this.params = requestMapping.getParamsCondition().getExpressions().stream() - .map(NameValueExpressionDescription::new).toList(); + this.params = requestMapping.getParamsCondition() + .getExpressions() + .stream() + .map(NameValueExpressionDescription::new) + .toList(); this.patterns = extractPathPatterns(requestMapping); - this.produces = requestMapping.getProducesCondition().getExpressions().stream() - .map(MediaTypeExpressionDescription::new).toList(); + this.produces = requestMapping.getProducesCondition() + .getExpressions() + .stream() + .map(MediaTypeExpressionDescription::new) + .toList(); } private Set extractPathPatterns(RequestMappingInfo requestMapping) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java index 47ebfe9946..c64ff23f29 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,8 +44,12 @@ public class ServletsMappingDescriptionProvider implements MappingDescriptionPro @Override public List describeMappings(ApplicationContext context) { if (context instanceof WebApplicationContext webApplicationContext) { - return webApplicationContext.getServletContext().getServletRegistrations().values().stream() - .map(ServletRegistrationMappingDescription::new).toList(); + return webApplicationContext.getServletContext() + .getServletRegistrations() + .values() + .stream() + .map(ServletRegistrationMappingDescription::new) + .toList(); } return Collections.emptyList(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java index 0e7ab62d5c..63856b2f16 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class RabbitHealthIndicatorTests { @Test void createWhenRabbitTemplateIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RabbitHealthIndicator(null)) - .withMessageContaining("RabbitTemplate must not be null"); + .withMessageContaining("RabbitTemplate must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java index a1bf034055..97b3cd270f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java @@ -59,15 +59,15 @@ class AuditEventTests { @Test void nullTimestamp() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", "b"))) - .withMessageContaining("Timestamp must not be null"); + .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", Collections.singletonMap("a", "b"))) + .withMessageContaining("Timestamp must not be null"); } @Test void nullType() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AuditEvent("phil", null, Collections.singletonMap("a", "b"))) - .withMessageContaining("Type must not be null"); + .isThrownBy(() -> new AuditEvent("phil", null, Collections.singletonMap("a", "b"))) + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java index 66e60ca94a..324565a836 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventsEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,32 +37,54 @@ class AuditEventsEndpointWebIntegrationTests { @WebEndpointTest void allEvents(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/auditevents").build()).exchange().expectStatus().isOk() - .expectBody().jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("admin").appendElement("admin").appendElement("user")); + client.get() + .uri((builder) -> builder.path("/actuator/auditevents").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("admin").appendElement("admin").appendElement("user")); } @WebEndpointTest void eventsAfter(WebTestClient client) { client.get() - .uri((builder) -> builder.path("/actuator/auditevents") - .queryParam("after", "2016-11-01T13:00:00%2B00:00").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("events").isEmpty(); + .uri((builder) -> builder.path("/actuator/auditevents") + .queryParam("after", "2016-11-01T13:00:00%2B00:00") + .build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events") + .isEmpty(); } @WebEndpointTest void eventsWithPrincipal(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("principal", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("user")); + client.get() + .uri((builder) -> builder.path("/actuator/auditevents").queryParam("principal", "user").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("user")); } @WebEndpointTest void eventsWithType(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/auditevents").queryParam("type", "logout").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("events.[*].principal") - .isEqualTo(new JSONArray().appendElement("admin")).jsonPath("events.[*].type") - .isEqualTo(new JSONArray().appendElement("logout")); + client.get() + .uri((builder) -> builder.path("/actuator/auditevents").queryParam("type", "logout").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("events.[*].principal") + .isEqualTo(new JSONArray().appendElement("admin")) + .jsonPath("events.[*].type") + .isEqualTo(new JSONArray().appendElement("logout")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java index 057f87dd6b..cb1ab53956 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java @@ -63,7 +63,7 @@ class InMemoryAuditEventRepositoryTests { void addNullAuditEvent() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); assertThatIllegalArgumentException().isThrownBy(() -> repository.add(null)) - .withMessageContaining("AuditEvent must not be null"); + .withMessageContaining("AuditEvent must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java index e7823e4f6c..a874e4be5f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/availability/AvailabilityStateHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -44,30 +44,33 @@ class AvailabilityStateHealthIndicatorTests { @Test void createWhenApplicationAvailabilityIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AvailabilityStateHealthIndicator(null, LivenessState.class, (statusMappings) -> { - })).withMessage("ApplicationAvailability must not be null"); + .isThrownBy(() -> new AvailabilityStateHealthIndicator(null, LivenessState.class, (statusMappings) -> { + })) + .withMessage("ApplicationAvailability must not be null"); } @Test void createWhenStateTypeIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy( () -> new AvailabilityStateHealthIndicator(this.applicationAvailability, null, (statusMappings) -> { - })).withMessage("StateType must not be null"); + })) + .withMessage("StateType must not be null"); } @Test void createWhenStatusMappingIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new AvailabilityStateHealthIndicator(this.applicationAvailability, LivenessState.class, null)) - .withMessage("StatusMappings must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new AvailabilityStateHealthIndicator(this.applicationAvailability, LivenessState.class, null)) + .withMessage("StatusMappings must not be null"); } @Test void createWhenStatusMappingDoesNotCoverAllEnumsThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new AvailabilityStateHealthIndicator(this.applicationAvailability, - LivenessState.class, (statusMappings) -> statusMappings.add(LivenessState.CORRECT, Status.UP))) - .withMessage("StatusMappings does not include BROKEN"); + .isThrownBy(() -> new AvailabilityStateHealthIndicator(this.applicationAvailability, LivenessState.class, + (statusMappings) -> statusMappings.add(LivenessState.CORRECT, Status.UP))) + .withMessage("StatusMappings does not include BROKEN"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java index ac9f428c17..0494df8104 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/beans/BeansEndpointTests.java @@ -46,7 +46,7 @@ class BeansEndpointTests { @Test void beansAreFound() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class); + .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { BeansDescriptor result = context.getBean(BeansEndpoint.class).beans(); ContextBeansDescriptor descriptor = result.getContexts().get(context.getId()); @@ -60,13 +60,13 @@ class BeansEndpointTests { @Test void infrastructureBeansAreOmitted() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class); + .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { ConfigurableListableBeanFactory factory = (ConfigurableListableBeanFactory) context - .getAutowireCapableBeanFactory(); + .getAutowireCapableBeanFactory(); List infrastructureBeans = Stream.of(context.getBeanDefinitionNames()) - .filter((name) -> BeanDefinition.ROLE_INFRASTRUCTURE == factory.getBeanDefinition(name).getRole()) - .toList(); + .filter((name) -> BeanDefinition.ROLE_INFRASTRUCTURE == factory.getBeanDefinition(name).getRole()) + .toList(); BeansDescriptor result = context.getBean(BeansEndpoint.class).beans(); ContextBeansDescriptor contextDescriptor = result.getContexts().get(context.getId()); Map beans = contextDescriptor.getBeans(); @@ -79,7 +79,7 @@ class BeansEndpointTests { @Test void lazyBeansAreOmitted() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class, LazyBeanConfiguration.class); + .withUserConfiguration(EndpointConfiguration.class, LazyBeanConfiguration.class); contextRunner.run((context) -> { BeansDescriptor result = context.getBean(BeansEndpoint.class).beans(); ContextBeansDescriptor contextDescriptor = result.getContexts().get(context.getId()); @@ -91,14 +91,15 @@ class BeansEndpointTests { @Test void beansInParentContextAreFound() { ApplicationContextRunner parentRunner = new ApplicationContextRunner() - .withUserConfiguration(BeanConfiguration.class); + .withUserConfiguration(BeanConfiguration.class); parentRunner.run((parent) -> { - new ApplicationContextRunner().withUserConfiguration(EndpointConfiguration.class).withParent(parent) - .run((child) -> { - BeansDescriptor result = child.getBean(BeansEndpoint.class).beans(); - assertThat(result.getContexts().get(parent.getId()).getBeans()).containsKey("bean"); - assertThat(result.getContexts().get(child.getId()).getBeans()).containsKey("endpoint"); - }); + new ApplicationContextRunner().withUserConfiguration(EndpointConfiguration.class) + .withParent(parent) + .run((child) -> { + BeansDescriptor result = child.getBean(BeansEndpoint.class).beans(); + assertThat(result.getContexts().get(parent.getId()).getBeans()).containsKey("bean"); + assertThat(result.getContexts().get(child.getId()).getBeans()).containsKey("endpoint"); + }); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java index a0f424d095..f87ed86969 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,9 @@ class CachesEndpointTests { cacheManagers.put("another", new ConcurrentMapCacheManager("c", "dupe-cache")); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); assertThatExceptionOfType(NonUniqueCacheException.class).isThrownBy(() -> endpoint.cache("dupe-cache", null)) - .withMessageContaining("dupe-cache").withMessageContaining("test").withMessageContaining("another"); + .withMessageContaining("dupe-cache") + .withMessageContaining("test") + .withMessageContaining("another"); } @Test @@ -147,8 +149,10 @@ class CachesEndpointTests { cacheManagers.put("another", cacheManager(mockCache("dupe-cache"))); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); assertThatExceptionOfType(NonUniqueCacheException.class) - .isThrownBy(() -> endpoint.clearCache("dupe-cache", null)).withMessageContaining("dupe-cache") - .withMessageContaining("test").withMessageContaining("another"); + .isThrownBy(() -> endpoint.clearCache("dupe-cache", null)) + .withMessageContaining("dupe-cache") + .withMessageContaining("test") + .withMessageContaining("another"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java index 1feb23577a..28f4742c87 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -40,18 +40,36 @@ class CachesEndpointWebIntegrationTests { @WebEndpointTest void allCaches(WebTestClient client) { - client.get().uri("/actuator/caches").exchange().expectStatus().isOk().expectBody() - .jsonPath("cacheManagers.one.caches.a.target").isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.one.caches.b.target").isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.two.caches.a.target").isEqualTo(ConcurrentHashMap.class.getName()) - .jsonPath("cacheManagers.two.caches.c.target").isEqualTo(ConcurrentHashMap.class.getName()); + client.get() + .uri("/actuator/caches") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("cacheManagers.one.caches.a.target") + .isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.one.caches.b.target") + .isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.two.caches.a.target") + .isEqualTo(ConcurrentHashMap.class.getName()) + .jsonPath("cacheManagers.two.caches.c.target") + .isEqualTo(ConcurrentHashMap.class.getName()); } @WebEndpointTest void namedCache(WebTestClient client) { - client.get().uri("/actuator/caches/b").exchange().expectStatus().isOk().expectBody().jsonPath("name") - .isEqualTo("b").jsonPath("cacheManager").isEqualTo("one").jsonPath("target") - .isEqualTo(ConcurrentHashMap.class.getName()); + client.get() + .uri("/actuator/caches/b") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("name") + .isEqualTo("b") + .jsonPath("cacheManager") + .isEqualTo("one") + .jsonPath("target") + .isEqualTo(ConcurrentHashMap.class.getName()); } @WebEndpointTest diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java index f7ee4be84f..01e6b5f515 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cassandra/CassandraDriverReactiveHealthIndicatorTests.java @@ -59,8 +59,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test @@ -68,8 +69,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } @Test @@ -77,8 +79,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UNKNOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } @Test @@ -86,8 +89,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.FORCED_DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } @Test @@ -95,8 +99,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP, NodeState.DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test @@ -104,8 +109,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP, NodeState.UNKNOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test @@ -113,8 +119,9 @@ class CassandraDriverReactiveHealthIndicatorTests { CqlSession session = mockCqlSessionWithNodeState(NodeState.UP, NodeState.FORCED_DOWN); CassandraDriverReactiveHealthIndicator healthIndicator = new CassandraDriverReactiveHealthIndicator(session); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.UP)) + .verifyComplete(); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java index d5cb604c08..45b37c3e6f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/ShutdownEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class ShutdownEndpointTests { @Test void shutdown() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfig.class); + .withUserConfiguration(EndpointConfig.class); contextRunner.run((context) -> { EndpointConfig config = context.getBean(EndpointConfig.class); ClassLoader previousTccl = Thread.currentThread().getContextClassLoader(); @@ -69,7 +69,9 @@ class ShutdownEndpointTests { @Test void shutdownChild() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(EmptyConfig.class) - .child(EndpointConfig.class).web(WebApplicationType.NONE).run(); + .child(EndpointConfig.class) + .web(WebApplicationType.NONE) + .run(); CountDownLatch latch = context.getBean(EndpointConfig.class).latch; assertThat(context.getBean(ShutdownEndpoint.class).shutdown().getMessage()).startsWith("Shutting down"); assertThat(context.isActive()).isTrue(); @@ -79,7 +81,9 @@ class ShutdownEndpointTests { @Test void shutdownParent() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(EndpointConfig.class) - .child(EmptyConfig.class).web(WebApplicationType.NONE).run(); + .child(EmptyConfig.class) + .web(WebApplicationType.NONE) + .run(); CountDownLatch parentLatch = context.getBean(EndpointConfig.class).latch; CountDownLatch childLatch = context.getBean(EmptyConfig.class).latch; assertThat(context.getBean(ShutdownEndpoint.class).shutdown().getMessage()).startsWith("Shutting down"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java index c0c820d321..16d2026a7e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointFilteringTests.java @@ -44,22 +44,22 @@ class ConfigurationPropertiesReportEndpointFilteringTests { @Test void filterByPrefixSingleMatch() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); assertProperties(contextRunner, "solo1"); } @Test void filterByPrefixMultipleMatches() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint - .configurationPropertiesWithPrefix("foo."); + .configurationPropertiesWithPrefix("foo."); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationPropertiesDescriptor contextProperties = applicationProperties.getContexts() - .get(context.getId()); + .get(context.getId()); assertThat(contextProperties.getBeans()).containsOnlyKeys("primaryFoo", "secondaryFoo"); }); } @@ -67,15 +67,15 @@ class ConfigurationPropertiesReportEndpointFilteringTests { @Test void filterByPrefixNoMatches() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint - .configurationPropertiesWithPrefix("foo.third"); + .configurationPropertiesWithPrefix("foo.third"); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationPropertiesDescriptor contextProperties = applicationProperties.getContexts() - .get(context.getId()); + .get(context.getId()); assertThat(contextProperties.getBeans()).isEmpty(); }); } @@ -83,30 +83,33 @@ class ConfigurationPropertiesReportEndpointFilteringTests { @Test void noSanitizationWhenShowAlways() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(ConfigWithAlways.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withUserConfiguration(ConfigWithAlways.class) + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); assertProperties(contextRunner, "solo1"); } @Test void sanitizationWhenShowNever() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(ConfigWithNever.class) - .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); + .withUserConfiguration(ConfigWithNever.class) + .withPropertyValues("foo.primary.name:foo1", "foo.secondary.name:foo2", "only.bar.name:solo1"); assertProperties(contextRunner, "******"); } private void assertProperties(ApplicationContextRunner contextRunner, String value) { contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint - .configurationPropertiesWithPrefix("only.bar"); + .configurationPropertiesWithPrefix("only.bar"); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationPropertiesDescriptor contextProperties = applicationProperties.getContexts() - .get(context.getId()); - Optional key = contextProperties.getBeans().keySet().stream() - .filter((id) -> findIdFromPrefix("only.bar", id)).findAny(); + .get(context.getId()); + Optional key = contextProperties.getBeans() + .keySet() + .stream() + .filter((id) -> findIdFromPrefix("only.bar", id)) + .findAny(); ConfigurationPropertiesBeanDescriptor descriptor = contextProperties.getBeans().get(key.get()); assertThat(descriptor.getPrefix()).isEqualTo("only.bar"); assertThat(descriptor.getProperties()).containsEntry("name", value); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java index ea048c864d..1abf275822 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointMethodAnnotationsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,14 +43,14 @@ class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @Test void testNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(Config.class) - .withPropertyValues("other.name:foo", "first.name:bar"); + .withPropertyValues("other.name:foo", "first.name:bar"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationPropertiesDescriptor contextProperties = applicationProperties.getContexts() - .get(context.getId()); + .get(context.getId()); ConfigurationPropertiesBeanDescriptor other = contextProperties.getBeans().get("other"); assertThat(other).isNotNull(); assertThat(other.getPrefix()).isEqualTo("other"); @@ -62,14 +62,15 @@ class ConfigurationPropertiesReportEndpointMethodAnnotationsTests { @Test void prefixFromBeanMethodConfigurationPropertiesCanOverridePrefixOnClass() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(OverriddenPrefix.class).withPropertyValues("other.name:foo"); + .withUserConfiguration(OverriddenPrefix.class) + .withPropertyValues("other.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); assertThat(applicationProperties.getContexts()).containsOnlyKeys(context.getId()); ContextConfigurationPropertiesDescriptor contextProperties = applicationProperties.getContexts() - .get(context.getId()); + .get(context.getId()); ConfigurationPropertiesBeanDescriptor bar = contextProperties.getBeans().get("bar"); assertThat(bar).isNotNull(); assertThat(bar.getPrefix()).isEqualTo("other"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java index 10c0d8a84e..1c4ae533f9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointParentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,17 +42,18 @@ class ConfigurationPropertiesReportEndpointParentTests { @Test void configurationPropertiesClass() { new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { - new ApplicationContextRunner().withUserConfiguration(ClassConfigurationProperties.class).withParent(parent) - .run((child) -> { - ConfigurationPropertiesReportEndpoint endpoint = child - .getBean(ConfigurationPropertiesReportEndpoint.class); - ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - assertThat(applicationProperties.getContexts()).containsOnlyKeys(child.getId(), parent.getId()); - assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) - .containsExactly("someProperties"); - assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) - .containsExactly("testProperties"); - }); + new ApplicationContextRunner().withUserConfiguration(ClassConfigurationProperties.class) + .withParent(parent) + .run((child) -> { + ConfigurationPropertiesReportEndpoint endpoint = child + .getBean(ConfigurationPropertiesReportEndpoint.class); + ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts()).containsOnlyKeys(child.getId(), parent.getId()); + assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) + .containsExactly("someProperties"); + assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) + .containsExactly("testProperties"); + }); }); } @@ -60,15 +61,16 @@ class ConfigurationPropertiesReportEndpointParentTests { void configurationPropertiesBeanMethod() { new ApplicationContextRunner().withUserConfiguration(Parent.class).run((parent) -> { new ApplicationContextRunner().withUserConfiguration(BeanMethodConfigurationProperties.class) - .withParent(parent).run((child) -> { - ConfigurationPropertiesReportEndpoint endpoint = child - .getBean(ConfigurationPropertiesReportEndpoint.class); - ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) - .containsExactlyInAnyOrder("otherProperties"); - assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) - .containsExactly("testProperties"); - }); + .withParent(parent) + .run((child) -> { + ConfigurationPropertiesReportEndpoint endpoint = child + .getBean(ConfigurationPropertiesReportEndpoint.class); + ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); + assertThat(applicationProperties.getContexts().get(child.getId()).getBeans().keySet()) + .containsExactlyInAnyOrder("otherProperties"); + assertThat((applicationProperties.getContexts().get(parent.getId()).getBeans().keySet())) + .containsExactly("testProperties"); + }); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java index 90eb3def41..84c196eda7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java @@ -60,22 +60,36 @@ class ConfigurationPropertiesReportEndpointProxyTests { SqlExecutor.class); contextRunner.run((context) -> { ConfigurationPropertiesDescriptor applicationProperties = context - .getBean(ConfigurationPropertiesReportEndpoint.class).configurationProperties(); - assertThat(applicationProperties.getContexts().get(context.getId()).getBeans().values().stream() - .map(ConfigurationPropertiesBeanDescriptor::getPrefix).filter("executor.sql"::equals).findFirst()) - .isNotEmpty(); + .getBean(ConfigurationPropertiesReportEndpoint.class) + .configurationProperties(); + assertThat(applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .values() + .stream() + .map(ConfigurationPropertiesBeanDescriptor::getPrefix) + .filter("executor.sql"::equals) + .findFirst()).isNotEmpty(); }); } @Test void proxiedConstructorBoundPropertiesShouldBeAvailableInReport() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(ValidatedConfiguration.class).withPropertyValues("validated.name=baz"); + .withUserConfiguration(ValidatedConfiguration.class) + .withPropertyValues("validated.name=baz"); contextRunner.run((context) -> { ConfigurationPropertiesDescriptor applicationProperties = context - .getBean(ConfigurationPropertiesReportEndpoint.class).configurationProperties(); - Map properties = applicationProperties.getContexts().get(context.getId()).getBeans() - .values().stream().map(ConfigurationPropertiesBeanDescriptor::getProperties).findFirst().get(); + .getBean(ConfigurationPropertiesReportEndpoint.class) + .configurationProperties(); + Map properties = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .values() + .stream() + .map(ConfigurationPropertiesBeanDescriptor::getProperties) + .findFirst() + .get(); assertThat(properties).containsEntry("name", "baz"); }); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java index 7304d41ce9..3acea77a8b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java @@ -59,13 +59,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void testNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) - .withPropertyValues("foo.name:foo"); + .withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -79,13 +81,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testNestedNaming() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(FooConfig.class) - .withPropertyValues("foo.bar.name:foo"); + .withPropertyValues("foo.bar.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); Map map = foo.getProperties(); assertThat(map).isNotNull(); @@ -98,13 +102,16 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testSelfReferentialProperty() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(SelfReferentialConfig.class).withPropertyValues("foo.name:foo"); + .withUserConfiguration(SelfReferentialConfig.class) + .withPropertyValues("foo.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); assertThat(map).isNotNull(); @@ -119,13 +126,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void testCycle() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(CycleConfig.class); + .withUserConfiguration(CycleConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor cycle = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("cycle"); + ConfigurationPropertiesBeanDescriptor cycle = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("cycle"); assertThat(cycle.getPrefix()).isEqualTo("cycle"); Map map = cycle.getProperties(); assertThat(map).isNotNull(); @@ -138,13 +147,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testMap() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class) - .withPropertyValues("foo.map.name:foo"); + .withPropertyValues("foo.map.name:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); ConfigurationPropertiesBeanDescriptor fooProperties = applicationProperties.getContexts() - .get(context.getId()).getBeans().get("foo"); + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(fooProperties).isNotNull(); assertThat(fooProperties.getPrefix()).isEqualTo("foo"); Map map = fooProperties.getProperties(); @@ -159,10 +170,12 @@ class ConfigurationPropertiesReportEndpointSerializationTests { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(MapConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -176,13 +189,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testList() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(ListConfig.class) - .withPropertyValues("foo.list[0]:foo"); + .withPropertyValues("foo.list[0]:foo"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -195,13 +210,16 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void testInetAddress() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(AddressedConfig.class).withPropertyValues("foo.address:192.168.1.10"); + .withUserConfiguration(AddressedConfig.class) + .withPropertyValues("foo.address:192.168.1.10"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo).isNotNull(); assertThat(foo.getPrefix()).isEqualTo("foo"); Map map = foo.getProperties(); @@ -215,14 +233,16 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @SuppressWarnings("unchecked") void testInitializedMapAndList() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(InitializedMapAndListPropertiesConfig.class) - .withPropertyValues("foo.map.entryOne:true", "foo.list[0]:abc"); + .withUserConfiguration(InitializedMapAndListPropertiesConfig.class) + .withPropertyValues("foo.map.entryOne:true", "foo.list[0]:abc"); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor foo = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat(foo.getPrefix()).isEqualTo("foo"); Map propertiesMap = foo.getProperties(); assertThat(propertiesMap).containsOnlyKeys("bar", "name", "map", "list"); @@ -236,13 +256,15 @@ class ConfigurationPropertiesReportEndpointSerializationTests { @Test void hikariDataSourceConfigurationPropertiesBeanCanBeSerialized() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(HikariDataSourceConfig.class); + .withUserConfiguration(HikariDataSourceConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); ConfigurationPropertiesBeanDescriptor hikariDataSource = applicationProperties.getContexts() - .get(context.getId()).getBeans().get("hikariDataSource"); + .get(context.getId()) + .getBeans() + .get("hikariDataSource"); Map nestedProperties = hikariDataSource.getProperties(); assertThat(nestedProperties).doesNotContainKey("error"); }); @@ -253,15 +275,18 @@ class ConfigurationPropertiesReportEndpointSerializationTests { void endpointResponseUsesToStringOfCharSequenceAsPropertyValue() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withInitializer((context) -> { ConfigurableEnvironment environment = context.getEnvironment(); - environment.getPropertySources().addFirst(new MapPropertySource("test", - Collections.singletonMap("foo.name", new CharSequenceProperty("Spring Boot")))); + environment.getPropertySources() + .addFirst(new MapPropertySource("test", + Collections.singletonMap("foo.name", new CharSequenceProperty("Spring Boot")))); }).withUserConfiguration(FooConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat((Map) descriptor.getInputs().get("name")).containsEntry("value", "Spring Boot"); }); } @@ -271,15 +296,18 @@ class ConfigurationPropertiesReportEndpointSerializationTests { void endpointResponseUsesPlaceholderForComplexValueAsPropertyValue() { ApplicationContextRunner contextRunner = new ApplicationContextRunner().withInitializer((context) -> { ConfigurableEnvironment environment = context.getEnvironment(); - environment.getPropertySources().addFirst(new MapPropertySource("test", - Collections.singletonMap("foo.name", new ComplexProperty("Spring Boot")))); + environment.getPropertySources() + .addFirst(new MapPropertySource("test", + Collections.singletonMap("foo.name", new ComplexProperty("Spring Boot")))); }).withUserConfiguration(ComplexPropertyToStringConverter.class, FooConfig.class); contextRunner.run((context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesDescriptor applicationProperties = endpoint.configurationProperties(); - ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts().get(context.getId()) - .getBeans().get("foo"); + ConfigurationPropertiesBeanDescriptor descriptor = applicationProperties.getContexts() + .get(context.getId()) + .getBeans() + .get("foo"); assertThat((Map) descriptor.getInputs().get("name")).containsEntry("value", "Complex property value " + ComplexProperty.class.getName()); }); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java index cec8667876..c0e606a923 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointTests.java @@ -66,114 +66,122 @@ import static org.assertj.core.api.Assertions.entry; class ConfigurationPropertiesReportEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(EndpointConfig.class); + .withUserConfiguration(EndpointConfig.class); @Test void descriptorWithJavaBeanBindMethodDetectsRelevantProperties() { - this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class).run(assertProperties("test", - (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", "myTestProperty", "duration"))); + this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", + "myTestProperty", "duration"))); } @Test void descriptorWithAutowiredConstructorBindMethodDetectsRelevantProperties() { this.contextRunner.withUserConfiguration(AutowiredPropertiesConfiguration.class) - .run(assertProperties("autowired", (properties) -> assertThat(properties).containsOnlyKeys("counter"))); + .run(assertProperties("autowired", (properties) -> assertThat(properties).containsOnlyKeys("counter"))); } @Test void descriptorWithValueObjectBindMethodDetectsRelevantProperties() { - this.contextRunner.withUserConfiguration(ImmutablePropertiesConfiguration.class).run(assertProperties( - "immutable", - (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", "myTestProperty", "for"))); + this.contextRunner.withUserConfiguration(ImmutablePropertiesConfiguration.class) + .run(assertProperties("immutable", + (properties) -> assertThat(properties).containsOnlyKeys("dbPassword", "myTestProperty", "for"))); } @Test void descriptorWithValueObjectBindMethodUseDedicatedConstructor() { - this.contextRunner.withUserConfiguration(MultiConstructorPropertiesConfiguration.class).run(assertProperties( - "multiconstructor", (properties) -> assertThat(properties).containsOnly(entry("name", "test")))); + this.contextRunner.withUserConfiguration(MultiConstructorPropertiesConfiguration.class) + .run(assertProperties("multiconstructor", + (properties) -> assertThat(properties).containsOnly(entry("name", "test")))); } @Test void descriptorWithValueObjectBindMethodHandleNestedType() { this.contextRunner.withPropertyValues("immutablenested.nested.name=nested", "immutablenested.nested.counter=42") - .withUserConfiguration(ImmutableNestedPropertiesConfiguration.class) - .run(assertProperties("immutablenested", (properties) -> { - assertThat(properties).containsOnlyKeys("name", "nested"); - Map nested = (Map) properties.get("nested"); - assertThat(nested).containsOnly(entry("name", "nested"), entry("counter", 42)); - }, (inputs) -> { - Map nested = (Map) inputs.get("nested"); - Map name = (Map) nested.get("name"); - Map counter = (Map) nested.get("counter"); - assertThat(name).containsEntry("value", "nested"); - assertThat(name).containsEntry("origin", - "\"immutablenested.nested.name\" from property source \"test\""); - assertThat(counter).containsEntry("origin", - "\"immutablenested.nested.counter\" from property source \"test\""); - assertThat(counter).containsEntry("value", "42"); - })); + .withUserConfiguration(ImmutableNestedPropertiesConfiguration.class) + .run(assertProperties("immutablenested", (properties) -> { + assertThat(properties).containsOnlyKeys("name", "nested"); + Map nested = (Map) properties.get("nested"); + assertThat(nested).containsOnly(entry("name", "nested"), entry("counter", 42)); + }, (inputs) -> { + Map nested = (Map) inputs.get("nested"); + Map name = (Map) nested.get("name"); + Map counter = (Map) nested.get("counter"); + assertThat(name).containsEntry("value", "nested"); + assertThat(name).containsEntry("origin", + "\"immutablenested.nested.name\" from property source \"test\""); + assertThat(counter).containsEntry("origin", + "\"immutablenested.nested.counter\" from property source \"test\""); + assertThat(counter).containsEntry("value", "42"); + })); } @Test void descriptorWithSimpleList() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.simpleList=a,b").run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("simpleList")).isInstanceOf(List.class); - List list = (List) properties.get("simpleList"); - assertThat(list).hasSize(2); - assertThat(list.get(0)).isEqualTo("a"); - assertThat(list.get(1)).isEqualTo("b"); - }, (inputs) -> { - List list = (List) inputs.get("simpleList"); - assertThat(list).hasSize(2); - Map item = (Map) list.get(0); - String origin = item.get("origin"); - String value = item.get("value"); - assertThat(value).isEqualTo("a,b"); - assertThat(origin).isEqualTo("\"sensible.simpleList\" from property source \"test\""); - })); + .withPropertyValues("sensible.simpleList=a,b") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("simpleList")).isInstanceOf(List.class); + List list = (List) properties.get("simpleList"); + assertThat(list).hasSize(2); + assertThat(list.get(0)).isEqualTo("a"); + assertThat(list.get(1)).isEqualTo("b"); + }, (inputs) -> { + List list = (List) inputs.get("simpleList"); + assertThat(list).hasSize(2); + Map item = (Map) list.get(0); + String origin = item.get("origin"); + String value = item.get("value"); + assertThat(value).isEqualTo("a,b"); + assertThat(origin).isEqualTo("\"sensible.simpleList\" from property source \"test\""); + })); } @Test void descriptorDoesNotIncludePropertyWithNullValue() { this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) - .run(assertProperties("test", (properties) -> assertThat(properties).doesNotContainKey("nullValue"))); + .run(assertProperties("test", (properties) -> assertThat(properties).doesNotContainKey("nullValue"))); } @Test void descriptorWithDurationProperty() { - this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class).run(assertProperties("test", - (properties) -> assertThat(properties.get("duration")).isEqualTo(Duration.ofSeconds(10).toString()))); + this.contextRunner.withUserConfiguration(TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> assertThat(properties.get("duration")) + .isEqualTo(Duration.ofSeconds(10).toString()))); } @Test void descriptorWithNonCamelCaseProperty() { - this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class).run(assertProperties( - "mixedcase", (properties) -> assertThat(properties.get("myURL")).isEqualTo("https://example.com"))); + this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class) + .run(assertProperties("mixedcase", + (properties) -> assertThat(properties.get("myURL")).isEqualTo("https://example.com"))); } @Test void descriptorWithMixedCaseProperty() { - this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class).run(assertProperties( - "mixedcase", (properties) -> assertThat(properties.get("mIxedCase")).isEqualTo("mixed"))); + this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class) + .run(assertProperties("mixedcase", + (properties) -> assertThat(properties.get("mIxedCase")).isEqualTo("mixed"))); } @Test void descriptorWithSingleLetterProperty() { this.contextRunner.withUserConfiguration(MixedCasePropertiesConfiguration.class) - .run(assertProperties("mixedcase", (properties) -> assertThat(properties.get("z")).isEqualTo("zzz"))); + .run(assertProperties("mixedcase", (properties) -> assertThat(properties.get("z")).isEqualTo("zzz"))); } @Test void descriptorWithSimpleBooleanProperty() { - this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class).run(assertProperties("boolean", - (properties) -> assertThat(properties.get("simpleBoolean")).isEqualTo(true))); + this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class) + .run(assertProperties("boolean", + (properties) -> assertThat(properties.get("simpleBoolean")).isEqualTo(true))); } @Test void descriptorWithMixedBooleanProperty() { - this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class).run(assertProperties("boolean", - (properties) -> assertThat(properties.get("mixedBoolean")).isEqualTo(true))); + this.contextRunner.withUserConfiguration(BooleanPropertiesConfiguration.class) + .run(assertProperties("boolean", + (properties) -> assertThat(properties.get("mixedBoolean")).isEqualTo(true))); } @Test @@ -181,136 +189,140 @@ class ConfigurationPropertiesReportEndpointTests { String configSize = "1MB"; String stringifySize = DataSize.parse(configSize).toString(); this.contextRunner.withUserConfiguration(DataSizePropertiesConfiguration.class) - .withPropertyValues(String.format("data.size=%s", configSize)).run(assertProperties("data", - (properties) -> assertThat(properties.get("size")).isEqualTo(stringifySize), (inputs) -> { - Map size = (Map) inputs.get("size"); - assertThat(size).containsEntry("value", configSize); - assertThat(size).containsEntry("origin", "\"data.size\" from property source \"test\""); - })); + .withPropertyValues(String.format("data.size=%s", configSize)) + .run(assertProperties("data", (properties) -> assertThat(properties.get("size")).isEqualTo(stringifySize), + (inputs) -> { + Map size = (Map) inputs.get("size"); + assertThat(size).containsEntry("value", configSize); + assertThat(size).containsEntry("origin", "\"data.size\" from property source \"test\""); + })); } @Test void sanitizeLists() { new ApplicationContextRunner() - .withUserConfiguration(EndpointConfigWithShowNever.class, SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.listItems[0].some-password=password") - .run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("listItems")).isInstanceOf(List.class); - List list = (List) properties.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - assertThat(item).containsEntry("somePassword", "******"); - }, (inputs) -> { - List list = (List) inputs.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - Map somePassword = (Map) item.get("somePassword"); - assertThat(somePassword).containsEntry("value", "******"); - assertThat(somePassword).containsEntry("origin", - "\"sensible.listItems[0].some-password\" from property source \"test\""); - })); + .withUserConfiguration(EndpointConfigWithShowNever.class, SensiblePropertiesConfiguration.class) + .withPropertyValues("sensible.listItems[0].some-password=password") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("listItems")).isInstanceOf(List.class); + List list = (List) properties.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + assertThat(item).containsEntry("somePassword", "******"); + }, (inputs) -> { + List list = (List) inputs.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + Map somePassword = (Map) item.get("somePassword"); + assertThat(somePassword).containsEntry("value", "******"); + assertThat(somePassword).containsEntry("origin", + "\"sensible.listItems[0].some-password\" from property source \"test\""); + })); } @Test void listsOfListsAreSanitized() { new ApplicationContextRunner() - .withUserConfiguration(EndpointConfigWithShowNever.class, SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.listOfListItems[0][0].some-password=password") - .run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("listOfListItems")).isInstanceOf(List.class); - List> listOfLists = (List>) properties.get("listOfListItems"); - assertThat(listOfLists).hasSize(1); - List list = listOfLists.get(0); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - assertThat(item).containsEntry("somePassword", "******"); - }, (inputs) -> { - assertThat(inputs.get("listOfListItems")).isInstanceOf(List.class); - List> listOfLists = (List>) inputs.get("listOfListItems"); - assertThat(listOfLists).hasSize(1); - List list = listOfLists.get(0); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - Map somePassword = (Map) item.get("somePassword"); - assertThat(somePassword).containsEntry("value", "******"); - assertThat(somePassword).containsEntry("origin", - "\"sensible.listOfListItems[0][0].some-password\" from property source \"test\""); - })); + .withUserConfiguration(EndpointConfigWithShowNever.class, SensiblePropertiesConfiguration.class) + .withPropertyValues("sensible.listOfListItems[0][0].some-password=password") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("listOfListItems")).isInstanceOf(List.class); + List> listOfLists = (List>) properties.get("listOfListItems"); + assertThat(listOfLists).hasSize(1); + List list = listOfLists.get(0); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + assertThat(item).containsEntry("somePassword", "******"); + }, (inputs) -> { + assertThat(inputs.get("listOfListItems")).isInstanceOf(List.class); + List> listOfLists = (List>) inputs.get("listOfListItems"); + assertThat(listOfLists).hasSize(1); + List list = listOfLists.get(0); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + Map somePassword = (Map) item.get("somePassword"); + assertThat(somePassword).containsEntry("value", "******"); + assertThat(somePassword).containsEntry("origin", + "\"sensible.listOfListItems[0][0].some-password\" from property source \"test\""); + })); } @Test void sanitizeWithCustomSanitizingFunction() { - new ApplicationContextRunner().withUserConfiguration(CustomSanitizingEndpointConfig.class, - SanitizingFunctionConfiguration.class, TestPropertiesConfiguration.class) - .run(assertProperties("test", (properties) -> { - assertThat(properties).containsEntry("dbPassword", "$$$"); - assertThat(properties).containsEntry("myTestProperty", "$$$"); - })); + new ApplicationContextRunner() + .withUserConfiguration(CustomSanitizingEndpointConfig.class, SanitizingFunctionConfiguration.class, + TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> { + assertThat(properties).containsEntry("dbPassword", "$$$"); + assertThat(properties).containsEntry("myTestProperty", "$$$"); + })); } @Test void sanitizeWithCustomPropertySourceBasedSanitizingFunction() { new ApplicationContextRunner() - .withUserConfiguration(CustomSanitizingEndpointConfig.class, - PropertySourceBasedSanitizingFunctionConfiguration.class, TestPropertiesConfiguration.class) - .withPropertyValues("test.my-test-property=abcde").run(assertProperties("test", (properties) -> { - assertThat(properties).containsEntry("dbPassword", "123456"); - assertThat(properties).containsEntry("myTestProperty", "$$$"); - })); + .withUserConfiguration(CustomSanitizingEndpointConfig.class, + PropertySourceBasedSanitizingFunctionConfiguration.class, TestPropertiesConfiguration.class) + .withPropertyValues("test.my-test-property=abcde") + .run(assertProperties("test", (properties) -> { + assertThat(properties).containsEntry("dbPassword", "123456"); + assertThat(properties).containsEntry("myTestProperty", "$$$"); + })); } @Test void sanitizeListsWithCustomSanitizingFunction() { new ApplicationContextRunner() - .withUserConfiguration(CustomSanitizingEndpointConfig.class, SanitizingFunctionConfiguration.class, - SensiblePropertiesConfiguration.class) - .withPropertyValues("sensible.listItems[0].custom=my-value") - .run(assertProperties("sensible", (properties) -> { - assertThat(properties.get("listItems")).isInstanceOf(List.class); - List list = (List) properties.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - assertThat(item).containsEntry("custom", "$$$"); - }, (inputs) -> { - List list = (List) inputs.get("listItems"); - assertThat(list).hasSize(1); - Map item = (Map) list.get(0); - Map somePassword = (Map) item.get("custom"); - assertThat(somePassword).containsEntry("value", "$$$"); - assertThat(somePassword).containsEntry("origin", - "\"sensible.listItems[0].custom\" from property source \"test\""); - })); + .withUserConfiguration(CustomSanitizingEndpointConfig.class, SanitizingFunctionConfiguration.class, + SensiblePropertiesConfiguration.class) + .withPropertyValues("sensible.listItems[0].custom=my-value") + .run(assertProperties("sensible", (properties) -> { + assertThat(properties.get("listItems")).isInstanceOf(List.class); + List list = (List) properties.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + assertThat(item).containsEntry("custom", "$$$"); + }, (inputs) -> { + List list = (List) inputs.get("listItems"); + assertThat(list).hasSize(1); + Map item = (Map) list.get(0); + Map somePassword = (Map) item.get("custom"); + assertThat(somePassword).containsEntry("value", "$$$"); + assertThat(somePassword).containsEntry("origin", + "\"sensible.listItems[0].custom\" from property source \"test\""); + })); } @Test void noSanitizationWhenShowAlways() { new ApplicationContextRunner() - .withUserConfiguration(EndpointConfigWithShowAlways.class, TestPropertiesConfiguration.class) - .run(assertProperties("test", (properties) -> { - assertThat(properties).containsEntry("dbPassword", "123456"); - assertThat(properties).containsEntry("myTestProperty", "654321"); - })); + .withUserConfiguration(EndpointConfigWithShowAlways.class, TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> { + assertThat(properties).containsEntry("dbPassword", "123456"); + assertThat(properties).containsEntry("myTestProperty", "654321"); + })); } @Test void sanitizationWhenShowNever() { new ApplicationContextRunner() - .withUserConfiguration(EndpointConfigWithShowNever.class, TestPropertiesConfiguration.class) - .run(assertProperties("test", (properties) -> { - assertThat(properties).containsEntry("dbPassword", "******"); - assertThat(properties).containsEntry("myTestProperty", "******"); - })); + .withUserConfiguration(EndpointConfigWithShowNever.class, TestPropertiesConfiguration.class) + .run(assertProperties("test", (properties) -> { + assertThat(properties).containsEntry("dbPassword", "******"); + assertThat(properties).containsEntry("myTestProperty", "******"); + })); } @Test void originParents() { this.contextRunner.withUserConfiguration(SensiblePropertiesConfiguration.class) - .withInitializer(this::initializeOriginParents).run(assertProperties("sensible", (properties) -> { - }, (inputs) -> { - Map stringInputs = (Map) inputs.get("string"); - String[] originParents = (String[]) stringInputs.get("originParents"); - assertThat(originParents).containsExactly("spring", "boot"); - })); + .withInitializer(this::initializeOriginParents) + .run(assertProperties("sensible", (properties) -> { + }, (inputs) -> { + Map stringInputs = (Map) inputs.get("string"); + String[] originParents = (String[]) stringInputs.get("originParents"); + assertThat(originParents).containsExactly("spring", "boot"); + })); } private void initializeOriginParents(ConfigurableApplicationContext context) { @@ -329,13 +341,16 @@ class ConfigurationPropertiesReportEndpointTests { Consumer> properties, Consumer> inputs) { return (context) -> { ConfigurationPropertiesReportEndpoint endpoint = context - .getBean(ConfigurationPropertiesReportEndpoint.class); + .getBean(ConfigurationPropertiesReportEndpoint.class); ConfigurationPropertiesReportEndpoint.ConfigurationPropertiesDescriptor configurationProperties = endpoint - .configurationProperties(); + .configurationProperties(); ContextConfigurationPropertiesDescriptor allProperties = configurationProperties.getContexts() - .get(context.getId()); - Optional key = allProperties.getBeans().keySet().stream() - .filter((id) -> findIdFromPrefix(prefix, id)).findAny(); + .get(context.getId()); + Optional key = allProperties.getBeans() + .keySet() + .stream() + .filter((id) -> findIdFromPrefix(prefix, id)) + .findAny(); assertThat(key).describedAs("No configuration properties with prefix '%s' found", prefix).isPresent(); ConfigurationPropertiesBeanDescriptor descriptor = allProperties.getBeans().get(key.get()); assertThat(descriptor.getPrefix()).isEqualTo(prefix); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtensionTests.java index 30e299a27e..31cb84310c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -88,7 +88,7 @@ class ConfigurationPropertiesReportEndpointWebExtensionTests { private void verifyPrefixed(SecurityContext securityContext, boolean showUnsanitized) { given(this.delegate.getConfigurationProperties("test", showUnsanitized)) - .willReturn(new ConfigurationPropertiesDescriptor(Collections.emptyMap())); + .willReturn(new ConfigurationPropertiesDescriptor(Collections.emptyMap())); this.webExtension.configurationPropertiesWithPrefix(securityContext, "test"); then(this.delegate).should().getConfigurationProperties("test", showUnsanitized); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java index 0fe5bc9fb8..504a049683 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,22 +51,48 @@ class ConfigurationPropertiesReportEndpointWebIntegrationTests { @WebEndpointTest void noFilters() { - this.client.get().uri("/actuator/configprops").exchange().expectStatus().isOk().expectBody() - .jsonPath("$..beans[*]").value(hasSize(greaterThanOrEqualTo(2))).jsonPath("$..beans['fooDotCom']") - .exists().jsonPath("$..beans['barDotCom']").exists(); + this.client.get() + .uri("/actuator/configprops") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$..beans[*]") + .value(hasSize(greaterThanOrEqualTo(2))) + .jsonPath("$..beans['fooDotCom']") + .exists() + .jsonPath("$..beans['barDotCom']") + .exists(); } @WebEndpointTest void filterByExactPrefix() { - this.client.get().uri("/actuator/configprops/com.foo").exchange().expectStatus().isOk().expectBody() - .jsonPath("$..beans[*]").value(hasSize(1)).jsonPath("$..beans['fooDotCom']").exists(); + this.client.get() + .uri("/actuator/configprops/com.foo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$..beans[*]") + .value(hasSize(1)) + .jsonPath("$..beans['fooDotCom']") + .exists(); } @WebEndpointTest void filterByGeneralPrefix() { - this.client.get().uri("/actuator/configprops/com.").exchange().expectStatus().isOk().expectBody() - .jsonPath("$..beans[*]").value(hasSize(2)).jsonPath("$..beans['fooDotCom']").exists() - .jsonPath("$..beans['barDotCom']").exists(); + this.client.get() + .uri("/actuator/configprops/com.") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$..beans[*]") + .value(hasSize(2)) + .jsonPath("$..beans['fooDotCom']") + .exists() + .jsonPath("$..beans['barDotCom']") + .exists(); } @WebEndpointTest diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java index fa614ead00..28d3583bfd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/elasticsearch/ElasticsearchReactiveHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -121,8 +121,8 @@ class ElasticsearchReactiveHealthIndicatorTests { private void setupMockResponse(int responseCode, String status) { MockResponse mockResponse = new MockResponse().setBody(createJsonResult(status)) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .setHeader("X-Elastic-Product", "Elasticsearch"); + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .setHeader("X-Elastic-Product", "Elasticsearch"); this.server.enqueue(mockResponse); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java index 190e17d510..bc57d0a1d0 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/EndpointIdTests.java @@ -37,7 +37,7 @@ class EndpointIdTests { @Test void ofWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -48,31 +48,31 @@ class EndpointIdTests { @Test void ofWhenContainsSlashThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo/bar")) - .withMessage("Value must only contain valid chars"); + .withMessage("Value must only contain valid chars"); } @Test void ofWhenContainsBackslashThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo\\bar")) - .withMessage("Value must only contain valid chars"); + .withMessage("Value must only contain valid chars"); } @Test void ofWhenHasBadCharThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("foo!bar")) - .withMessage("Value must only contain valid chars"); + .withMessage("Value must only contain valid chars"); } @Test void ofWhenStartsWithNumberThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("1foo")) - .withMessage("Value must not start with a number"); + .withMessage("Value must not start with a number"); } @Test void ofWhenStartsWithUppercaseLetterThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> EndpointId.of("Foo")) - .withMessage("Value must not start with an uppercase letter"); + .withMessage("Value must not start with an uppercase letter"); } @Test @@ -96,7 +96,7 @@ class EndpointIdTests { EndpointId.resetLoggedWarnings(); EndpointId.of("foo-bar"); assertThat(output) - .contains("Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format"); + .contains("Endpoint ID 'foo-bar' contains invalid characters, please migrate to a valid format"); } @Test @@ -136,8 +136,12 @@ class EndpointIdTests { EndpointId five = EndpointId.of("barfoo1"); EndpointId six = EndpointId.of("foobar2"); assertThat(one).hasSameHashCodeAs(two); - assertThat(one).isEqualTo(one).isEqualTo(two).isEqualTo(three).isEqualTo(four).isNotEqualTo(five) - .isNotEqualTo(six); + assertThat(one).isEqualTo(one) + .isEqualTo(two) + .isEqualTo(three) + .isEqualTo(four) + .isNotEqualTo(five) + .isNotEqualTo(six); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java index e4465feb48..84f2a83279 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/InvocationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,13 +45,13 @@ class InvocationContextTests { @Test void createWhenSecurityContextIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new InvocationContext(null, this.arguments)) - .withMessage("SecurityContext must not be null"); + .withMessage("SecurityContext must not be null"); } @Test void createWhenArgumentsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new InvocationContext(this.securityContext, null)) - .withMessage("Arguments must not be null"); + .withMessage("Arguments must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java index 6d40f00923..4a40d15bed 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ProducibleOperationArgumentResolverTests.java @@ -67,9 +67,9 @@ class ProducibleOperationArgumentResolverTests { @Test void whenSingleValueIsAcceptableThenMatchingEnumValueIsReturned() { assertThat(new ProducibleOperationArgumentResolver(acceptHeader(V2_JSON)).resolve(ApiVersion.class)) - .isEqualTo(ApiVersion.V2); + .isEqualTo(ApiVersion.V2); assertThat(new ProducibleOperationArgumentResolver(acceptHeader(V3_JSON)).resolve(ApiVersion.class)) - .isEqualTo(ApiVersion.V3); + .isEqualTo(ApiVersion.V3); } @Test @@ -90,7 +90,7 @@ class ProducibleOperationArgumentResolverTests { @Test void whenMultipleDefaultsThrowsException() { assertThatIllegalStateException().isThrownBy(() -> resolve(acceptHeader("one/one"), WithMultipleDefaults.class)) - .withMessageContaining("Multiple default values"); + .withMessageContaining("Multiple default values"); } private Supplier> acceptHeader(String... types) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShowTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShowTests.java index 9fcb761da4..97a688bdec 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShowTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/ShowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -91,7 +91,7 @@ class ShowTests { Authentication authentication = mock(Authentication.class); given(securityContext.getPrincipal()).willReturn(authentication); given(authentication.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("other"))); assertThat(Show.WHEN_AUTHORIZED.isShown(securityContext, Collections.singleton("admin"))).isFalse(); } @@ -101,7 +101,7 @@ class ShowTests { Authentication authentication = mock(Authentication.class); given(securityContext.getPrincipal()).willReturn(authentication); given(authentication.getAuthorities()) - .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); + .willAnswer((invocation) -> Collections.singleton(new SimpleGrantedAuthority("admin"))); assertThat(Show.WHEN_AUTHORIZED.isShown(securityContext, Collections.singleton("admin"))).isTrue(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java index ca17253b3a..3227e787f4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,8 @@ class DiscoveredOperationMethodTests { void createWhenAnnotationAttributesIsNullShouldThrowException() { Method method = ReflectionUtils.findMethod(getClass(), "example"); assertThatIllegalArgumentException() - .isThrownBy(() -> new DiscoveredOperationMethod(method, OperationType.READ, null)) - .withMessageContaining("AnnotationAttributes must not be null"); + .isThrownBy(() -> new DiscoveredOperationMethod(method, OperationType.READ, null)) + .withMessageContaining("AnnotationAttributes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java index 1f08a91468..c619700eab 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class DiscovererEndpointFilterTests { @Test void createWhenDiscovererIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestDiscovererEndpointFilter(null)) - .withMessageContaining("Discoverer must not be null"); + .withMessageContaining("Discoverer must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java index 0cb7ed8cab..96b68a2a56 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java @@ -71,33 +71,33 @@ class EndpointDiscovererTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), - Collections.emptyList(), Collections.emptyList())) - .withMessageContaining("ApplicationContext must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), + Collections.emptyList(), Collections.emptyList())) + .withMessageContaining("ApplicationContext must not be null"); } @Test void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), null, - Collections.emptyList(), Collections.emptyList())) - .withMessageContaining("ParameterValueMapper must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), null, Collections.emptyList(), + Collections.emptyList())) + .withMessageContaining("ParameterValueMapper must not be null"); } @Test void createWhenInvokerAdvisorsIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), null, Collections.emptyList())) - .withMessageContaining("InvokerAdvisors must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + mock(ParameterValueMapper.class), null, Collections.emptyList())) + .withMessageContaining("InvokerAdvisors must not be null"); } @Test void createWhenFiltersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), Collections.emptyList(), null)) - .withMessageContaining("Filters must not be null"); + .isThrownBy(() -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + mock(ParameterValueMapper.class), Collections.emptyList(), null)) + .withMessageContaining("Filters must not be null"); } @Test @@ -139,8 +139,8 @@ class EndpointDiscovererTests { void getEndpointsWhenTwoEndpointsHaveTheSameIdShouldThrowException() { load(ClashingEndpointConfiguration.class, (context) -> assertThatIllegalStateException() - .isThrownBy(new TestEndpointDiscoverer(context)::getEndpoints) - .withMessageContaining("Found two endpoints with the id 'test': ")); + .isThrownBy(new TestEndpointDiscoverer(context)::getEndpoints) + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test @@ -159,8 +159,9 @@ class EndpointDiscovererTests { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); - operations.values().forEach( - (operation) -> assertThat(operation.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class)); + operations.values() + .forEach((operation) -> assertThat(operation.getInvoker()) + .isNotInstanceOf(CachingOperationInvoker.class)); }); } @@ -172,8 +173,9 @@ class EndpointDiscovererTests { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("test")); Map operations = mapOperations(endpoints.get(EndpointId.of("test"))); - operations.values().forEach( - (operation) -> assertThat(operation.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class)); + operations.values() + .forEach((operation) -> assertThat(operation.getInvoker()) + .isNotInstanceOf(CachingOperationInvoker.class)); }); } @@ -188,7 +190,7 @@ class EndpointDiscovererTests { TestOperation getAll = operations.get(findTestEndpointMethod("getAll")); TestOperation getOne = operations.get(findTestEndpointMethod("getOne", String.class)); TestOperation update = operations - .get(ReflectionUtils.findMethod(TestEndpoint.class, "update", String.class, String.class)); + .get(ReflectionUtils.findMethod(TestEndpoint.class, "update", String.class, String.class)); assertThat(((CachingOperationInvoker) getAll.getInvoker()).getTimeToLive()).isEqualTo(500); assertThat(getOne.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class); assertThat(update.getInvoker()).isNotInstanceOf(CachingOperationInvoker.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/OperationReflectiveProcessorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/OperationReflectiveProcessorTests.java index 8d0618f30b..be10d5f3b3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/OperationReflectiveProcessorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/OperationReflectiveProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -80,12 +80,14 @@ class OperationReflectiveProcessorTests { } private void assertHintsForDto() { - assertThat(RuntimeHintsPredicates.reflection().onType(Dto.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(this.runtimeHints); - assertThat(RuntimeHintsPredicates.reflection().onType(NestedDto.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(this.runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(Dto.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(this.runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(NestedDto.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(this.runtimeHints); } private void runProcessor(Method method) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java index 31c07a45cd..3ba4df37a9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java @@ -58,12 +58,12 @@ class ConversionServiceParameterValueMapperTests { given(conversionService.convert(any(), any())).willThrow(error); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); assertThatExceptionOfType(ParameterMappingException.class) - .isThrownBy(() -> mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123")) - .satisfies((ex) -> { - assertThat(ex.getValue()).isEqualTo("123"); - assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); - assertThat(ex.getCause()).isEqualTo(error); - }); + .isThrownBy(() -> mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123")) + .satisfies((ex) -> { + assertThat(ex.getValue()).isEqualTo("123"); + assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); + assertThat(ex.getCause()).isEqualTo(error); + }); } @Test @@ -79,7 +79,7 @@ class ConversionServiceParameterValueMapperTests { ConversionService conversionService = new DefaultConversionService(); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper(conversionService); assertThatExceptionOfType(ParameterMappingException.class).isThrownBy(() -> mapper - .mapParameterValue(new TestOperationParameter(OffsetDateTime.class), "2011-12-03T10:15:30+01:00")); + .mapParameterValue(new TestOperationParameter(OffsetDateTime.class), "2011-12-03T10:15:30+01:00")); } static class TestOperationParameter implements OperationParameter { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java index 2348e121e9..7f7a1f12bb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java @@ -50,22 +50,21 @@ class OperationMethodParametersTests { @Test void createWhenMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new OperationMethodParameters(null, mock(ParameterNameDiscoverer.class))) - .withMessageContaining("Method must not be null"); + .isThrownBy(() -> new OperationMethodParameters(null, mock(ParameterNameDiscoverer.class))) + .withMessageContaining("Method must not be null"); } @Test void createWhenParameterNameDiscovererIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, null)) - .withMessageContaining("ParameterNameDiscoverer must not be null"); + .withMessageContaining("ParameterNameDiscoverer must not be null"); } @Test void createWhenParameterNameDiscovererReturnsNullShouldThrowException() { assertThatIllegalStateException() - .isThrownBy( - () -> new OperationMethodParameters(this.exampleMethod, mock(ParameterNameDiscoverer.class))) - .withMessageContaining("Failed to extract parameter names"); + .isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, mock(ParameterNameDiscoverer.class))) + .withMessageContaining("Failed to extract parameter names"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java index 1613548c77..46dea6abe3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java @@ -39,13 +39,13 @@ class OperationMethodTests { @Test void createWhenMethodIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(null, OperationType.READ)) - .withMessageContaining("Method must not be null"); + .withMessageContaining("Method must not be null"); } @Test void createWhenOperationTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new OperationMethod(this.exampleMethod, null)) - .withMessageContaining("OperationType must not be null"); + .withMessageContaining("OperationType must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java index 25aa5869ad..9e7cab081a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -59,22 +59,22 @@ class ReflectiveOperationInvokerTests { @Test void createWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(null, this.operationMethod, this.parameterValueMapper)) - .withMessageContaining("Target must not be null"); + .isThrownBy(() -> new ReflectiveOperationInvoker(null, this.operationMethod, this.parameterValueMapper)) + .withMessageContaining("Target must not be null"); } @Test void createWhenOperationMethodIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, this.parameterValueMapper)) - .withMessageContaining("OperationMethod must not be null"); + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, this.parameterValueMapper)) + .withMessageContaining("OperationMethod must not be null"); } @Test void createWhenParameterValueMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, this.operationMethod, null)) - .withMessageContaining("ParameterValueMapper must not be null"); + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, this.operationMethod, null)) + .withMessageContaining("ParameterValueMapper must not be null"); } @Test @@ -82,7 +82,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); Object result = invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", "boot"))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", "boot"))); assertThat(result).isEqualTo("toob"); } @@ -91,7 +91,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); assertThatExceptionOfType(MissingParametersException.class).isThrownBy(() -> invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null)))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null)))); } @Test @@ -101,7 +101,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, operationMethod, this.parameterValueMapper); Object result = invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", null))); assertThat(result).isEqualTo("llun"); } @@ -110,7 +110,7 @@ class ReflectiveOperationInvokerTests { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); Object result = invoker - .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", 1234))); + .invoke(new InvocationContext(mock(SecurityContext.class), Collections.singletonMap("name", 1234))); assertThat(result).isEqualTo("4321"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java index 27e242874d..19efb8f682 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,8 @@ class CachingOperationInvokerTests { @Test void createInstanceWithTtlSetToZero() { assertThatIllegalArgumentException() - .isThrownBy(() -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) - .withMessageContaining("TimeToLive"); + .isThrownBy(() -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) + .withMessageContaining("TimeToLive"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java index 771cadfee9..5fa8a81dd3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -61,15 +61,15 @@ class EndpointMBeanTests { @Test void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) - .withMessageContaining("ResponseMapper must not be null"); + .isThrownBy(() -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) + .withMessageContaining("ResponseMapper must not be null"); } @Test void createWhenEndpointIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null)) - .withMessageContaining("Endpoint must not be null"); + .isThrownBy(() -> new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null)) + .withMessageContaining("Endpoint must not be null"); } @Test @@ -93,8 +93,9 @@ class EndpointMBeanTests { })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(MBeanException.class) - .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(IllegalStateException.class).withMessageContaining("test failure"); + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("test failure"); } @@ -105,17 +106,18 @@ class EndpointMBeanTests { })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(MBeanException.class) - .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(UnsupportedOperationException.class).withMessageContaining("test failure"); + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(UnsupportedOperationException.class) + .withMessageContaining("test failure"); } @Test void invokeWhenActionNameIsNotAnOperationShouldThrowException() { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(ReflectionException.class) - .isThrownBy(() -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) - .withCauseInstanceOf(IllegalArgumentException.class) - .withMessageContaining("no operation named missingOperation"); + .isThrownBy(() -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("no operation named missingOperation"); } @Test @@ -143,8 +145,9 @@ class EndpointMBeanTests { TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(operation); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); assertThatExceptionOfType(ReflectionException.class) - .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) - .withRootCauseInstanceOf(IllegalArgumentException.class).withMessageContaining("test failure"); + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withRootCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("test failure"); } @Test @@ -178,15 +181,15 @@ class EndpointMBeanTests { void getAttributeShouldThrowException() { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(AttributeNotFoundException.class).isThrownBy(() -> bean.getAttribute("test")) - .withMessageContaining("EndpointMBeans do not support attributes"); + .withMessageContaining("EndpointMBeans do not support attributes"); } @Test void setAttributeShouldThrowException() { EndpointMBean bean = createEndpointMBean(); assertThatExceptionOfType(AttributeNotFoundException.class) - .isThrownBy(() -> bean.setAttribute(new Attribute("test", "test"))) - .withMessageContaining("EndpointMBeans do not support attributes"); + .isThrownBy(() -> bean.setAttribute(new Attribute("test", "test"))) + .withMessageContaining("EndpointMBeans do not support attributes"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java index e75b5e1f3d..add013e236 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -81,31 +81,32 @@ class JmxEndpointExporterTests { @Test void createWhenMBeanServerIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints)) - .withMessageContaining("MBeanServer must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints)) + .withMessageContaining("MBeanServer must not be null"); } @Test void createWhenObjectNameFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints)) - .withMessageContaining("ObjectNameFactory must not be null"); + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints)) + .withMessageContaining("ObjectNameFactory must not be null"); } @Test void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints)) - .withMessageContaining("ResponseMapper must not be null"); + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints)) + .withMessageContaining("ResponseMapper must not be null"); } @Test void createWhenEndpointsIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null)) - .withMessageContaining("Endpoints must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null)) + .withMessageContaining("Endpoints must not be null"); } @Test @@ -127,19 +128,19 @@ class JmxEndpointExporterTests { @Test void registerWhenObjectNameIsMalformedShouldThrowException() throws Exception { given(this.objectNameFactory.getObjectName(any(ExposableJmxEndpoint.class))) - .willThrow(MalformedObjectNameException.class); + .willThrow(MalformedObjectNameException.class); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); assertThatIllegalStateException().isThrownBy(this.exporter::afterPropertiesSet) - .withMessageContaining("Invalid ObjectName for endpoint 'test'"); + .withMessageContaining("Invalid ObjectName for endpoint 'test'"); } @Test void registerWhenRegistrationFailsShouldThrowException() throws Exception { given(this.mBeanServer.registerMBean(any(), any(ObjectName.class))) - .willThrow(new MBeanRegistrationException(new RuntimeException())); + .willThrow(new MBeanRegistrationException(new RuntimeException())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); assertThatExceptionOfType(MBeanExportException.class).isThrownBy(this.exporter::afterPropertiesSet) - .withMessageContaining("Failed to register MBean for endpoint 'test"); + .withMessageContaining("Failed to register MBean for endpoint 'test"); } @Test @@ -164,9 +165,9 @@ class JmxEndpointExporterTests { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); willThrow(new MBeanRegistrationException(new RuntimeException())).given(this.mBeanServer) - .unregisterMBean(any(ObjectName.class)); + .unregisterMBean(any(ObjectName.class)); assertThatExceptionOfType(JmxException.class).isThrownBy(() -> this.exporter.destroy()) - .withMessageContaining("Failed to unregister MBean with ObjectName 'boot"); + .withMessageContaining("Failed to unregister MBean with ObjectName 'boot"); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java index e8342ec763..0d71eb2c33 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/MBeanInfoFactoryTests.java @@ -61,21 +61,21 @@ class MBeanInfoFactoryTests { @Test void getMBeanInfoWhenReadOperationShouldHaveInfoImpact() { MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.READ))); + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.READ))); assertThat(info.getOperations()[0].getImpact()).isZero(); } @Test void getMBeanInfoWhenWriteOperationShouldHaveActionImpact() { MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.WRITE))); + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.WRITE))); assertThat(info.getOperations()[0].getImpact()).isOne(); } @Test void getMBeanInfoWhenDeleteOperationShouldHaveActionImpact() { MBeanInfo info = this.factory - .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.DELETE))); + .getMBeanInfo(new TestExposableJmxEndpoint(new TestJmxOperation(OperationType.DELETE))); assertThat(info.getOperations()[0].getImpact()).isOne(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java index cc004288aa..fc4465f398 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -110,8 +110,9 @@ class JmxEndpointDiscovererTests { @Test void getEndpointsWhenJmxExtensionIsMissingEndpointShouldThrowException() { load(TestJmxEndpointExtension.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); } @Test @@ -174,44 +175,49 @@ class JmxEndpointDiscovererTests { @Test void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { load(ClashingJmxEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Found two endpoints with the id 'test': ")); + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpoint.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); } @Test void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { load(AdditionalClashingOperationsConfiguration.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); } @Test void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { load(InvalidJmxExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining( - "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); } @Test void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new JmxEndpointDiscovererRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(JmxEndpointFilter.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(JmxEndpointFilter.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); } private Object getInvoker(JmxOperation operation) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java index 8ca98ddd66..29a7b00384 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class EndpointLinksResolverTests { @Test void linkResolutionWithTrailingSlashStripsSlashOnSelfLink() { Map links = new EndpointLinksResolver(Collections.emptyList()) - .resolveLinks("https://api.example.com/actuator/"); + .resolveLinks("https://api.example.com/actuator/"); assertThat(links).hasSize(1); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); } @@ -50,7 +50,7 @@ class EndpointLinksResolverTests { @Test void linkResolutionWithoutTrailingSlash() { Map links = new EndpointLinksResolver(Collections.emptyList()) - .resolveLinks("https://api.example.com/actuator"); + .resolveLinks("https://api.example.com/actuator"); assertThat(links).hasSize(1); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); } @@ -66,7 +66,7 @@ class EndpointLinksResolverTests { given(endpoint.getOperations()).willReturn(operations); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(endpoint)) - .resolveLinks(requestUrl); + .resolveLinks(requestUrl); assertThat(links).hasSize(3); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); @@ -82,7 +82,7 @@ class EndpointLinksResolverTests { given(servletEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(servletEndpoint)) - .resolveLinks(requestUrl); + .resolveLinks(requestUrl); assertThat(links).hasSize(2); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); @@ -96,7 +96,7 @@ class EndpointLinksResolverTests { given(controllerEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(controllerEndpoint)) - .resolveLinks(requestUrl); + .resolveLinks(requestUrl); assertThat(links).hasSize(2); assertThat(links).hasEntrySatisfying("self", linkWithHref("https://api.example.com/actuator")); assertThat(links).hasEntrySatisfying("alpha", linkWithHref("https://api.example.com/actuator/alpha")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java index 2f351a0a69..a9495d188e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,13 +47,13 @@ class EndpointMediaTypesTests { @Test void createWhenProducedIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(null, Collections.emptyList())) - .withMessageContaining("Produced must not be null"); + .withMessageContaining("Produced must not be null"); } @Test void createWhenConsumedIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointMediaTypes(Collections.emptyList(), null)) - .withMessageContaining("Consumed must not be null"); + .withMessageContaining("Consumed must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java index b37e186b45..56a819fc51 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,13 +41,13 @@ class EndpointServletTests { @Test void createWhenServletClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Class) null)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test void createWhenServletIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EndpointServlet((Servlet) null)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test @@ -84,36 +84,36 @@ class EndpointServletTests { @Test void withInitParameterWhenHasExistingShouldMergeParameters() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") - .withInitParameter("c", "d"); + .withInitParameter("c", "d"); assertThat(endpointServlet.withInitParameter("a", "b1").withInitParameter("e", "f").getInitParameters()) - .containsExactly(entry("a", "b1"), entry("c", "d"), entry("e", "f")); + .containsExactly(entry("a", "b1"), entry("c", "d"), entry("e", "f")); } @Test void withInitParametersNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException() - .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(null, "value"))); + .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(null, "value"))); } @Test void withInitParametersEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThatIllegalArgumentException() - .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(" ", "value"))); + .isThrownBy(() -> endpointServlet.withInitParameters(Collections.singletonMap(" ", "value"))); } @Test void withInitParametersShouldCreateNewInstance() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); assertThat(endpointServlet.withInitParameters(Collections.singletonMap("spring", "boot"))) - .isNotSameAs(endpointServlet); + .isNotSameAs(endpointServlet); } @Test void withInitParametersWhenHasExistingShouldMergeParameters() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class).withInitParameter("a", "b") - .withInitParameter("c", "d"); + .withInitParameter("c", "d"); Map extra = new LinkedHashMap<>(); extra.put("a", "b1"); extra.put("e", "f"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java index 7921b178cc..65f5a43183 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -31,7 +31,7 @@ class LinkTests { @Test void createWhenHrefIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Link(null)) - .withMessageContaining("HREF must not be null"); + .withMessageContaining("HREF must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java index fa13f1e7a3..246a3991ca 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,15 +42,15 @@ class PathMappedEndpointsTests { @Test void createWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) - .withMessageContaining("Supplier must not be null"); + .isThrownBy(() -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) + .withMessageContaining("Supplier must not be null"); } @Test void createWhenSuppliersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PathMappedEndpoints(null, (Collection>) null)) - .withMessageContaining("Suppliers must not be null"); + .isThrownBy(() -> new PathMappedEndpoints(null, (Collection>) null)) + .withMessageContaining("Suppliers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java index 088a5f23a6..82d81e4bfb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ class ServletEndpointRegistrarTests { @Test void createWhenServletEndpointsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ServletEndpointRegistrar(null, null)) - .withMessageContaining("ServletEndpoints must not be null"); + .withMessageContaining("ServletEndpoints must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java index ebd7b24ed0..5c7e87a48f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/WebOperationRequestPredicateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class WebOperationRequestPredicateTests { @Test void predicatesWithMultiplePathVariablesInTheSamePlaceAreEqual() { assertThat(predicateWithPath("/path/{foo1}/more/{bar1}")) - .isEqualTo(predicateWithPath("/path/{foo2}/more/{bar2}")); + .isEqualTo(predicateWithPath("/path/{foo2}/more/{bar2}")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java index 1648284866..d23d6fe380 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,36 +84,79 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("All") + .isEqualTo(true)); } @Test void readOperationWithEndpointsMappedToTheRoot() { - load(TestEndpointConfiguration.class, "", (client) -> client.get().uri("/test").exchange().expectStatus().isOk() - .expectBody().jsonPath("All").isEqualTo(true)); + load(TestEndpointConfiguration.class, "", + (client) -> client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("All") + .isEqualTo(true)); } @Test void readOperationWithSelector() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/one").exchange().expectStatus().isOk() - .expectBody().jsonPath("part").isEqualTo("one")); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test/one") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("part") + .isEqualTo("one")); } @Test void readOperationWithSelectorContainingADot() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test/foo.bar").exchange().expectStatus() - .isOk().expectBody().jsonPath("part").isEqualTo("foo.bar")); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test/foo.bar") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("part") + .isEqualTo("foo.bar")); } @Test void linksToOtherEndpointsAreProvided() { load(TestEndpointConfiguration.class, - (client) -> client.get().uri("").exchange().expectStatus().isOk().expectBody() - .jsonPath("_links.length()").isEqualTo(3).jsonPath("_links.self.href").isNotEmpty() - .jsonPath("_links.self.templated").isEqualTo(false).jsonPath("_links.test.href").isNotEmpty() - .jsonPath("_links.test.templated").isEqualTo(false).jsonPath("_links.test-part.href") - .isNotEmpty().jsonPath("_links.test-part.templated").isEqualTo(true)); + (client) -> client.get() + .uri("") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("_links.length()") + .isEqualTo(3) + .jsonPath("_links.self.href") + .isNotEmpty() + .jsonPath("_links.self.templated") + .isEqualTo(false) + .jsonPath("_links.test.href") + .isNotEmpty() + .jsonPath("_links.test.templated") + .isEqualTo(false) + .jsonPath("_links.test-part.href") + .isNotEmpty() + .jsonPath("_links.test-part.templated") + .isEqualTo(true)); } @Test @@ -131,46 +174,91 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/matchallremaining/one/two/three").exchange().expectStatus().isOk() - .expectBody().jsonPath("selection").isEqualTo("one|two|three")); + (client) -> client.get() + .uri("/matchallremaining/one/two/three") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("selection") + .isEqualTo("one|two|three")); } @Test void matchAllRemainingPathsSelectorShouldDecodePath() { load(MatchAllRemainingEndpointConfiguration.class, - (client) -> client.get().uri("/matchallremaining/one/two three/").exchange().expectStatus().isOk() - .expectBody().jsonPath("selection").isEqualTo("one|two three")); + (client) -> client.get() + .uri("/matchallremaining/one/two three/") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("selection") + .isEqualTo("one|two three")); } @Test void readOperationWithSingleQueryParameters() { - load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 2")); + load(QueryEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1 2")); } @Test void readOperationWithSingleQueryParametersAndMultipleValues() { - load(QueryEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1,1 2")); + load(QueryEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&one=1&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1,1 2")); } @Test void readOperationWithListQueryParameterAndSingleValue() { - load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2").exchange() - .expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2]")); + load(QueryWithListEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1 [2]")); } @Test void readOperationWithListQueryParameterAndMultipleValues() { - load(QueryWithListEndpointConfiguration.class, (client) -> client.get().uri("/query?one=1&two=2&two=2") - .exchange().expectStatus().isOk().expectBody().jsonPath("query").isEqualTo("1 [2, 2]")); + load(QueryWithListEndpointConfiguration.class, + (client) -> client.get() + .uri("/query?one=1&two=2&two=2") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("query") + .isEqualTo("1 [2, 2]")); } @Test void readOperationWithMappingFailureProducesBadRequestResponse() { load(QueryEndpointConfiguration.class, (client) -> { - WebTestClient.BodyContentSpec body = client.get().uri("/query?two=two").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isBadRequest().expectBody(); + WebTestClient.BodyContentSpec body = client.get() + .uri("/query?two=two") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isBadRequest() + .expectBody(); validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/query", "Missing parameters: one"); }); } @@ -195,8 +283,15 @@ public abstract class AbstractWebEndpointIntegrationTests client.delete().uri("/test/one").exchange().expectStatus() - .isOk().expectBody().jsonPath("part").isEqualTo("one")); + load(TestEndpointConfiguration.class, + (client) -> client.delete() + .uri("/test/one") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("part") + .isEqualTo("one")); } @Test @@ -220,8 +315,14 @@ public abstract class AbstractWebEndpointIntegrationTests { - client.post().uri("/test").contentType(MediaType.APPLICATION_JSON).exchange().expectStatus().isNoContent() - .expectBody().isEmpty(); + client.post() + .uri("/test") + .contentType(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNoContent() + .expectBody() + .isEmpty(); then(context.getBean(EndpointDelegate.class)).should().write(null, null); }); } @@ -247,9 +348,15 @@ public abstract class AbstractWebEndpointIntegrationTests { - byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); }); } @@ -257,38 +364,71 @@ public abstract class AbstractWebEndpointIntegrationTests { - byte[] responseBody = client.get().uri("/resource").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); }); } @Test void readOperationWithMonoResponse() { - load(MonoResponseEndpointConfiguration.class, (client) -> client.get().uri("/mono").exchange().expectStatus() - .isOk().expectBody().jsonPath("a").isEqualTo("alpha")); + load(MonoResponseEndpointConfiguration.class, + (client) -> client.get() + .uri("/mono") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("a") + .isEqualTo("alpha")); } @Test void readOperationWithFluxResponse() { load(FluxResponseEndpointConfiguration.class, - (client) -> client.get().uri("/flux").exchange().expectStatus().isOk().expectBody().jsonPath("[0].a") - .isEqualTo("alpha").jsonPath("[1].b").isEqualTo("bravo").jsonPath("[2].c") - .isEqualTo("charlie")); + (client) -> client.get() + .uri("/flux") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("[0].a") + .isEqualTo("alpha") + .jsonPath("[1].b") + .isEqualTo("bravo") + .jsonPath("[2].c") + .isEqualTo("charlie")); } @Test void readOperationWithCustomMediaType() { - load(CustomMediaTypesEndpointConfiguration.class, (client) -> client.get().uri("/custommediatypes").exchange() - .expectStatus().isOk().expectHeader().valueMatches("Content-Type", "text/plain(;charset=.*)?")); + load(CustomMediaTypesEndpointConfiguration.class, + (client) -> client.get() + .uri("/custommediatypes") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", "text/plain(;charset=.*)?")); } @Test void readOperationWithMissingRequiredParametersReturnsBadRequestResponse() { load(RequiredParameterEndpointConfiguration.class, (client) -> { - WebTestClient.BodyContentSpec body = client.get().uri("/requiredparameters") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isBadRequest().expectBody(); + WebTestClient.BodyContentSpec body = client.get() + .uri("/requiredparameters") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isBadRequest() + .expectBody(); validateErrorBody(body, HttpStatus.BAD_REQUEST, "/endpoints/requiredparameters", "Missing parameters: foo"); }); } @@ -301,33 +441,65 @@ public abstract class AbstractWebEndpointIntegrationTests client.get().uri("/test").exchange().expectStatus().isOk() - .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test void endpointsProduceSecondaryMediaTypeWhenRequested() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("/test").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("/test") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test void linksProducesPrimaryMediaTypeByDefault() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("").exchange().expectStatus().isOk() - .expectHeader().valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", ACTUATOR_MEDIA_TYPE_PATTERN)); } @Test void linksProducesSecondaryMediaTypeWhenRequested() { - load(TestEndpointConfiguration.class, (client) -> client.get().uri("").accept(MediaType.APPLICATION_JSON) - .exchange().expectStatus().isOk().expectHeader().valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); + load(TestEndpointConfiguration.class, + (client) -> client.get() + .uri("") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueMatches("Content-Type", JSON_MEDIA_TYPE_PATTERN)); } @Test void principalIsNullWhenRequestHasNoPrincipal() { load(PrincipalEndpointConfiguration.class, - (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("None")); + (client) -> client.get() + .uri("/principal") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("None")); } @Test @@ -335,8 +507,14 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalEndpointConfiguration.class); - }, (client) -> client.get().uri("/principal").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("Alice")); + }, (client) -> client.get() + .uri("/principal") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Alice")); } @Test @@ -344,15 +522,27 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(PrincipalQueryEndpointConfiguration.class); - }, (client) -> client.get().uri("/principalquery?principal=Zoe").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("Zoe")); + }, (client) -> client.get() + .uri("/principalquery?principal=Zoe") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Zoe")); } @Test void securityContextIsAvailableAndHasNullPrincipalWhenRequestHasNoPrincipal() { load(SecurityContextEndpointConfiguration.class, - (client) -> client.get().uri("/securitycontext").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("None")); + (client) -> client.get() + .uri("/securitycontext") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("None")); } @Test @@ -360,15 +550,27 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(SecurityContextEndpointConfiguration.class); - }, (client) -> client.get().uri("/securitycontext").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody(String.class).isEqualTo("Alice")); + }, (client) -> client.get() + .uri("/securitycontext") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Alice")); } @Test void userInRoleReturnsFalseWhenRequestHasNoPrincipal() { load(UserInRoleEndpointConfiguration.class, - (client) -> client.get().uri("/userinrole?role=ADMIN").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("ADMIN: false")); + (client) -> client.get() + .uri("/userinrole?role=ADMIN") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("ADMIN: false")); } @Test @@ -376,8 +578,14 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); - }, (client) -> client.get().uri("/userinrole?role=ADMIN").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("ADMIN: false")); + }, (client) -> client.get() + .uri("/userinrole?role=ADMIN") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("ADMIN: false")); } @Test @@ -385,8 +593,14 @@ public abstract class AbstractWebEndpointIntegrationTests { this.authenticatedContextCustomizer.accept(context); context.register(UserInRoleEndpointConfiguration.class); - }, (client) -> client.get().uri("/userinrole?role=ACTUATOR").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("ACTUATOR: true")); + }, (client) -> client.get() + .uri("/userinrole?role=ACTUATOR") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("ACTUATOR: true")); } @Test @@ -399,8 +613,14 @@ public abstract class AbstractWebEndpointIntegrationTests configuration, BiConsumer consumer) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java index 88127143dc..bf29e3bde1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,7 @@ class ControllerEndpointDiscovererTests { @Test void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); + .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test @@ -75,66 +75,67 @@ class ControllerEndpointDiscovererTests { @Test void getEndpointsShouldDiscoverProxyControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyControllerEndpoint.class) - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testcontroller")); - assertThat(endpoint.getController()).isInstanceOf(TestProxyControllerEndpoint.class); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableControllerEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestProxyControllerEndpoint.class); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test void getEndpointsShouldIncludeRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestRestControllerEndpoint.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); - assertThat(endpoint.getController()).isInstanceOf(TestRestControllerEndpoint.class); - })); + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableControllerEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestRestControllerEndpoint.class); + })); } @Test void getEndpointsShouldDiscoverProxyRestControllerEndpoints() { this.contextRunner.withUserConfiguration(TestProxyRestControllerEndpoint.class) - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableControllerEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); - assertThat(endpoint.getController()).isInstanceOf(TestProxyRestControllerEndpoint.class); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableControllerEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testrestcontroller")); + assertThat(endpoint.getController()).isInstanceOf(TestProxyRestControllerEndpoint.class); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - List ids = endpoints.stream().map(ExposableControllerEndpoint::getEndpointId).toList(); - assertThat(ids).containsOnly(EndpointId.of("testcontroller"), EndpointId.of("testrestcontroller")); - })); + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + List ids = endpoints.stream().map(ExposableControllerEndpoint::getEndpointId).toList(); + assertThat(ids).containsOnly(EndpointId.of("testcontroller"), EndpointId.of("testrestcontroller")); + })); } @Test void getEndpointWhenEndpointHasOperationsShouldThrowException() { - this.contextRunner.withUserConfiguration(TestControllerWithOperation.class).run( - assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("ControllerEndpoints must not declare operations"))); + this.contextRunner.withUserConfiguration(TestControllerWithOperation.class) + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("ControllerEndpoints must not declare operations"))); } @Test void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new ControllerEndpointDiscovererRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(ControllerEndpointFilter.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(ControllerEndpointFilter.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java index 0e68f0cb63..372a8a61b8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,16 +48,16 @@ class RequestPredicateFactoryTests { void getRequestPredicateWhenHasMoreThanOneMatchAllThrowsException() { DiscoveredOperationMethod operationMethod = getDiscoveredOperationMethod(MoreThanOneMatchAll.class); assertThatIllegalStateException() - .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) - .withMessage("@Selector annotation with Match.ALL_REMAINING must be unique"); + .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) + .withMessage("@Selector annotation with Match.ALL_REMAINING must be unique"); } @Test void getRequestPredicateWhenMatchAllIsNotLastParameterThrowsException() { DiscoveredOperationMethod operationMethod = getDiscoveredOperationMethod(MatchAllIsNotLastParameter.class); assertThatIllegalStateException() - .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) - .withMessage("@Selector annotation with Match.ALL_REMAINING must be the last parameter"); + .isThrownBy(() -> this.factory.getRequestPredicate(this.rootPath, operationMethod)) + .withMessage("@Selector annotation with Match.ALL_REMAINING must be the last parameter"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java index d5fd60c890..e4d9ec56a7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -65,7 +65,7 @@ class ServletEndpointDiscovererTests { @Test void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); + .run(assertDiscoverer((discoverer) -> assertThat(discoverer.getEndpoints()).isEmpty())); } @Test @@ -83,61 +83,62 @@ class ServletEndpointDiscovererTests { @Test void getEndpointsShouldDiscoverProxyServletEndpoints() { this.contextRunner.withUserConfiguration(TestProxyServletEndpoint.class) - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - assertThat(endpoints).hasSize(1); - ExposableServletEndpoint endpoint = endpoints.iterator().next(); - assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testservlet")); - assertThat(endpoint.getEndpointServlet()).isNotNull(); - assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + assertThat(endpoints).hasSize(1); + ExposableServletEndpoint endpoint = endpoints.iterator().next(); + assertThat(endpoint.getEndpointId()).isEqualTo(EndpointId.of("testservlet")); + assertThat(endpoint.getEndpointServlet()).isNotNull(); + assertThat(endpoint).isInstanceOf(DiscoveredEndpoint.class); + })); } @Test void getEndpointsShouldNotDiscoverRegularEndpoints() { this.contextRunner.withUserConfiguration(WithRegularEndpointConfiguration.class) - .run(assertDiscoverer((discoverer) -> { - Collection endpoints = discoverer.getEndpoints(); - List ids = endpoints.stream().map(ExposableServletEndpoint::getEndpointId).toList(); - assertThat(ids).containsOnly(EndpointId.of("testservlet")); - })); + .run(assertDiscoverer((discoverer) -> { + Collection endpoints = discoverer.getEndpoints(); + List ids = endpoints.stream().map(ExposableServletEndpoint::getEndpointId).toList(); + assertThat(ids).containsOnly(EndpointId.of("testservlet")); + })); } @Test void getEndpointWhenEndpointHasOperationsShouldThrowException() { - this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class).run( - assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("ServletEndpoints must not declare operations"))); + this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class) + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("ServletEndpoints must not declare operations"))); } @Test void getEndpointWhenEndpointNotASupplierShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointNotASupplier.class) - .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining("must be a supplier"))); + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must be a supplier"))); } @Test void getEndpointWhenEndpointSuppliesWrongTypeShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) - .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining("must supply an EndpointServlet"))); + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must supply an EndpointServlet"))); } @Test void getEndpointWhenEndpointSuppliesNullShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfNull.class) - .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException() - .isThrownBy(discoverer::getEndpoints).withMessageContaining("must not supply null"))); + .run(assertDiscoverer((discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must not supply null"))); } @Test void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new ServletEndpointDiscovererRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(ServletEndpointFilter.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(ServletEndpointFilter.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); } private ContextConsumer assertDiscoverer( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java index 18048ed371..02cc46336e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -81,8 +81,7 @@ class WebEndpointDiscovererTests { void getEndpointsWhenWebExtensionIsMissingEndpointShouldThrowException() { load(TestWebEndpointExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining( - "Invalid extension 'endpointExtension': no endpoint found with id 'test'")); + .withMessageContaining("Invalid extension 'endpointExtension': no endpoint found with id 'test'")); } @Test @@ -131,40 +130,40 @@ class WebEndpointDiscovererTests { void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { load(ClashingWebEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Found multiple extensions for the endpoint bean " - + "testEndpoint (testExtensionOne, testExtensionTwo)")); + .withMessageContaining("Found multiple extensions for the endpoint bean " + + "testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { load(ClashingStandardEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Found two endpoints with the id 'test': ")); + .withMessageContaining("Found two endpoints with the id 'test': ")); } @Test void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingOperationsEndpointConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Unable to map duplicate endpoint operations: " - + "[web request predicate GET to path 'test' " - + "produces: application/json] to clashingOperationsEndpoint")); + .withMessageContaining("Unable to map duplicate endpoint operations: " + + "[web request predicate GET to path 'test' " + + "produces: application/json] to clashingOperationsEndpoint")); } @Test void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { load(InvalidWebExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Endpoint bean 'nonWebEndpoint' cannot support the " - + "extension bean 'nonWebWebEndpointExtension'")); + .withMessageContaining("Endpoint bean 'nonWebEndpoint' cannot support the " + + "extension bean 'nonWebWebEndpointExtension'")); } @Test void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { load(ClashingSelectorsWebEndpointExtensionConfiguration.class, (discoverer) -> assertThatIllegalStateException().isThrownBy(discoverer::getEndpoints) - .withMessageContaining("Unable to map duplicate endpoint operations") - .withMessageContaining("to testEndpoint (clashingSelectorsExtension)")); + .withMessageContaining("Unable to map duplicate endpoint operations") + .withMessageContaining("to testEndpoint (clashingSelectorsExtension)")); } @Test @@ -187,8 +186,10 @@ class WebEndpointDiscovererTests { Map endpoints = mapEndpoints(discoverer.getEndpoints()); assertThat(endpoints).containsOnlyKeys(EndpointId.of("resource")); ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("resource")); - assertThat(requestPredicates(endpoint)).has(requestPredicates(path("resource") - .httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/octet-stream"))); + assertThat(requestPredicates(endpoint)) + .has(requestPredicates(path("resource").httpMethod(WebEndpointHttpMethod.GET) + .consumes() + .produces("application/octet-stream"))); }); } @@ -201,8 +202,9 @@ class WebEndpointDiscovererTests { assertThat(requestPredicates(endpoint)).has(requestPredicates( path("custommediatypes").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("text/plain"), path("custommediatypes").httpMethod(WebEndpointHttpMethod.POST).consumes().produces("a/b", "c/d"), - path("custommediatypes").httpMethod(WebEndpointHttpMethod.DELETE).consumes() - .produces("text/plain"))); + path("custommediatypes").httpMethod(WebEndpointHttpMethod.DELETE) + .consumes() + .produces("text/plain"))); }); } @@ -214,8 +216,9 @@ class WebEndpointDiscovererTests { ExposableWebEndpoint endpoint = endpoints.get(EndpointId.of("test")); Condition> expected = requestPredicates( path("custom/test").httpMethod(WebEndpointHttpMethod.GET).consumes().produces("application/json"), - path("custom/test/{id}").httpMethod(WebEndpointHttpMethod.GET).consumes() - .produces("application/json")); + path("custom/test/{id}").httpMethod(WebEndpointHttpMethod.GET) + .consumes() + .produces("application/json")); assertThat(requestPredicates(endpoint)).has(expected); }); } @@ -224,8 +227,9 @@ class WebEndpointDiscovererTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new WebEndpointDiscovererRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(WebEndpointFilter.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(WebEndpointFilter.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMappingTests.java index e234dbcfc6..3abb506a72 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/AbstractWebFluxEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,12 +37,14 @@ class AbstractWebFluxEndpointHandlerMappingTests { RuntimeHints runtimeHints = new RuntimeHints(); new AbstractWebFluxEndpointHandlerMappingRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of( - "org.springframework.boot.actuate.endpoint.web.reactive.AbstractWebFluxEndpointHandlerMapping.WriteOperationHandler"))) - .accepts(runtimeHints); - assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of( - "org.springframework.boot.actuate.endpoint.web.reactive.AbstractWebFluxEndpointHandlerMapping.ReadOperationHandler"))) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(TypeReference + .of("org.springframework.boot.actuate.endpoint.web.reactive.AbstractWebFluxEndpointHandlerMapping.WriteOperationHandler"))) + .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(TypeReference + .of("org.springframework.boot.actuate.endpoint.web.reactive.AbstractWebFluxEndpointHandlerMapping.ReadOperationHandler"))) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java index 1b7517b661..03e5a94dfa 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -61,34 +61,51 @@ import org.springframework.web.util.DefaultUriBuilderFactory; class ControllerEndpointHandlerMappingIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, - ExampleWebFluxEndpoint.class); + AnnotationConfigReactiveWebServerApplicationContext::new) + .withUserConfiguration(EndpointConfiguration.class, ExampleWebFluxEndpoint.class); @Test void get() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() - .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_PLAIN) + .expectBody(String.class) + .isEqualTo("One"))); } @Test void getWithUnacceptableContentType() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test void post() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") - .bodyValue(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() - .valueEquals(HttpHeaders.LOCATION, "/example/test"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post() + .uri("/actuator/example/two") + .bodyValue(Collections.singletonMap("id", "test")) + .exchange() + .expectStatus() + .isCreated() + .expectHeader() + .valueEquals(HttpHeaders.LOCATION, "/example/test"))); } private ContextConsumer withWebTestClient( Consumer webClient) { return (context) -> { int port = ((AnnotationConfigReactiveWebServerApplicationContext) context.getSourceApplicationContext()) - .getWebServer().getPort(); + .getWebServer() + .getPort(); WebTestClient webTestClient = createWebTestClient(port); webClient.accept(webTestClient); }; @@ -97,8 +114,10 @@ class ControllerEndpointHandlerMappingIntegrationTests { private WebTestClient createWebTestClient(int port) { DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://localhost:" + port); uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(Duration.ofMinutes(5)) - .build(); + return WebTestClient.bindToServer() + .uriBuilderFactory(uriBuilderFactory) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java index 635b58c15d..e307b8d1bc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,7 @@ class ControllerEndpointHandlerMappingTests { ControllerEndpointHandlerMapping mapping = createMapping("", first, second); assertThat(getHandler(mapping, HttpMethod.GET, "/first")).isEqualTo(handlerOf(first.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.POST, "/second")) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(getHandler(mapping, HttpMethod.GET, "/third")).isNull(); } @@ -67,9 +67,9 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); assertThat(getHandler(mapping, HttpMethod.GET, "/actuator/first")) - .isEqualTo(handlerOf(first.getController(), "get")); + .isEqualTo(handlerOf(first.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.POST, "/actuator/second")) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(getHandler(mapping, HttpMethod.GET, "/first")).isNull(); assertThat(getHandler(mapping, HttpMethod.GET, "/second")).isNull(); } @@ -79,7 +79,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint pathless = pathlessEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", pathless); assertThat(getHandler(mapping, HttpMethod.GET, "/actuator/pathless")) - .isEqualTo(handlerOf(pathless.getController(), "get")); + .isEqualTo(handlerOf(pathless.getController(), "get")); assertThat(getHandler(mapping, HttpMethod.GET, "/pathless")).isNull(); assertThat(getHandler(mapping, HttpMethod.GET, "/")).isNull(); } @@ -89,7 +89,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); assertThatExceptionOfType(MethodNotAllowedException.class) - .isThrownBy(() -> getHandler(mapping, HttpMethod.POST, "/actuator/first")); + .isThrownBy(() -> getHandler(mapping, HttpMethod.POST, "/actuator/first")); } private Object getHandler(ControllerEndpointHandlerMapping mapping, HttpMethod method, String requestURI) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMappingTests.java index 4d02996eaa..988853cc21 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ class WebFluxEndpointHandlerMappingTests { RuntimeHints runtimeHints = new RuntimeHints(); new WebFluxEndpointHandlerMappingRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onMethod(WebFluxLinksHandler.class, "links")) - .accepts(runtimeHints); + .accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(Link.class)).accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java index b6aaf05a70..f27d667e57 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -77,20 +77,33 @@ class WebFluxEndpointIntegrationTests @Test void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, - (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") - .exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST")); + (client) -> client.options() + .uri("/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { - byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() - .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .header("Range", "bytes=0-3") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.PARTIAL_CONTENT) + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3); }); } @@ -141,9 +154,9 @@ class WebFluxEndpointIntegrationTests @Bean WebFilter webFilter() { - return (exchange, chain) -> chain.filter(exchange).contextWrite( - ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken("Alice", - "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR"))))); + return (exchange, chain) -> chain.filter(exchange) + .contextWrite(ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken( + "Alice", "secret", Arrays.asList(new SimpleGrantedAuthority("ROLE_ACTUATOR"))))); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMappingTests.java index cd5a152d83..799ae9b7e9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/AbstractWebMvcEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,9 +36,10 @@ class AbstractWebMvcEndpointHandlerMappingTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new AbstractWebMvcEndpointHandlerMappingRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of( - "org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.OperationHandler"))) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(TypeReference + .of("org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping.OperationHandler"))) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java index bf8b98b736..75b5877794 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -60,33 +60,50 @@ import org.springframework.web.util.DefaultUriBuilderFactory; class ControllerEndpointHandlerMappingIntegrationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( - AnnotationConfigServletWebServerApplicationContext::new).withUserConfiguration(EndpointConfiguration.class, - ExampleMvcEndpoint.class); + AnnotationConfigServletWebServerApplicationContext::new) + .withUserConfiguration(EndpointConfiguration.class, ExampleMvcEndpoint.class); @Test void get() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk().expectHeader() - .contentTypeCompatibleWith(MediaType.TEXT_PLAIN).expectBody(String.class).isEqualTo("One"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_PLAIN) + .expectBody(String.class) + .isEqualTo("One"))); } @Test void getWithUnacceptableContentType() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get().uri("/actuator/example/one") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.get() + .uri("/actuator/example/one") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.NOT_ACCEPTABLE))); } @Test void post() { - this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post().uri("/actuator/example/two") - .bodyValue(Collections.singletonMap("id", "test")).exchange().expectStatus().isCreated().expectHeader() - .valueEquals(HttpHeaders.LOCATION, "/example/test"))); + this.contextRunner.run(withWebTestClient((webTestClient) -> webTestClient.post() + .uri("/actuator/example/two") + .bodyValue(Collections.singletonMap("id", "test")) + .exchange() + .expectStatus() + .isCreated() + .expectHeader() + .valueEquals(HttpHeaders.LOCATION, "/example/test"))); } private ContextConsumer withWebTestClient(Consumer webClient) { return (context) -> { int port = ((AnnotationConfigServletWebServerApplicationContext) context.getSourceApplicationContext()) - .getWebServer().getPort(); + .getWebServer() + .getPort(); WebTestClient webTestClient = createWebTestClient(port); webClient.accept(webTestClient); }; @@ -95,8 +112,10 @@ class ControllerEndpointHandlerMappingIntegrationTests { private WebTestClient createWebTestClient(int port) { DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory("http://localhost:" + port); uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(Duration.ofMinutes(5)) - .build(); + return WebTestClient.bindToServer() + .uriBuilderFactory(uriBuilderFactory) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java index b9b1b09ec5..9a74d68b33 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -53,9 +53,9 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("", first, second); assertThat(mapping.getHandler(request("GET", "/first")).getHandler()) - .isEqualTo(handlerOf(first.getController(), "get")); + .isEqualTo(handlerOf(first.getController(), "get")); assertThat(mapping.getHandler(request("POST", "/second")).getHandler()) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(mapping.getHandler(request("GET", "/third"))).isNull(); } @@ -65,9 +65,9 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint second = secondEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first, second); assertThat(mapping.getHandler(request("GET", "/actuator/first")).getHandler()) - .isEqualTo(handlerOf(first.getController(), "get")); + .isEqualTo(handlerOf(first.getController(), "get")); assertThat(mapping.getHandler(request("POST", "/actuator/second")).getHandler()) - .isEqualTo(handlerOf(second.getController(), "save")); + .isEqualTo(handlerOf(second.getController(), "save")); assertThat(mapping.getHandler(request("GET", "/first"))).isNull(); assertThat(mapping.getHandler(request("GET", "/second"))).isNull(); } @@ -77,7 +77,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class) - .isThrownBy(() -> mapping.getHandler(request("POST", "/actuator/first"))); + .isThrownBy(() -> mapping.getHandler(request("POST", "/actuator/first"))); } @Test @@ -85,7 +85,7 @@ class ControllerEndpointHandlerMappingTests { ExposableControllerEndpoint pathless = pathlessEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", pathless); assertThat(mapping.getHandler(request("GET", "/actuator/pathless")).getHandler()) - .isEqualTo(handlerOf(pathless.getController(), "get")); + .isEqualTo(handlerOf(pathless.getController(), "get")); assertThat(mapping.getHandler(request("GET", "/pathless"))).isNull(); assertThat(mapping.getHandler(request("GET", "/"))).isNull(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java index e84a947074..4bdcb94ce4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/DefaultWebMvcTagsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,8 @@ class DefaultWebMvcTagsProviderTests { void givenSomeContributorsWhenTagsAreProvidedThenDefaultTagsAndContributedTagsArePresent() { Map tags = asMap( new DefaultWebMvcTagsProvider(Arrays.asList(new TestWebMvcTagsContributor("alpha"), - new TestWebMvcTagsContributor("bravo", "charlie"))).getTags(null, null, null, null)); + new TestWebMvcTagsContributor("bravo", "charlie"))) + .getTags(null, null, null, null)); assertThat(tags).containsOnlyKeys("exception", "method", "outcome", "status", "uri", "alpha", "bravo", "charlie"); } @@ -69,7 +70,8 @@ class DefaultWebMvcTagsProviderTests { void givenSomeContributorsWhenLongRequestTagsAreProvidedThenDefaultTagsAndContributedTagsArePresent() { Map tags = asMap( new DefaultWebMvcTagsProvider(Arrays.asList(new TestWebMvcTagsContributor("alpha"), - new TestWebMvcTagsContributor("bravo", "charlie"))).getLongRequestTags(null, null)); + new TestWebMvcTagsContributor("bravo", "charlie"))) + .getLongRequestTags(null, null)); assertThat(tags).containsOnlyKeys("method", "uri", "alpha", "bravo", "charlie"); } @@ -91,7 +93,7 @@ class DefaultWebMvcTagsProviderTests { private Map asMap(Iterable tags) { return StreamSupport.stream(tags.spliterator(), false) - .collect(Collectors.toMap(Tag::getKey, Function.identity())); + .collect(Collectors.toMap(Tag::getKey, Function.identity())); } private static final class TestWebMvcTagsContributor implements WebMvcTagsContributor { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java index d793e7d52e..3cbca88dd6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/MvcWebEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -83,28 +83,46 @@ class MvcWebEndpointIntegrationTests @Test void responseToOptionsRequestIncludesCorsHeaders() { load(TestEndpointConfiguration.class, - (client) -> client.options().uri("/test").accept(MediaType.APPLICATION_JSON) - .header("Access-Control-Request-Method", "POST").header("Origin", "https://example.com") - .exchange().expectStatus().isOk().expectHeader() - .valueEquals("Access-Control-Allow-Origin", "https://example.com").expectHeader() - .valueEquals("Access-Control-Allow-Methods", "GET,POST")); + (client) -> client.options() + .uri("/test") + .accept(MediaType.APPLICATION_JSON) + .header("Access-Control-Request-Method", "POST") + .header("Origin", "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("Access-Control-Allow-Origin", "https://example.com") + .expectHeader() + .valueEquals("Access-Control-Allow-Methods", "GET,POST")); } @Test void readOperationsThatReturnAResourceSupportRangeRequests() { load(ResourceEndpointConfiguration.class, (client) -> { - byte[] responseBody = client.get().uri("/resource").header("Range", "bytes=0-3").exchange().expectStatus() - .isEqualTo(HttpStatus.PARTIAL_CONTENT).expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).returnResult(byte[].class) - .getResponseBodyContent(); + byte[] responseBody = client.get() + .uri("/resource") + .header("Range", "bytes=0-3") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.PARTIAL_CONTENT) + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .returnResult(byte[].class) + .getResponseBodyContent(); assertThat(responseBody).containsExactly(0, 1, 2, 3); }); } @Test void requestWithSuffixShouldNotMatch() { - load(TestEndpointConfiguration.class, (client) -> client.options().uri("/test.do") - .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isNotFound()); + load(TestEndpointConfiguration.class, + (client) -> client.options() + .uri("/test.do") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNotFound()); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMappingTests.java index fcfc2d3018..11bd7ee410 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/WebMvcEndpointHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ class WebMvcEndpointHandlerMappingTests { RuntimeHints runtimeHints = new RuntimeHints(); new WebMvcEndpointHandlerMappingRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onMethod(WebMvcLinksHandler.class, "links")) - .accepts(runtimeHints); + .accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(Link.class)).accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java index a4cab4516b..debfdb6078 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -144,8 +144,9 @@ class WebEndpointTestInvocationContextProvider implements TestTemplateInvocation @Override public void beforeEach(ExtensionContext extensionContext) throws Exception { List> configurationClasses = Stream - .of(extensionContext.getRequiredTestClass().getDeclaredClasses()).filter(this::isConfiguration) - .collect(Collectors.toCollection(ArrayList::new)); + .of(extensionContext.getRequiredTestClass().getDeclaredClasses()) + .filter(this::isConfiguration) + .collect(Collectors.toCollection(ArrayList::new)); this.context = this.contextFactory.apply(configurationClasses); } @@ -191,13 +192,17 @@ class WebEndpointTestInvocationContextProvider implements TestTemplateInvocation DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory( "http://localhost:" + determinePort()); uriBuilderFactory.setEncodingMode(EncodingMode.NONE); - return WebTestClient.bindToServer().uriBuilderFactory(uriBuilderFactory).responseTimeout(TIMEOUT) - .codecs((codecs) -> codecs.defaultCodecs().maxInMemorySize(-1)).filter((request, next) -> { - if (HttpMethod.GET == request.method()) { - return next.exchange(request).retry(10); - } - return next.exchange(request); - }).build(); + return WebTestClient.bindToServer() + .uriBuilderFactory(uriBuilderFactory) + .responseTimeout(TIMEOUT) + .codecs((codecs) -> codecs.defaultCodecs().maxInMemorySize(-1)) + .filter((request, next) -> { + if (HttpMethod.GET == request.method()) { + return next.exchange(request).retry(10); + } + return next.exchange(request); + }) + .build(); } private int determinePort() { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java index dd9d2e1f1e..3621fcae49 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -75,7 +75,7 @@ class EnvironmentEndpointTests { environment.getPropertySources().addLast(singleKeyPropertySource("one", "my.key", "first")); environment.getPropertySources().addLast(singleKeyPropertySource("two", "my.key", "second")); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); assertThat(descriptor.getActiveProfiles()).isEmpty(); Map sources = propertySources(descriptor); assertThat(sources.keySet()).containsExactly("one", "two"); @@ -89,11 +89,11 @@ class EnvironmentEndpointTests { TestPropertyValues.of("other.service=abcde").applyTo(environment); TestPropertyValues.of("system.service=123456").applyToSystemProperties(() -> { EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.NEVER) - .environment(null); + .environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("other.service").getValue()) - .isEqualTo("******"); + .isEqualTo("******"); Map systemProperties = propertySources(descriptor).get("systemProperties") - .getProperties(); + .getProperties(); assertThat(systemProperties.get("system.service").getValue()).isEqualTo("******"); return null; }); @@ -105,11 +105,12 @@ class EnvironmentEndpointTests { TestPropertyValues.of("other.service=abcde").applyTo(environment); TestPropertyValues.of("system.service=123456").applyToSystemProperties(() -> { EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), - Show.WHEN_AUTHORIZED).environment(null); + Show.WHEN_AUTHORIZED) + .environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("other.service").getValue()) - .isEqualTo("abcde"); + .isEqualTo("abcde"); Map systemProperties = propertySources(descriptor).get("systemProperties") - .getProperties(); + .getProperties(); assertThat(systemProperties.get("system.service").getValue()).isEqualTo("123456"); return null; }); @@ -123,7 +124,7 @@ class EnvironmentEndpointTests { source.addPropertySource(new MapPropertySource("two", Collections.singletonMap("foo", "spam"))); environment.getPropertySources().addFirst(source); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); Map sources = propertySources(descriptor); assertThat(sources.keySet()).containsExactly("composite:one", "composite:two"); assertThat(sources.get("composite:one").getProperties().get("foo").getValue()).isEqualTo("bar"); @@ -142,11 +143,12 @@ class EnvironmentEndpointTests { return data.withValue("******"); } return data; - }), Show.ALWAYS).environment(null); + }), Show.ALWAYS) + .environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("other.service").getValue()) - .isEqualTo("abcde"); + .isEqualTo("abcde"); Map systemProperties = propertySources(descriptor).get("systemProperties") - .getProperties(); + .getProperties(); assertThat(systemProperties.get("system.service").getValue()).isEqualTo("******"); return null; }); @@ -157,7 +159,7 @@ class EnvironmentEndpointTests { ConfigurableEnvironment environment = emptyEnvironment(); TestPropertyValues.of("my.foo: ${bar.blah}", "bar.blah: hello").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()).isEqualTo("hello"); } @@ -166,18 +168,18 @@ class EnvironmentEndpointTests { ConfigurableEnvironment environment = emptyEnvironment(); TestPropertyValues.of("my.foo: ${bar.blah}").applyTo(environment); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); assertThat(propertySources(descriptor).get("test").getProperties().get("my.foo").getValue()) - .isEqualTo("${bar.blah}"); + .isEqualTo("${bar.blah}"); } @Test void propertyWithComplexTypeShouldNotFail() { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources() - .addFirst(singleKeyPropertySource("test", "foo", Collections.singletonMap("bar", "baz"))); + .addFirst(singleKeyPropertySource("test", "foo", Collections.singletonMap("bar", "baz"))); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); String value = (String) propertySources(descriptor).get("test").getProperties().get("foo").getValue(); assertThat(value).isEqualTo("Complex property type java.util.Collections$SingletonMap"); } @@ -192,7 +194,7 @@ class EnvironmentEndpointTests { map.put("biginteger", BigInteger.valueOf(200)); environment.getPropertySources().addFirst(new MapPropertySource("test", map)); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); Map properties = propertySources(descriptor).get("test").getProperties(); assertThat(properties.get("char").getValue()).isEqualTo('a'); assertThat(properties.get("integer").getValue()).isEqualTo(100); @@ -205,7 +207,7 @@ class EnvironmentEndpointTests { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources().addFirst(singleKeyPropertySource("test", "foo", new CharSequenceProperty())); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); String value = (String) propertySources(descriptor).get("test").getProperties().get("foo").getValue(); assertThat(value).isEqualTo("test value"); } @@ -228,10 +230,11 @@ class EnvironmentEndpointTests { private void testPropertyEntry(Show always, String bar, String another) { TestPropertyValues.of("my.foo=another").applyToSystemProperties(() -> { StandardEnvironment environment = new StandardEnvironment(); - TestPropertyValues.of("my.foo=bar", "my.foo2=bar2").applyTo(environment, TestPropertyValues.Type.MAP, - "test"); + TestPropertyValues.of("my.foo=bar", "my.foo2=bar2") + .applyTo(environment, TestPropertyValues.Type.MAP, "test"); EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), - always).environmentEntry("my.foo"); + always) + .environmentEntry("my.foo"); assertThat(descriptor).isNotNull(); assertThat(descriptor.getProperty()).isNotNull(); assertThat(descriptor.getProperty().getSource()).isEqualTo("test"); @@ -252,7 +255,8 @@ class EnvironmentEndpointTests { propertySource.setProperty("name", "test"); environment.getPropertySources().addFirst(propertySource); EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), - Show.ALWAYS).environmentEntry("name"); + Show.ALWAYS) + .environmentEntry("name"); PropertySourceEntryDescriptor entryDescriptor = propertySources(descriptor).get("mockProperties"); assertThat(entryDescriptor.getProperty().getOrigin()).isEqualTo("name"); assertThat(entryDescriptor.getProperty().getOriginParents()).containsExactly("spring", "boot"); @@ -263,7 +267,8 @@ class EnvironmentEndpointTests { ConfigurableEnvironment environment = emptyEnvironment(); environment.getPropertySources().addFirst(singleKeyPropertySource("test", "foo", "bar")); EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), - Show.ALWAYS).environmentEntry("does.not.exist"); + Show.ALWAYS) + .environmentEntry("does.not.exist"); assertThat(descriptor).isNotNull(); assertThat(descriptor.getProperty()).isNull(); Map sources = propertySources(descriptor); @@ -277,7 +282,7 @@ class EnvironmentEndpointTests { environment.getPropertySources().addFirst(singleKeyPropertySource("one", "a", "alpha")); environment.getPropertySources().addFirst(singleKeyPropertySource("two", "a", "apple")); EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS) - .environment(null); + .environment(null); Map sources = propertySources(descriptor); assertThat(sources.keySet()).containsExactly("two", "one"); assertThat(sources.get("one").getProperties().get("a").getValue()).isEqualTo("alpha"); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtensionTests.java index c8d0131455..febf1ee346 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -86,7 +86,7 @@ class EnvironmentEndpointWebExtensionTests { private void verifyPrefixed(SecurityContext securityContext, boolean showUnsanitized) { given(this.delegate.getEnvironmentEntryDescriptor("test", showUnsanitized)) - .willReturn(new EnvironmentEntryDescriptor(null, Collections.emptyList(), Collections.emptyList())); + .willReturn(new EnvironmentEntryDescriptor(null, Collections.emptyList(), Collections.emptyList())); this.webExtension.environmentEntry(securityContext, "test"); then(this.delegate).should().getEnvironmentEntryDescriptor("test", showUnsanitized); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java index 49b3e9f347..63fcb0e553 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,14 +47,28 @@ class EnvironmentEndpointWebIntegrationTests { @WebEndpointTest void home() { - this.client.get().uri("/actuator/env").exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources[?(@.name=='systemProperties')]").exists(); + this.client.get() + .uri("/actuator/env") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources[?(@.name=='systemProperties')]") + .exists(); } @WebEndpointTest void sub() { - this.client.get().uri("/actuator/env/foo").exchange().expectStatus().isOk().expectBody() - .jsonPath("property.source").isEqualTo("test").jsonPath("property.value").isEqualTo("bar"); + this.client.get() + .uri("/actuator/env/foo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("property.source") + .isEqualTo("test") + .jsonPath("property.value") + .isEqualTo("bar"); } @WebEndpointTest @@ -62,20 +76,35 @@ class EnvironmentEndpointWebIntegrationTests { Map map = new HashMap<>(); map.put("food", null); this.context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("null-value", map)); - this.client.get().uri("/actuator/env?pattern=foo.*").exchange().expectStatus().isOk().expectBody() - .jsonPath(forProperty("test", "foo")).isEqualTo("bar").jsonPath(forProperty("test", "fool")) - .isEqualTo("baz"); + this.client.get() + .uri("/actuator/env?pattern=foo.*") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath(forProperty("test", "foo")) + .isEqualTo("bar") + .jsonPath(forProperty("test", "fool")) + .isEqualTo("baz"); } @WebEndpointTest void nestedPathWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - this.context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("unresolved-placeholder", map)); - this.client.get().uri("/actuator/env/my.foo").exchange().expectStatus().isOk().expectBody() - .jsonPath("property.value").isEqualTo("${my.bar}").jsonPath(forPropertyEntry("unresolved-placeholder")) - .isEqualTo("${my.bar}"); + this.context.getEnvironment() + .getPropertySources() + .addFirst(new MapPropertySource("unresolved-placeholder", map)); + this.client.get() + .uri("/actuator/env/my.foo") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("property.value") + .isEqualTo("${my.bar}") + .jsonPath(forPropertyEntry("unresolved-placeholder")) + .isEqualTo("${my.bar}"); } @WebEndpointTest @@ -87,11 +116,17 @@ class EnvironmentEndpointWebIntegrationTests { void nestedPathMatchedByRegexWhenPlaceholderCannotBeResolvedShouldReturnUnresolvedProperty() { Map map = new HashMap<>(); map.put("my.foo", "${my.bar}"); - this.context.getEnvironment().getPropertySources() - .addFirst(new MapPropertySource("unresolved-placeholder", map)); - this.client.get().uri("/actuator/env?pattern=my.*").exchange().expectStatus().isOk().expectBody() - .jsonPath("propertySources[?(@.name=='unresolved-placeholder')].properties.['my.foo'].value") - .isEqualTo("${my.bar}"); + this.context.getEnvironment() + .getPropertySources() + .addFirst(new MapPropertySource("unresolved-placeholder", map)); + this.client.get() + .uri("/actuator/env?pattern=my.*") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("propertySources[?(@.name=='unresolved-placeholder')].properties.['my.foo'].value") + .isEqualTo("${my.bar}"); } private String forProperty(String source, String name) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java index 3a93665f6f..4a892135a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/flyway/FlywayEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,14 +39,18 @@ import static org.assertj.core.api.Assertions.assertThat; class FlywayEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class).withBean("endpoint", FlywayEndpoint.class); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withBean("endpoint", FlywayEndpoint.class); @Test void flywayReportIsProduced() { this.contextRunner.run((context) -> { - Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() - .getContexts().get(context.getId()).getFlywayBeans(); + Map flywayBeans = context.getBean(FlywayEndpoint.class) + .flywayBeans() + .getContexts() + .get(context.getId()) + .getFlywayBeans(); assertThat(flywayBeans).hasSize(1); assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(3); }); @@ -55,15 +59,19 @@ class FlywayEndpointTests { @Test void whenFlywayHasBeenBaselinedFlywayReportIsProduced() { this.contextRunner.withPropertyValues("spring.flyway.baseline-version=2") - .withBean(FlywayMigrationStrategy.class, () -> (flyway) -> { - flyway.baseline(); - flyway.migrate(); - }).run((context) -> { - Map flywayBeans = context.getBean(FlywayEndpoint.class).flywayBeans() - .getContexts().get(context.getId()).getFlywayBeans(); - assertThat(flywayBeans).hasSize(1); - assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(4); - }); + .withBean(FlywayMigrationStrategy.class, () -> (flyway) -> { + flyway.baseline(); + flyway.migrate(); + }) + .run((context) -> { + Map flywayBeans = context.getBean(FlywayEndpoint.class) + .flywayBeans() + .getContexts() + .get(context.getId()) + .getFlywayBeans(); + assertThat(flywayBeans).hasSize(1); + assertThat(flywayBeans.values().iterator().next().getMigrations()).hasSize(4); + }); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java index 053db98a3a..d478843988 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/hazelcast/HazelcastHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,14 +42,15 @@ class HazelcastHealthIndicatorTests { @Test void hazelcastUp() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withPropertyValues("spring.hazelcast.config=hazelcast.xml").run((context) -> { - HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); - Health health = new HazelcastHealthIndicator(hazelcast).health(); - assertThat(health.getStatus()).isEqualTo(Status.UP); - assertThat(health.getDetails()).containsOnlyKeys("name", "uuid").containsEntry("name", - "actuator-hazelcast"); - assertThat(health.getDetails().get("uuid")).asString().isNotEmpty(); - }); + .withPropertyValues("spring.hazelcast.config=hazelcast.xml") + .run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + Health health = new HazelcastHealthIndicator(hazelcast).health(); + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails()).containsOnlyKeys("name", "uuid") + .containsEntry("name", "actuator-hazelcast"); + assertThat(health.getDetails().get("uuid")).asString().isNotEmpty(); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java index 9be65afac3..2e2d77c4d7 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AbstractHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,8 @@ class AbstractHealthIndicatorTests { @Test void healthCheckWhenDownWithExceptionConfiguredLogsHealthCheckFailedMessage(CapturedOutput output) { Health heath = new TestHealthIndicator("Test message", - (builder) -> builder.down().withException(new IllegalStateException("Test exception"))).health(); + (builder) -> builder.down().withException(new IllegalStateException("Test exception"))) + .health(); assertThat(heath.getStatus()).isEqualTo(Status.DOWN); assertThat(output).contains("Test message").contains("Test exception"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java index a9d02b061b..5ddbb02444 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/AdditionalHealthEndpointPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -67,31 +67,31 @@ class AdditionalHealthEndpointPathTests { @Test void fromPathWithMultipleSegmentsShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:/my-path/my-sub-path")); + .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:/my-path/my-sub-path")); } @Test void fromPathWithMultipleSegmentsNotStartingWithSlashShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:my-path/my-sub-path")); + .isThrownBy(() -> AdditionalHealthEndpointPath.from("server:my-path/my-sub-path")); } @Test void pathsWithTheSameNamespaceAndValueAreEqual() { assertThat(AdditionalHealthEndpointPath.from("server:/my-path")) - .isEqualTo(AdditionalHealthEndpointPath.from("server:/my-path")); + .isEqualTo(AdditionalHealthEndpointPath.from("server:/my-path")); } @Test void pathsWithTheDifferentNamespaceAndSameValueAreNotEqual() { assertThat(AdditionalHealthEndpointPath.from("server:/my-path")) - .isNotEqualTo((AdditionalHealthEndpointPath.from("management:/my-path"))); + .isNotEqualTo((AdditionalHealthEndpointPath.from("management:/my-path"))); } @Test void pathsWithTheSameNamespaceAndValuesWithNoSlashAreEqual() { assertThat(AdditionalHealthEndpointPath.from("server:/my-path")) - .isEqualTo((AdditionalHealthEndpointPath.from("server:my-path"))); + .isEqualTo((AdditionalHealthEndpointPath.from("server:my-path"))); } @Test @@ -102,13 +102,13 @@ class AdditionalHealthEndpointPathTests { @Test void ofWithNullPathShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, null)); + .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, null)); } @Test void ofWithMultipleSegmentValueShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, "/my-path/my-subpath")); + .isThrownBy(() -> AdditionalHealthEndpointPath.of(WebServerNamespace.SERVER, "/my-path/my-subpath")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java index ecc87fdb34..1a2916ad08 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthContributorReactiveAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,14 +34,14 @@ class CompositeHealthContributorReactiveAdapterTests { @Test void createWhenDelegateIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new CompositeHealthContributorReactiveAdapter(null)) - .withMessage("Delegate must not be null"); + .withMessage("Delegate must not be null"); } @Test void iteratorWhenDelegateContainsHealthIndicatorAdaptsDelegate() { HealthIndicator indicator = () -> Health.up().withDetail("spring", "boot").build(); CompositeHealthContributor delegate = CompositeHealthContributor - .fromMap(Collections.singletonMap("test", indicator)); + .fromMap(Collections.singletonMap("test", indicator)); CompositeHealthContributorReactiveAdapter adapter = new CompositeHealthContributorReactiveAdapter(delegate); Iterator> iterator = adapter.iterator(); assertThat(iterator.hasNext()).isTrue(); @@ -57,9 +57,9 @@ class CompositeHealthContributorReactiveAdapterTests { void iteratorWhenDelegateContainsCompositeHealthContributorAdaptsDelegate() { HealthIndicator indicator = () -> Health.up().withDetail("spring", "boot").build(); CompositeHealthContributor composite = CompositeHealthContributor - .fromMap(Collections.singletonMap("test1", indicator)); + .fromMap(Collections.singletonMap("test1", indicator)); CompositeHealthContributor delegate = CompositeHealthContributor - .fromMap(Collections.singletonMap("test2", composite)); + .fromMap(Collections.singletonMap("test2", composite)); CompositeHealthContributorReactiveAdapter adapter = new CompositeHealthContributorReactiveAdapter(delegate); Iterator> iterator = adapter.iterator(); assertThat(iterator.hasNext()).isTrue(); @@ -67,7 +67,7 @@ class CompositeHealthContributorReactiveAdapterTests { assertThat(adapted.getName()).isEqualTo("test2"); assertThat(adapted.getContributor()).isInstanceOf(CompositeReactiveHealthContributor.class); ReactiveHealthContributor nested = ((CompositeReactiveHealthContributor) adapted.getContributor()) - .getContributor("test1"); + .getContributor("test1"); Health health = ((ReactiveHealthIndicator) nested).getHealth(true).block(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsEntry("spring", "boot"); @@ -77,7 +77,7 @@ class CompositeHealthContributorReactiveAdapterTests { void getContributorAdaptsDelegate() { HealthIndicator indicator = () -> Health.up().withDetail("spring", "boot").build(); CompositeHealthContributor delegate = CompositeHealthContributor - .fromMap(Collections.singletonMap("test", indicator)); + .fromMap(Collections.singletonMap("test", indicator)); CompositeHealthContributorReactiveAdapter adapter = new CompositeHealthContributorReactiveAdapter(delegate); ReactiveHealthContributor adapted = adapter.getContributor("test"); Health health = ((ReactiveHealthIndicator) adapted).getHealth(true).block(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java index bb2b3d192b..0d8d51112e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/CompositeHealthTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,8 @@ class CompositeHealthTests { @Test void createWhenStatusIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new CompositeHealth(ApiVersion.V3, null, Collections.emptyMap())) - .withMessage("Status must not be null"); + .isThrownBy(() -> new CompositeHealth(ApiVersion.V3, null, Collections.emptyMap())) + .withMessage("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java index 00e1e6b195..6316adfe62 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultContributorRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -53,14 +53,14 @@ abstract class DefaultContributorRegistryTests { @Test void createWhenContributorsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultContributorRegistry<>(null)) - .withMessage("Contributors must not be null"); + .withMessage("Contributors must not be null"); } @Test void createWhenNameFactoryIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DefaultContributorRegistry<>(Collections.emptyMap(), null)) - .withMessage("NameFactory must not be null"); + .isThrownBy(() -> new DefaultContributorRegistry<>(Collections.emptyMap(), null)) + .withMessage("NameFactory must not be null"); } @Test @@ -80,13 +80,13 @@ abstract class DefaultContributorRegistryTests { @Test void registerContributorWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.registry.registerContributor(null, this.one)) - .withMessage("Name must not be null"); + .withMessage("Name must not be null"); } @Test void registerContributorWhenContributorIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.registry.registerContributor("one", null)) - .withMessage("Contributor must not be null"); + .withMessage("Contributor must not be null"); } @Test @@ -102,7 +102,7 @@ abstract class DefaultContributorRegistryTests { void registerContributorWhenNameAlreadyUsedThrowsException() { this.registry.registerContributor("one", this.one); assertThatIllegalStateException().isThrownBy(() -> this.registry.registerContributor("one", this.two)) - .withMessageContaining("A contributor named \"one\" has already been registered"); + .withMessageContaining("A contributor named \"one\" has already been registered"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java index e74194bf83..8079461177 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthContributorNameFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -47,9 +47,9 @@ class HealthContributorNameFactoryTests { @Test void applyWhenNameContainsSuffixReturnsName() { assertThat(HealthContributorNameFactory.INSTANCE.apply("testHealthIndicatorTest")) - .isEqualTo("testHealthIndicatorTest"); + .isEqualTo("testHealthIndicatorTest"); assertThat(HealthContributorNameFactory.INSTANCE.apply("testHealthContributorTest")) - .isEqualTo("testHealthContributorTest"); + .isEqualTo("testHealthContributorTest"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java index ba176cb310..a9e8058a56 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointGroupsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,14 +34,14 @@ class HealthEndpointGroupsTests { @Test void ofWhenPrimaryIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> HealthEndpointGroups.of(null, Collections.emptyMap())) - .withMessage("Primary must not be null"); + .withMessage("Primary must not be null"); } @Test void ofWhenAdditionalIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> HealthEndpointGroups.of(mock(HealthEndpointGroup.class), null)) - .withMessage("Additional must not be null"); + .isThrownBy(() -> HealthEndpointGroups.of(mock(HealthEndpointGroup.class), null)) + .withMessage("Additional must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java index fabbd93274..8af31ccdbf 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointSupportTests.java @@ -64,13 +64,13 @@ abstract class HealthEndpointSupportTests, @Test void createWhenRegistryIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> create(null, this.groups)) - .withMessage("Registry must not be null"); + .withMessage("Registry must not be null"); } @Test void createWhenGroupsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> create(this.registry, null)) - .withMessage("Groups must not be null"); + .withMessage("Groups must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java index 02d20a5955..167ad6a0bc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,8 @@ class HealthEndpointTests extends void healthWithNoContributorReturnsUp() { assertThat(this.registry).isEmpty(); HealthComponent health = create(this.registry, - HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())).health(); + HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())) + .health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health).isInstanceOf(Health.class); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionRuntimeHintsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionRuntimeHintsTests.java index 9415240096..020f6b522f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,9 +39,10 @@ class HealthEndpointWebExtensionRuntimeHintsTests { new HealthEndpointWebExtensionRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); Set> bindingTypes = Set.of(Health.class, SystemHealth.class, CompositeHealth.class); for (Class bindingType : bindingTypes) { - assertThat(RuntimeHintsPredicates.reflection().onType(bindingType) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(bindingType) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java index 56f44169ce..f340799faa 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ class HealthEndpointWebExtensionTests extends assertThat(this.registry).isEmpty(); WebEndpointResponse response = create(this.registry, HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())) - .health(ApiVersion.LATEST, WebServerNamespace.SERVER, SecurityContext.NONE); + .health(ApiVersion.LATEST, WebServerNamespace.SERVER, SecurityContext.NONE); assertThat(response.getStatus()).isEqualTo(200); HealthComponent health = response.getBody(); assertThat(health.getStatus()).isEqualTo(Status.UP); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java index 4db81a4971..12a7d32717 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,32 +51,70 @@ class HealthEndpointWebIntegrationTests { @WebEndpointTest void whenHealthIsUp200ResponseIsReturned(WebTestClient client) { - client.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().jsonPath("status").isEqualTo("UP").jsonPath("components.alpha.status").isEqualTo("UP") - .jsonPath("components.bravo.status").isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest void whenHealthIsUpAndAcceptsV3Request200ResponseIsReturned(WebTestClient client) { - client.get().uri("/actuator/health").headers((headers) -> headers.set(HttpHeaders.ACCEPT, V3_JSON)).exchange() - .expectStatus().isOk().expectBody().jsonPath("status").isEqualTo("UP") - .jsonPath("components.alpha.status").isEqualTo("UP").jsonPath("components.bravo.status") - .isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .headers((headers) -> headers.set(HttpHeaders.ACCEPT, V3_JSON)) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest void whenHealthIsUpAndAcceptsAllRequest200ResponseIsReturned(WebTestClient client) { - client.get().uri("/actuator/health").headers((headers) -> headers.set(HttpHeaders.ACCEPT, "*/*")).exchange() - .expectStatus().isOk().expectBody().jsonPath("status").isEqualTo("UP") - .jsonPath("components.alpha.status").isEqualTo("UP").jsonPath("components.bravo.status") - .isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .headers((headers) -> headers.set(HttpHeaders.ACCEPT, "*/*")) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest void whenHealthIsUpAndV2Request200ResponseIsReturnedInV2Format(WebTestClient client) { - client.get().uri("/actuator/health").headers((headers) -> headers.set(HttpHeaders.ACCEPT, V2_JSON)).exchange() - .expectStatus().isOk().expectBody().jsonPath("status").isEqualTo("UP").jsonPath("details.alpha.status") - .isEqualTo("UP").jsonPath("details.bravo.status").isEqualTo("UP"); + client.get() + .uri("/actuator/health") + .headers((headers) -> headers.set(HttpHeaders.ACCEPT, V2_JSON)) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("details.alpha.status") + .isEqualTo("UP") + .jsonPath("details.bravo.status") + .isEqualTo("UP"); } @WebEndpointTest @@ -84,10 +122,21 @@ class HealthEndpointWebIntegrationTests { HealthIndicator healthIndicator = () -> Health.down().build(); ReactiveHealthIndicator reactiveHealthIndicator = () -> Mono.just(Health.down().build()); withHealthContributor(context, "charlie", healthIndicator, reactiveHealthIndicator, - () -> client.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN") - .jsonPath("components.alpha.status").isEqualTo("UP").jsonPath("components.bravo.status") - .isEqualTo("UP").jsonPath("components.charlie.status").isEqualTo("DOWN")); + () -> client.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody() + .jsonPath("status") + .isEqualTo("DOWN") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .isEqualTo("UP") + .jsonPath("components.charlie.status") + .isEqualTo("DOWN")); } @WebEndpointTest @@ -95,23 +144,35 @@ class HealthEndpointWebIntegrationTests { HealthIndicator healthIndicator = () -> Health.down().build(); ReactiveHealthIndicator reactiveHealthIndicator = () -> Mono.just(Health.down().build()); withHealthContributor(context, "charlie", healthIndicator, reactiveHealthIndicator, - () -> client.get().uri("/actuator/health/charlie").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status") - .isEqualTo("DOWN")); + () -> client.get() + .uri("/actuator/health/charlie") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody() + .jsonPath("status") + .isEqualTo("DOWN")); } @WebEndpointTest void whenComponentInstanceHealthIsDown503ResponseIsReturned(ApplicationContext context, WebTestClient client) { HealthIndicator healthIndicator = () -> Health.down().build(); CompositeHealthContributor composite = CompositeHealthContributor - .fromMap(Collections.singletonMap("one", healthIndicator)); + .fromMap(Collections.singletonMap("one", healthIndicator)); ReactiveHealthIndicator reactiveHealthIndicator = () -> Mono.just(Health.down().build()); CompositeReactiveHealthContributor reactiveComposite = CompositeReactiveHealthContributor - .fromMap(Collections.singletonMap("one", reactiveHealthIndicator)); + .fromMap(Collections.singletonMap("one", reactiveHealthIndicator)); withHealthContributor(context, "charlie", composite, reactiveComposite, - () -> client.get().uri("/actuator/health/charlie/one").accept(MediaType.APPLICATION_JSON).exchange() - .expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status") - .isEqualTo("DOWN")); + () -> client.get() + .uri("/actuator/health/charlie/one") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE) + .expectBody() + .jsonPath("status") + .isEqualTo("DOWN")); } private void withHealthContributor(ApplicationContext context, String name, HealthContributor healthContributor, @@ -154,9 +215,19 @@ class HealthEndpointWebIntegrationTests { ReactiveHealthContributor reactiveBravo = (reactiveHealthContributorRegistry != null) ? reactiveHealthContributorRegistry.unregisterContributor(name) : null; try { - client.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().jsonPath("status").isEqualTo("UP").jsonPath("components.alpha.status").isEqualTo("UP") - .jsonPath("components.bravo.status").doesNotExist(); + client.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("status") + .isEqualTo("UP") + .jsonPath("components.alpha.status") + .isEqualTo("UP") + .jsonPath("components.bravo.status") + .doesNotExist(); } finally { healthContributorRegistry.registerContributor(name, bravo); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java index 1506c751f9..bfb32465cb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthIndicatorReactiveAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,8 @@ class HealthIndicatorReactiveAdapterTests { void delegateRunsOnTheElasticScheduler() { String currentThread = Thread.currentThread().getName(); HealthIndicator delegate = () -> Health - .status(Thread.currentThread().getName().equals(currentThread) ? Status.DOWN : Status.UP).build(); + .status(Thread.currentThread().getName().equals(currentThread) ? Status.DOWN : Status.UP) + .build(); HealthIndicatorReactiveAdapter adapter = new HealthIndicatorReactiveAdapter(delegate); StepVerifier.create(adapter.health()).expectNext(Health.status(Status.UP).build()).verifyComplete(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index d7ef1d0a6b..5f0aba8421 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -40,7 +40,7 @@ class HealthTests { @Test void statusMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Health.Builder(null, null)) - .withMessageContaining("Status must not be null"); + .withMessageContaining("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java index f357eccc53..a26c1e460e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -38,13 +38,13 @@ class NamedContributorTests { @Test void ofWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> NamedContributor.of(null, "two")) - .withMessage("Name must not be null"); + .withMessage("Name must not be null"); } @Test void ofWhenContributorIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> NamedContributor.of("one", null)) - .withMessage("Contributor must not be null"); + .withMessage("Contributor must not be null"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java index c33214ef1d..9794a32b09 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/NamedContributorsMapAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,39 +39,39 @@ class NamedContributorsMapAdapterTests { @Test void createWhenMapIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(null, Function.identity())) - .withMessage("Map must not be null"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(null, Function.identity())) + .withMessage("Map must not be null"); } @Test void createWhenValueAdapterIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.emptyMap(), null)) - .withMessage("ValueAdapter must not be null"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.emptyMap(), null)) + .withMessage("ValueAdapter must not be null"); } @Test void createWhenMapContainsNullValueThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test", null), - Function.identity())) - .withMessage("Map must not contain null values"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test", null), + Function.identity())) + .withMessage("Map must not contain null values"); } @Test void createWhenMapContainsNullKeyThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap(null, "test"), - Function.identity())) - .withMessage("Map must not contain null keys"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap(null, "test"), + Function.identity())) + .withMessage("Map must not contain null keys"); } @Test void createWhenMapContainsKeyWithSlashThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test/key", "test"), - Function.identity())) - .withMessage("Map keys must not contain a '/'"); + .isThrownBy(() -> new TestNamedContributorsMapAdapter<>(Collections.singletonMap("test/key", "test"), + Function.identity())) + .withMessage("Map keys must not contain a '/'"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java index 201d79e0ac..2acf5a61f3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class ReactiveHealthContributorTests { @Test void adaptWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ReactiveHealthContributor.adapt(null)) - .withMessage("HealthContributor must not be null"); + .withMessage("HealthContributor must not be null"); } @Test @@ -50,7 +50,7 @@ class ReactiveHealthContributorTests { void adaptWhenCompositeHealthContributorReturnsCompositeHealthContributorReactiveAdapter() { HealthIndicator indicator = () -> Health.outOfService().build(); CompositeHealthContributor contributor = CompositeHealthContributor - .fromMap(Collections.singletonMap("a", indicator)); + .fromMap(Collections.singletonMap("a", indicator)); ReactiveHealthContributor adapted = ReactiveHealthContributor.adapt(contributor); assertThat(adapted).isInstanceOf(CompositeHealthContributorReactiveAdapter.class); ReactiveHealthContributor contained = ((CompositeReactiveHealthContributor) adapted).getContributor("a"); @@ -60,8 +60,8 @@ class ReactiveHealthContributorTests { @Test void adaptWhenUnknownThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ReactiveHealthContributor.adapt(mock(HealthContributor.class))) - .withMessage("Unknown HealthContributor type"); + .isThrownBy(() -> ReactiveHealthContributor.adapt(mock(HealthContributor.class))) + .withMessage("Unknown HealthContributor type"); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java index 92c7e00665..60a5958109 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,8 @@ class ReactiveHealthEndpointWebExtensionTests extends void healthReturnsSystemHealth() { this.registry.registerContributor("test", createContributor(this.up)); WebEndpointResponse response = create(this.registry, this.groups) - .health(ApiVersion.LATEST, null, SecurityContext.NONE).block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE) + .block(); HealthComponent health = response.getBody(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health).isInstanceOf(SystemHealth.class); @@ -56,7 +57,8 @@ class ReactiveHealthEndpointWebExtensionTests extends assertThat(this.registry).isEmpty(); WebEndpointResponse response = create(this.registry, HealthEndpointGroups.of(mock(HealthEndpointGroup.class), Collections.emptyMap())) - .health(ApiVersion.LATEST, null, SecurityContext.NONE).block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE) + .block(); assertThat(response.getStatus()).isEqualTo(200); HealthComponent health = response.getBody(); assertThat(health.getStatus()).isEqualTo(Status.UP); @@ -67,7 +69,8 @@ class ReactiveHealthEndpointWebExtensionTests extends void healthWhenPathDoesNotExistReturnsHttp404() { this.registry.registerContributor("test", createContributor(this.up)); WebEndpointResponse response = create(this.registry, this.groups) - .health(ApiVersion.LATEST, null, SecurityContext.NONE, "missing").block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE, "missing") + .block(); assertThat(response.getBody()).isNull(); assertThat(response.getStatus()).isEqualTo(404); } @@ -76,7 +79,8 @@ class ReactiveHealthEndpointWebExtensionTests extends void healthWhenPathExistsReturnsHealth() { this.registry.registerContributor("test", createContributor(this.up)); WebEndpointResponse response = create(this.registry, this.groups) - .health(ApiVersion.LATEST, null, SecurityContext.NONE, "test").block(); + .health(ApiVersion.LATEST, null, SecurityContext.NONE, "test") + .block(); assertThat(response.getBody()).isEqualTo(this.up); assertThat(response.getStatus()).isEqualTo(200); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java index aaf3fd1281..f9f715514f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorImplementationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -39,23 +39,25 @@ class ReactiveHealthIndicatorImplementationTests { @Test void healthUp(CapturedOutput output) { StepVerifier.create(new SimpleReactiveHealthIndicator().health()) - .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.up().build())).verifyComplete(); + .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.up().build())) + .verifyComplete(); assertThat(output).doesNotContain("Health check failed for simple"); } @Test void healthDownWithCustomErrorMessage(CapturedOutput output) { - StepVerifier.create(new CustomErrorMessageReactiveHealthIndicator().health()).consumeNextWith( - (health) -> assertThat(health).isEqualTo(Health.down(new UnsupportedOperationException()).build())) - .verifyComplete(); + StepVerifier.create(new CustomErrorMessageReactiveHealthIndicator().health()) + .consumeNextWith( + (health) -> assertThat(health).isEqualTo(Health.down(new UnsupportedOperationException()).build())) + .verifyComplete(); assertThat(output).contains("Health check failed for custom"); } @Test void healthDownWithCustomErrorMessageFunction(CapturedOutput output) { StepVerifier.create(new CustomErrorMessageFunctionReactiveHealthIndicator().health()) - .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.down(new RuntimeException()).build())) - .verifyComplete(); + .consumeNextWith((health) -> assertThat(health).isEqualTo(Health.down(new RuntimeException()).build())) + .verifyComplete(); assertThat(output).contains("Health check failed with RuntimeException"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java index 0cc7564b01..7aac9e40eb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/SimpleHttpCodeStatusMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class SimpleHttpCodeStatusMapperTests { assertThat(mapper.getStatusCode(Status.UP)).isEqualTo(WebEndpointResponse.STATUS_OK); assertThat(mapper.getStatusCode(Status.DOWN)).isEqualTo(WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); assertThat(mapper.getStatusCode(Status.OUT_OF_SERVICE)) - .isEqualTo(WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); + .isEqualTo(WebEndpointResponse.STATUS_SERVICE_UNAVAILABLE); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java index 32696b0c97..f9284dd433 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/StatusTests.java @@ -32,13 +32,13 @@ class StatusTests { @Test void createWhenCodeIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Status(null, "")) - .withMessage("Code must not be null"); + .withMessage("Code must not be null"); } @Test void createWhenDescriptionIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Status("code", null)) - .withMessage("Description must not be null"); + .withMessage("Description must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/BuildInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/BuildInfoContributorTests.java index 5c3a7e195e..a05dbada3a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/BuildInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/BuildInfoContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,9 +37,10 @@ class BuildInfoContributorTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new BuildInfoContributorRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(BuildProperties.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(BuildProperties.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java index f5f72a14a5..0bf002bdef 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/GitInfoContributorTests.java @@ -88,9 +88,10 @@ class GitInfoContributorTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new GitInfoContributorRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(GitProperties.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(GitProperties.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java index f3d83dbd93..3f5463fbdf 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,10 +39,21 @@ class InfoEndpointWebIntegrationTests { @WebEndpointTest void info(WebTestClient client) { - client.get().uri("/actuator/info").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().jsonPath("beanName1.key11").isEqualTo("value11").jsonPath("beanName1.key12") - .isEqualTo("value12").jsonPath("beanName2.key21").isEqualTo("value21").jsonPath("beanName2.key22") - .isEqualTo("value22"); + client.get() + .uri("/actuator/info") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("beanName1.key11") + .isEqualTo("value11") + .jsonPath("beanName1.key12") + .isEqualTo("value12") + .jsonPath("beanName2.key21") + .isEqualTo("value21") + .jsonPath("beanName2.key22") + .isEqualTo("value22"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/JavaInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/JavaInfoContributorTests.java index ec4747d998..154d37f209 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/JavaInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/JavaInfoContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,9 +47,10 @@ class JavaInfoContributorTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new JavaInfoContributorRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(JavaInfo.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(JavaInfo.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/OsInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/OsInfoContributorTests.java index ea85185dc6..d7f292e8f3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/OsInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/OsInfoContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,9 +47,10 @@ class OsInfoContributorTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new OsInfoContributorRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(OsInfo.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(OsInfo.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java index 76593213de..6ee57ee54b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/integration/IntegrationGraphEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,16 +34,29 @@ class IntegrationGraphEndpointWebIntegrationTests { @WebEndpointTest void graph(WebTestClient client) { - client.get().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody().jsonPath("contentDescriptor.providerVersion").isNotEmpty() - .jsonPath("contentDescriptor.providerFormatVersion").isEqualTo(1.2f) - .jsonPath("contentDescriptor.provider").isEqualTo("spring-integration"); + client.get() + .uri("/actuator/integrationgraph") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("contentDescriptor.providerVersion") + .isNotEmpty() + .jsonPath("contentDescriptor.providerFormatVersion") + .isEqualTo(1.2f) + .jsonPath("contentDescriptor.provider") + .isEqualTo("spring-integration"); } @WebEndpointTest void rebuild(WebTestClient client) { - client.post().uri("/actuator/integrationgraph").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isNoContent(); + client.post() + .uri("/actuator/integrationgraph") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isNoContent(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java index b2cb9921ea..11f2547620 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/ldap/LdapHealthIndicatorTests.java @@ -54,7 +54,7 @@ class LdapHealthIndicatorTests { void ldapIsDown() { LdapTemplate ldapTemplate = mock(LdapTemplate.class); given(ldapTemplate.executeReadOnly((ContextExecutor) any())) - .willThrow(new CommunicationException(new javax.naming.CommunicationException("Connection failed"))); + .willThrow(new CommunicationException(new javax.naming.CommunicationException("Connection failed"))); LdapHealthIndicator healthIndicator = new LdapHealthIndicator(ldapTemplate); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java index 0c640c7f45..c0f6900f1a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/liquibase/LiquibaseEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,15 +53,17 @@ import static org.assertj.core.api.Assertions.assertThat; class LiquibaseEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void liquibaseReportIsReturned() { this.contextRunner.withUserConfiguration(Config.class).run((context) -> { Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); }); } @@ -71,7 +73,10 @@ class LiquibaseEndpointTests { this.contextRunner.withUserConfiguration().run((parent) -> { this.contextRunner.withUserConfiguration(Config.class).withParent(parent).run((context) -> { Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(parent.getId()).getLiquibaseBeans(); + .liquibaseBeans() + .getContexts() + .get(parent.getId()) + .getLiquibaseBeans(); assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); }); }); @@ -80,23 +85,30 @@ class LiquibaseEndpointTests { @Test void invokeWithCustomSchema() { this.contextRunner.withUserConfiguration(Config.class, DataSourceWithSchemaConfiguration.class) - .withPropertyValues("spring.liquibase.default-schema=CUSTOMSCHEMA").run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); - }); + .withPropertyValues("spring.liquibase.default-schema=CUSTOMSCHEMA") + .run((context) -> { + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); + }); } @Test void invokeWithCustomTables() { this.contextRunner.withUserConfiguration(Config.class) - .withPropertyValues("spring.liquibase.database-change-log-lock-table=liquibase_database_changelog_lock", - "spring.liquibase.database-change-log-table=liquibase_database_changelog") - .run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); - }); + .withPropertyValues("spring.liquibase.database-change-log-lock-table=liquibase_database_changelog_lock", + "spring.liquibase.database-change-log-table=liquibase_database_changelog") + .run((context) -> { + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); + }); } @Test @@ -112,16 +124,19 @@ class LiquibaseEndpointTests { @Test void whenMultipleLiquibaseBeansArePresentChangeSetsAreCorrectlyReportedForEachBean() { this.contextRunner.withUserConfiguration(Config.class, MultipleDataSourceLiquibaseConfiguration.class) - .run((context) -> { - Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) - .liquibaseBeans().getContexts().get(context.getId()).getLiquibaseBeans(); - assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); - assertThat(liquibaseBeans.get("liquibase").getChangeSets().get(0).getChangeLog()) - .isEqualTo("db/changelog/db.changelog-master.yaml"); - assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets()).hasSize(1); - assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets().get(0).getChangeLog()) - .isEqualTo("db/changelog/db.changelog-master-backup.yaml"); - }); + .run((context) -> { + Map liquibaseBeans = context.getBean(LiquibaseEndpoint.class) + .liquibaseBeans() + .getContexts() + .get(context.getId()) + .getLiquibaseBeans(); + assertThat(liquibaseBeans.get("liquibase").getChangeSets()).hasSize(1); + assertThat(liquibaseBeans.get("liquibase").getChangeSets().get(0).getChangeLog()) + .isEqualTo("db/changelog/db.changelog-master.yaml"); + assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets()).hasSize(1); + assertThat(liquibaseBeans.get("liquibaseBackup").getChangeSets().get(0).getChangeLog()) + .isEqualTo("db/changelog/db.changelog-master-backup.yaml"); + }); } private boolean getAutoCommit(DataSource dataSource) throws SQLException { @@ -146,8 +161,9 @@ class LiquibaseEndpointTests { @Bean DataSource dataSource() { DataSource dataSource = new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()) - .setName(UUID.randomUUID().toString()).build(); + .setType(EmbeddedDatabaseConnection.get(getClass().getClassLoader()).getType()) + .setName(UUID.randomUUID().toString()) + .build(); DatabaseInitializationSettings settings = new DatabaseInitializationSettings(); settings.setSchemaLocations(Arrays.asList("classpath:/db/create-custom-schema.sql")); DataSourceScriptDatabaseInitializer initializer = new DataSourceScriptDatabaseInitializer(dataSource, @@ -183,7 +199,8 @@ class LiquibaseEndpointTests { private DataSource createEmbeddedDatabase() { return new EmbeddedDatabaseBuilder().generateUniqueName(true) - .setType(EmbeddedDatabaseConnection.HSQLDB.getType()).build(); + .setType(EmbeddedDatabaseConnection.HSQLDB.getType()) + .build(); } private SpringLiquibase createSpringLiquibase(String changeLog, DataSource dataSource) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java index b7566eeace..5f1248f7ff 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LogFileWebEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -56,14 +56,29 @@ class LogFileWebEndpointWebIntegrationTests { @WebEndpointTest void getRequestProducesResponseWithLogFile() { - this.client.get().uri("/actuator/logfile").exchange().expectStatus().isOk().expectHeader() - .contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); + this.client.get() + .uri("/actuator/logfile") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType("text/plain; charset=UTF-8") + .expectBody(String.class) + .isEqualTo("--TEST--"); } @WebEndpointTest void getRequestThatAcceptsTextPlainProducesResponseWithLogFile() { - this.client.get().uri("/actuator/logfile").accept(MediaType.TEXT_PLAIN).exchange().expectStatus().isOk() - .expectHeader().contentType("text/plain; charset=UTF-8").expectBody(String.class).isEqualTo("--TEST--"); + this.client.get() + .uri("/actuator/logfile") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType("text/plain; charset=UTF-8") + .expectBody(String.class) + .isEqualTo("--TEST--"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java index 820cc72f82..966873930d 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class LoggersEndpointTests { @Test void loggersShouldReturnLoggerConfigurationsWithNoLoggerGroups() { given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); LoggersDescriptor result = new LoggersEndpoint(this.loggingSystem, new LoggerGroups()).loggers(); Map loggers = result.getLoggers(); @@ -85,7 +85,7 @@ class LoggersEndpointTests { @Test void loggersShouldReturnLoggerConfigurationsWithLoggerGroups() { given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); given(this.loggingSystem.getSupportedLogLevels()).willReturn(EnumSet.allOf(LogLevel.class)); LoggersDescriptor result = new LoggersEndpoint(this.loggingSystem, this.loggerGroups).loggers(); Map loggerGroups = result.getGroups(); @@ -105,9 +105,10 @@ class LoggersEndpointTests { @Test void loggerLevelsWhenNameSpecifiedShouldReturnLevels() { given(this.loggingSystem.getLoggerConfiguration("ROOT")) - .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); + .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); SingleLoggerLevelsDescriptor levels = (SingleLoggerLevelsDescriptor) new LoggersEndpoint(this.loggingSystem, - this.loggerGroups).loggerLevels("ROOT"); + this.loggerGroups) + .loggerLevels("ROOT"); assertThat(levels.getConfiguredLevel()).isNull(); assertThat(levels.getEffectiveLevel()).isEqualTo("DEBUG"); } @@ -115,7 +116,8 @@ class LoggersEndpointTests { @Test void groupNameSpecifiedShouldReturnConfiguredLevelAndMembers() { GroupLoggerLevelsDescriptor levels = (GroupLoggerLevelsDescriptor) new LoggersEndpoint(this.loggingSystem, - this.loggerGroups).loggerLevels("test"); + this.loggerGroups) + .loggerLevels("test"); assertThat(levels.getConfiguredLevel()).isEqualTo("DEBUG"); assertThat(levels.getMembers()).isEqualTo(Collections.singletonList("test.member")); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java index f075cec94c..ad83eb790f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/logging/LoggersEndpointWebIntegrationTests.java @@ -84,24 +84,48 @@ class LoggersEndpointWebIntegrationTests { void getLoggerShouldReturnAllLoggerConfigurationsWithLoggerGroups() { setLogLevelToDebug("test"); given(this.loggingSystem.getLoggerConfigurations()) - .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); - this.client.get().uri("/actuator/loggers").exchange().expectStatus().isOk().expectBody().jsonPath("$.length()") - .isEqualTo(3).jsonPath("levels") - .isEqualTo(jsonArrayOf("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE")) - .jsonPath("loggers.length()").isEqualTo(1).jsonPath("loggers.ROOT.length()").isEqualTo(2) - .jsonPath("loggers.ROOT.configuredLevel").isEqualTo(null).jsonPath("loggers.ROOT.effectiveLevel") - .isEqualTo("DEBUG").jsonPath("groups.length()").isEqualTo(2).jsonPath("groups.test.configuredLevel") - .isEqualTo("DEBUG"); + .willReturn(Collections.singletonList(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG))); + this.client.get() + .uri("/actuator/loggers") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(3) + .jsonPath("levels") + .isEqualTo(jsonArrayOf("OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE")) + .jsonPath("loggers.length()") + .isEqualTo(1) + .jsonPath("loggers.ROOT.length()") + .isEqualTo(2) + .jsonPath("loggers.ROOT.configuredLevel") + .isEqualTo(null) + .jsonPath("loggers.ROOT.effectiveLevel") + .isEqualTo("DEBUG") + .jsonPath("groups.length()") + .isEqualTo(2) + .jsonPath("groups.test.configuredLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest void getLoggerShouldReturnLogLevels() { setLogLevelToDebug("test"); given(this.loggingSystem.getLoggerConfiguration("ROOT")) - .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); - this.client.get().uri("/actuator/loggers/ROOT").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null) - .jsonPath("effectiveLevel").isEqualTo("DEBUG"); + .willReturn(new LoggerConfiguration("ROOT", null, LogLevel.DEBUG)); + this.client.get() + .uri("/actuator/loggers/ROOT") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("configuredLevel") + .isEqualTo(null) + .jsonPath("effectiveLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest @@ -112,88 +136,140 @@ class LoggersEndpointWebIntegrationTests { @WebEndpointTest void getLoggerGroupShouldReturnConfiguredLogLevelAndMembers() { setLogLevelToDebug("test"); - this.client.get().uri("actuator/loggers/test").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("members") - .value(IsIterableContainingInAnyOrder.containsInAnyOrder("test.member1", "test.member2")) - .jsonPath("configuredLevel").isEqualTo("DEBUG"); + this.client.get() + .uri("actuator/loggers/test") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("members") + .value(IsIterableContainingInAnyOrder.containsInAnyOrder("test.member1", "test.member2")) + .jsonPath("configuredLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest void setLoggerUsingApplicationJsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG); } @WebEndpointTest void setLoggerUsingActuatorV2JsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V2_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V2_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG); } @WebEndpointTest void setLoggerUsingActuatorV3JsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", LogLevel.DEBUG); } @WebEndpointTest void setLoggerGroupUsingActuatorV2JsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V2_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.parseMediaType(V2_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG); } @WebEndpointTest void setLoggerGroupUsingApplicationJsonShouldSetLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.APPLICATION_JSON) - .bodyValue(Collections.singletonMap("configuredLevel", "debug")).exchange().expectStatus() - .isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(Collections.singletonMap("configuredLevel", "debug")) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", LogLevel.DEBUG); then(this.loggingSystem).should().setLogLevel("test.member2", LogLevel.DEBUG); } @WebEndpointTest void setLoggerOrLoggerGroupWithWrongLogLevelResultInBadRequestResponse() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.APPLICATION_JSON) - .bodyValue(Collections.singletonMap("configuredLevel", "other")).exchange().expectStatus() - .isBadRequest(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue(Collections.singletonMap("configuredLevel", "other")) + .exchange() + .expectStatus() + .isBadRequest(); then(this.loggingSystem).shouldHaveNoInteractions(); } @WebEndpointTest void setLoggerWithNullLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", null)) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", null); } @WebEndpointTest void setLoggerWithNoLogLevel() { - this.client.post().uri("/actuator/loggers/ROOT").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/ROOT") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.emptyMap()) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("ROOT", null); } @WebEndpointTest void setLoggerGroupWithNullLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.singletonMap("configuredLevel", null)).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.singletonMap("configuredLevel", null)) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", null); then(this.loggingSystem).should().setLogLevel("test.member2", null); } @WebEndpointTest void setLoggerGroupWithNoLogLevel() { - this.client.post().uri("/actuator/loggers/test").contentType(MediaType.parseMediaType(V3_JSON)) - .bodyValue(Collections.emptyMap()).exchange().expectStatus().isNoContent(); + this.client.post() + .uri("/actuator/loggers/test") + .contentType(MediaType.parseMediaType(V3_JSON)) + .bodyValue(Collections.emptyMap()) + .exchange() + .expectStatus() + .isNoContent(); then(this.loggingSystem).should().setLogLevel("test.member1", null); then(this.loggingSystem).should().setLogLevel("test.member2", null); } @@ -201,18 +277,36 @@ class LoggersEndpointWebIntegrationTests { @WebEndpointTest void logLevelForLoggerWithNameThatCouldBeMistakenForAPathExtension() { given(this.loggingSystem.getLoggerConfiguration("com.png")) - .willReturn(new LoggerConfiguration("com.png", null, LogLevel.DEBUG)); - this.client.get().uri("/actuator/loggers/com.png").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo(null) - .jsonPath("effectiveLevel").isEqualTo("DEBUG"); + .willReturn(new LoggerConfiguration("com.png", null, LogLevel.DEBUG)); + this.client.get() + .uri("/actuator/loggers/com.png") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("configuredLevel") + .isEqualTo(null) + .jsonPath("effectiveLevel") + .isEqualTo("DEBUG"); } @WebEndpointTest void logLevelForLoggerGroupWithNameThatCouldBeMistakenForAPathExtension() { setLogLevelToDebug("group.png"); - this.client.get().uri("/actuator/loggers/group.png").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.length()").isEqualTo(2).jsonPath("configuredLevel").isEqualTo("DEBUG").jsonPath("members") - .value(IsIterableContainingInAnyOrder.containsInAnyOrder("png.member1", "png.member2")); + this.client.get() + .uri("/actuator/loggers/group.png") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.length()") + .isEqualTo(2) + .jsonPath("configuredLevel") + .isEqualTo("DEBUG") + .jsonPath("members") + .value(IsIterableContainingInAnyOrder.containsInAnyOrder("png.member1", "png.member2")); } private void setLogLevelToDebug(String name) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java index 854787305c..5377a819d4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/HeapDumpWebEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,8 +60,15 @@ class HeapDumpWebEndpointWebIntegrationTests { @WebEndpointTest void getRequestShouldReturnHeapDumpInResponseBody(WebTestClient client) { - client.get().uri("/actuator/heapdump").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.APPLICATION_OCTET_STREAM).expectBody(String.class).isEqualTo("HEAPDUMP"); + client.get() + .uri("/actuator/heapdump") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .expectBody(String.class) + .isEqualTo("HEAPDUMP"); assertHeapDumpFileIsDeleted(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java index 5bf2a4861e..467caccedb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointTests.java @@ -99,20 +99,20 @@ class ThreadDumpEndpointTests { monitor.notifyAll(); } assertThat(threadDump) - .containsPattern(String.format("\t- parking to wait for <[0-9a-z]+> \\(a %s\\$Sync\\)", - CountDownLatch.class.getName().replace(".", "\\."))) - .contains(String.format("\t- locked <%s> (a java.lang.Object)", hexIdentityHashCode(contendedMonitor))) - .contains(String.format("\t- waiting to lock <%s> (a java.lang.Object) owned by \"%s\" t@%d", - hexIdentityHashCode(contendedMonitor), Thread.currentThread().getName(), - Thread.currentThread().getId())) - .satisfiesAnyOf( - (dump) -> assertThat(dump).contains(String.format("\t- waiting on <%s> (a java.lang.Object)", - hexIdentityHashCode(monitor))), - (dump) -> assertThat(dump).contains(String.format( - "\t- parking to wait for <%s> (a java.lang.Object)", hexIdentityHashCode(monitor)))) - .containsPattern( - String.format("Locked ownable synchronizers:%n\t- Locked <[0-9a-z]+> \\(a %s\\$NonfairSync\\)", - ReentrantReadWriteLock.class.getName().replace(".", "\\."))); + .containsPattern(String.format("\t- parking to wait for <[0-9a-z]+> \\(a %s\\$Sync\\)", + CountDownLatch.class.getName().replace(".", "\\."))) + .contains(String.format("\t- locked <%s> (a java.lang.Object)", hexIdentityHashCode(contendedMonitor))) + .contains(String.format("\t- waiting to lock <%s> (a java.lang.Object) owned by \"%s\" t@%d", + hexIdentityHashCode(contendedMonitor), Thread.currentThread().getName(), + Thread.currentThread().getId())) + .satisfiesAnyOf( + (dump) -> assertThat(dump).contains( + String.format("\t- waiting on <%s> (a java.lang.Object)", hexIdentityHashCode(monitor))), + (dump) -> assertThat(dump).contains(String + .format("\t- parking to wait for <%s> (a java.lang.Object)", hexIdentityHashCode(monitor)))) + .containsPattern( + String.format("Locked ownable synchronizers:%n\t- Locked <[0-9a-z]+> \\(a %s\\$NonfairSync\\)", + ReentrantReadWriteLock.class.getName().replace(".", "\\."))); } private String hexIdentityHashCode(Object object) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java index 3d4f361940..bbbd44c772 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/management/ThreadDumpEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -34,15 +34,29 @@ class ThreadDumpEndpointWebIntegrationTests { @WebEndpointTest void getRequestWithJsonAcceptHeaderShouldProduceJsonThreadDumpResponse(WebTestClient client) { - client.get().uri("/actuator/threaddump").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectHeader().contentType(MediaType.APPLICATION_JSON); + client.get() + .uri("/actuator/threaddump") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_JSON); } @WebEndpointTest void getRequestWithTextPlainAcceptHeaderShouldProduceTextPlainResponse(WebTestClient client) { - String response = client.get().uri("/actuator/threaddump").accept(MediaType.TEXT_PLAIN).exchange() - .expectStatus().isOk().expectHeader().contentType("text/plain;charset=UTF-8").expectBody(String.class) - .returnResult().getResponseBody(); + String response = client.get() + .uri("/actuator/threaddump") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType("text/plain;charset=UTF-8") + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(response).contains("Full thread dump"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java index c61c901f80..e49034395f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -132,8 +132,10 @@ class MetricsEndpointTests { this.registry.counter("cache", "host", "1", "region", "east", "result", "hit"); this.registry.counter("cache", "host", "1", "region", "east", "result", "miss"); MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("cache", Collections.singletonList("host:1")); - assertThat(response.getAvailableTags().stream().filter((t) -> t.getTag().equals("region")) - .flatMap((t) -> t.getValues().stream())).containsExactly("east"); + assertThat(response.getAvailableTags() + .stream() + .filter((t) -> t.getTag().equals("region")) + .flatMap((t) -> t.getValues().stream())).containsExactly("east"); } @Test @@ -149,7 +151,7 @@ class MetricsEndpointTests { @Test void metricWithInvalidTag() { assertThatExceptionOfType(InvalidEndpointRequestException.class) - .isThrownBy(() -> this.endpoint.metric("counter", Collections.singletonList("key"))); + .isThrownBy(() -> this.endpoint.metric("counter", Collections.singletonList("key"))); } @Test @@ -191,14 +193,19 @@ class MetricsEndpointTests { private void assertMetricHasStatisticEqualTo(MeterRegistry registry, String metricName, Statistic stat, Double value) { MetricsEndpoint endpoint = new MetricsEndpoint(registry); - assertThat(endpoint.metric(metricName, Collections.emptyList()).getMeasurements().stream() - .filter((sample) -> sample.getStatistic().equals(stat)).findAny()) - .hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value)); + assertThat(endpoint.metric(metricName, Collections.emptyList()) + .getMeasurements() + .stream() + .filter((sample) -> sample.getStatistic().equals(stat)) + .findAny()).hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value)); } private Optional getCount(MetricsEndpoint.MetricDescriptor response) { - return response.getMeasurements().stream().filter((sample) -> sample.getStatistic().equals(Statistic.COUNT)) - .findAny().map(MetricsEndpoint.Sample::getValue); + return response.getMeasurements() + .stream() + .filter((sample) -> sample.getStatistic().equals(Statistic.COUNT)) + .findAny() + .map(MetricsEndpoint.Sample::getValue); } private Stream availableTagKeys(MetricsEndpoint.MetricDescriptor response) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java index 60f8374bda..b4f8c2addc 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,22 +49,40 @@ class MetricsEndpointWebIntegrationTests { @WebEndpointTest @SuppressWarnings("unchecked") void listNames(WebTestClient client) throws IOException { - String responseBody = client.get().uri("/actuator/metrics").exchange().expectStatus().isOk() - .expectBody(String.class).returnResult().getResponseBody(); + String responseBody = client.get() + .uri("/actuator/metrics") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); Map> names = this.mapper.readValue(responseBody, Map.class); assertThat(names.get("names")).containsOnlyOnce("jvm.memory.used"); } @WebEndpointTest void selectByName(WebTestClient client) { - client.get().uri("/actuator/metrics/jvm.memory.used").exchange().expectStatus().isOk().expectBody() - .jsonPath("$.name").isEqualTo("jvm.memory.used"); + client.get() + .uri("/actuator/metrics/jvm.memory.used") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.name") + .isEqualTo("jvm.memory.used"); } @WebEndpointTest void selectByTag(WebTestClient client) { - client.get().uri("/actuator/metrics/jvm.memory.used?tag=id:Compressed%20Class%20Space").exchange() - .expectStatus().isOk().expectBody().jsonPath("$.name").isEqualTo("jvm.memory.used"); + client.get() + .uri("/actuator/metrics/jvm.memory.used?tag=id:Compressed%20Class%20Space") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("$.name") + .isEqualTo("jvm.memory.used"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java index 38bccbb10d..6c551abbfd 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/Cache2kCacheMeterBinderProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class Cache2kCacheMeterBinderProviderTests { @Test void cache2kCacheProvider() { SpringCache2kCacheManager cacheManager = new SpringCache2kCacheManager() - .addCaches((builder) -> builder.name("test")); + .addCaches((builder) -> builder.name("test")); MeterBinder meterBinder = new Cache2kCacheMeterBinderProvider().getMeterBinder(cacheManager.getCache("test"), Collections.emptyList()); assertThat(meterBinder).isInstanceOf(Cache2kCacheMetrics.class); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java index 150601e176..8b6dbc783a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,8 @@ class CacheMetricsRegistrarTests { CacheMetricsRegistrar registrar = new CacheMetricsRegistrar(this.meterRegistry, Collections.singleton(new CaffeineCacheMeterBinderProvider())); assertThat(registrar.bindCacheToRegistry( - new TransactionAwareCacheDecorator(new CaffeineCache("test", Caffeine.newBuilder().build())))).isTrue(); + new TransactionAwareCacheDecorator(new CaffeineCache("test", Caffeine.newBuilder().build())))) + .isTrue(); assertThat(this.meterRegistry.get("cache.gets").tags("name", "test").meter()).isNotNull(); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java index 4e3400dacc..a38b49b47c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/HazelcastCacheMeterBinderProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ class HazelcastCacheMeterBinderProviderTests { RuntimeHints runtimeHints = new RuntimeHints(); new HazelcastCacheMeterBinderProviderRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onMethod(HazelcastCache.class, "getNativeCache")) - .accepts(runtimeHints); + .accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(HazelcastCacheMetrics.class)).accepts(runtimeHints); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java index 7e659fdd29..235b38994e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/cache/RedisCacheMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,10 +54,11 @@ class RedisCacheMetricsTests { private static final Tags TAGS = Tags.of("app", "test").and("cache", "test"); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, CacheAutoConfiguration.class)) - .withUserConfiguration(CachingConfiguration.class).withPropertyValues( - "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort(), - "spring.cache.type=redis", "spring.cache.redis.enable-statistics=true"); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, CacheAutoConfiguration.class)) + .withUserConfiguration(CachingConfiguration.class) + .withPropertyValues("spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort(), "spring.cache.type=redis", + "spring.cache.redis.enable-statistics=true"); @Test void cacheStatisticsAreExposed() { @@ -66,7 +67,7 @@ class RedisCacheMetricsTests { assertThat(meterRegistry.find("cache.gets").tags(TAGS.and("result", "hit")).functionCounter()).isNotNull(); assertThat(meterRegistry.find("cache.gets").tags(TAGS.and("result", "miss")).functionCounter()).isNotNull(); assertThat(meterRegistry.find("cache.gets").tags(TAGS.and("result", "pending")).functionCounter()) - .isNotNull(); + .isNotNull(); assertThat(meterRegistry.find("cache.evictions").tags(TAGS).functionCounter()).isNull(); assertThat(meterRegistry.find("cache.puts").tags(TAGS).functionCounter()).isNotNull(); assertThat(meterRegistry.find("cache.removals").tags(TAGS).functionCounter()).isNotNull(); @@ -83,7 +84,7 @@ class RedisCacheMetricsTests { cache.get(key); cache.get(key); assertThat(meterRegistry.get("cache.gets").tags(TAGS.and("result", "hit")).functionCounter().count()) - .isEqualTo(2.0d); + .isEqualTo(2.0d); })); } @@ -95,7 +96,7 @@ class RedisCacheMetricsTests { cache.get(key); cache.get(key); assertThat(meterRegistry.get("cache.gets").tags(TAGS.and("result", "miss")).functionCounter().count()) - .isEqualTo(3.0d); + .isEqualTo(3.0d); })); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java index c548ad8da1..ca8d61d310 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,36 +73,42 @@ class PrometheusPushGatewayManagerTests { @Test void createWhenPushGatewayIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, - this.scheduler, this.pushRate, "job", this.groupingKey, null)) - .withMessage("PushGateway must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(null, this.registry, this.scheduler, this.pushRate, + "job", this.groupingKey, null)) + .withMessage("PushGateway must not be null"); } @Test void createWhenCollectorRegistryIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, null, - this.scheduler, this.pushRate, "job", this.groupingKey, null)).withMessage("Registry must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, null, this.scheduler, this.pushRate, + "job", this.groupingKey, null)) + .withMessage("Registry must not be null"); } @Test void createWhenSchedulerIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, - this.registry, null, this.pushRate, "job", this.groupingKey, null)) - .withMessage("Scheduler must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, null, this.pushRate, + "job", this.groupingKey, null)) + .withMessage("Scheduler must not be null"); } @Test void createWhenPushRateIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, - this.registry, this.scheduler, null, "job", this.groupingKey, null)) - .withMessage("PushRate must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, null, + "job", this.groupingKey, null)) + .withMessage("PushRate must not be null"); } @Test void createWhenJobIsEmptyThrowsException() { - assertThatIllegalArgumentException().isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, - this.registry, this.scheduler, this.pushRate, "", this.groupingKey, null)) - .withMessage("Job must not be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrometheusPushGatewayManager(this.pushGateway, this.registry, this.scheduler, + this.pushRate, "", this.groupingKey, null)) + .withMessage("Job must not be empty"); } @Test @@ -202,7 +208,7 @@ class PrometheusPushGatewayManagerTests { @SuppressWarnings({ "unchecked", "rawtypes" }) private T givenScheduleAtFixedRateWillReturnFuture(T scheduler) { given(scheduler.scheduleAtFixedRate(isA(Runnable.class), isA(Duration.class))) - .willReturn((ScheduledFuture) this.future); + .willReturn((ScheduledFuture) this.future); return scheduler; } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java index 1265d82106..d74a63e875 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusScrapeEndpointIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,10 +43,17 @@ class PrometheusScrapeEndpointIntegrationTests { void scrapeHasContentTypeText004ByDefault(WebTestClient client) { String expectedContentType = TextFormat.CONTENT_TYPE_004; assertThat(TextFormat.chooseContentType(null)).isEqualTo(expectedContentType); - client.get().uri("/actuator/prometheus").exchange().expectStatus().isOk().expectHeader() - .contentType(MediaType.parseMediaType(expectedContentType)).expectBody(String.class) - .value((body) -> assertThat(body).contains("counter1_total").contains("counter2_total") - .contains("counter3_total")); + client.get() + .uri("/actuator/prometheus") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.parseMediaType(expectedContentType)) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .contains("counter3_total")); } @WebEndpointTest @@ -54,34 +61,64 @@ class PrometheusScrapeEndpointIntegrationTests { String expectedContentType = TextFormat.CONTENT_TYPE_004; String accept = "*/*;q=0.8"; assertThat(TextFormat.chooseContentType(accept)).isEqualTo(expectedContentType); - client.get().uri("/actuator/prometheus").accept(MediaType.parseMediaType(accept)).exchange().expectStatus() - .isOk().expectHeader().contentType(MediaType.parseMediaType(expectedContentType)) - .expectBody(String.class).value((body) -> assertThat(body).contains("counter1_total") - .contains("counter2_total").contains("counter3_total")); + client.get() + .uri("/actuator/prometheus") + .accept(MediaType.parseMediaType(accept)) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.parseMediaType(expectedContentType)) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .contains("counter3_total")); } @WebEndpointTest void scrapeCanProduceOpenMetrics100(WebTestClient client) { MediaType openMetrics = MediaType.parseMediaType(TextFormat.CONTENT_TYPE_OPENMETRICS_100); - client.get().uri("/actuator/prometheus").accept(openMetrics).exchange().expectStatus().isOk().expectHeader() - .contentType(openMetrics).expectBody(String.class).value((body) -> assertThat(body) - .contains("counter1_total").contains("counter2_total").contains("counter3_total")); + client.get() + .uri("/actuator/prometheus") + .accept(openMetrics) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(openMetrics) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .contains("counter3_total")); } @WebEndpointTest void scrapePrefersToProduceOpenMetrics100(WebTestClient client) { MediaType openMetrics = MediaType.parseMediaType(TextFormat.CONTENT_TYPE_OPENMETRICS_100); MediaType textPlain = MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004); - client.get().uri("/actuator/prometheus").accept(openMetrics, textPlain).exchange().expectStatus().isOk() - .expectHeader().contentType(openMetrics); + client.get() + .uri("/actuator/prometheus") + .accept(openMetrics, textPlain) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(openMetrics); } @WebEndpointTest void scrapeWithIncludedNames(WebTestClient client) { - client.get().uri("/actuator/prometheus?includedNames=counter1_total,counter2_total").exchange().expectStatus() - .isOk().expectHeader().contentType(MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004)) - .expectBody(String.class).value((body) -> assertThat(body).contains("counter1_total") - .contains("counter2_total").doesNotContain("counter3_total")); + client.get() + .uri("/actuator/prometheus?includedNames=counter1_total,counter2_total") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.parseMediaType(TextFormat.CONTENT_TYPE_004)) + .expectBody(String.class) + .value((body) -> assertThat(body).contains("counter1_total") + .contains("counter2_total") + .doesNotContain("counter3_total")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java index 34764a4053..77fd731283 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/jdbc/DataSourcePoolMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -43,12 +43,12 @@ class DataSourcePoolMetricsTests { @Test void dataSourceIsInstrumented() { new ApplicationContextRunner().withUserConfiguration(DataSourceConfig.class, MetricsApp.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", "metrics.use-global-registry=false") - .run((context) -> { - context.getBean(DataSource.class).getConnection().getMetaData(); - context.getBean(MeterRegistry.class).get("jdbc.connections.max").meter(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", "metrics.use-global-registry=false") + .run((context) -> { + context.getBean(DataSource.class).getConnection().getMetaData(); + context.getBean(MeterRegistry.class).get("jdbc.connections.max").meter(); + }); } @Configuration(proxyBeanMethods = false) @@ -67,7 +67,7 @@ class DataSourcePoolMetricsTests { DataSourceConfig(DataSource dataSource, Collection metadataProviders, MeterRegistry registry) { new DataSourcePoolMetrics(dataSource, metadataProviders, "data.source", Collections.emptyList()) - .bindTo(registry); + .bindTo(registry); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java index 19a435860d..f124e1797f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -118,9 +118,10 @@ class StartupTimeMetricsListenerTests { private void assertMetricExistsWithCustomTagsAndValue(String metricName, Tags expectedCustomTags, Long expectedValueInMillis) { assertThat(this.registry.find(metricName) - .tags(Tags.concat(expectedCustomTags, "main.application.class", TestMainApplication.class.getName())) - .timeGauge()).isNotNull().extracting((m) -> m.value(TimeUnit.MILLISECONDS)) - .isEqualTo(expectedValueInMillis.doubleValue()); + .tags(Tags.concat(expectedCustomTags, "main.application.class", TestMainApplication.class.getName())) + .timeGauge()).isNotNull() + .extracting((m) -> m.value(TimeUnit.MILLISECONDS)) + .isEqualTo(expectedValueInMillis.doubleValue()); } static class TestMainApplication { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/ObservationRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/ObservationRestTemplateCustomizerTests.java index 3d3b017171..266a21cb23 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/ObservationRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/client/ObservationRestTemplateCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,8 +46,8 @@ class ObservationRestTemplateCustomizerTests { this.customizer.customize(this.restTemplate); assertThat(this.restTemplate).hasFieldOrPropertyWithValue("observationRegistry", this.observationRegistry); assertThat(this.restTemplate).extracting("observationConvention") - .isInstanceOf(DefaultClientRequestObservationConvention.class) - .hasFieldOrPropertyWithValue("name", TEST_METRIC_NAME); + .isInstanceOf(DefaultClientRequestObservationConvention.class) + .hasFieldOrPropertyWithValue("name", TEST_METRIC_NAME); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java index f75a110744..c04846e716 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/DefaultWebClientExchangeTagsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,8 @@ class DefaultWebClientExchangeTagsProviderTests { @BeforeEach void setup() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}").build(); + .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}") + .build(); this.response = mock(ClientResponse.class); given(this.response.statusCode()).willReturn(HttpStatus.OK); } @@ -68,7 +69,8 @@ class DefaultWebClientExchangeTagsProviderTests { @Test void tagsWhenNoUriTemplateShouldProvideUriPath() { ClientRequest request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")).build(); + .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) + .build(); Iterable tags = this.tagsProvider.tags(request, this.response, null); assertThat(tags).containsExactlyInAnyOrder(Tag.of("method", "GET"), Tag.of("uri", "/projects/spring-boot"), Tag.of("client.name", "example.org"), Tag.of("status", "200"), Tag.of("outcome", "SUCCESS")); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizerTests.java index 43447c88f0..676d3d36e8 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/ObservationWebClientCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,8 +49,8 @@ class ObservationWebClientCustomizerTests { this.customizer.customize(this.clientBuilder); assertThat(this.clientBuilder).hasFieldOrPropertyWithValue("observationRegistry", this.observationRegistry); assertThat(this.clientBuilder).extracting("observationConvention") - .isInstanceOf(DefaultClientRequestObservationConvention.class) - .hasFieldOrPropertyWithValue("name", TEST_METRIC_NAME); + .isInstanceOf(DefaultClientRequestObservationConvention.class) + .hasFieldOrPropertyWithValue("name", TEST_METRIC_NAME); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java index 96f67e8e1b..fbc3860fb4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/client/WebClientExchangeTagsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,8 @@ class WebClientExchangeTagsTests { @BeforeEach void setup() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}").build(); + .attribute(URI_TEMPLATE_ATTRIBUTE, "https://example.org/projects/{project}") + .build(); this.response = mock(ClientResponse.class); } @@ -69,23 +70,25 @@ class WebClientExchangeTagsTests { @Test void uriWhenRelativeTemplateIsAvailableShouldReturnTemplate() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}").build(); + .attribute(URI_TEMPLATE_ATTRIBUTE, "/projects/{project}") + .build(); assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/{project}")); } @Test void uriWhenTemplateIsMissingShouldReturnPath() { this.request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot")) - .build(); + .build(); assertThat(WebClientExchangeTags.uri(this.request)).isEqualTo(Tag.of("uri", "/projects/spring-boot")); } @Test void uriWhenTemplateIsMissingShouldReturnPathWithQueryParams() { this.request = ClientRequest - .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot?section=docs")).build(); + .create(HttpMethod.GET, URI.create("https://example.org/projects/spring-boot?section=docs")) + .build(); assertThat(WebClientExchangeTags.uri(this.request)) - .isEqualTo(Tag.of("uri", "/projects/spring-boot?section=docs")); + .isEqualTo(Tag.of("uri", "/projects/spring-boot?section=docs")); } @Test @@ -107,7 +110,7 @@ class WebClientExchangeTagsTests { @Test void statusWhenClientException() { assertThat(WebClientExchangeTags.status(null, new IllegalArgumentException())) - .isEqualTo(Tag.of("status", "CLIENT_ERROR")); + .isEqualTo(Tag.of("status", "CLIENT_ERROR")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java index e35cc5676b..39240b2fd3 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/DefaultWebFluxTagsProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,14 +53,15 @@ class DefaultWebFluxTagsProviderTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test")); Map tags = asMap( new DefaultWebFluxTagsProvider(Arrays.asList(new TestWebFluxTagsContributor("alpha"), - new TestWebFluxTagsContributor("bravo", "charlie"))).httpRequestTags(exchange, null)); + new TestWebFluxTagsContributor("bravo", "charlie"))) + .httpRequestTags(exchange, null)); assertThat(tags).containsOnlyKeys("exception", "method", "outcome", "status", "uri", "alpha", "bravo", "charlie"); } private Map asMap(Iterable tags) { return StreamSupport.stream(tags.spliterator(), false) - .collect(Collectors.toMap(Tag::getKey, Function.identity())); + .collect(Collectors.toMap(Tag::getKey, Function.identity())); } private static final class TestWebFluxTagsContributor implements WebFluxTagsContributor { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java index 60f913f2ae..03d7a10302 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/web/reactive/server/WebFluxTagsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,8 +59,8 @@ class WebFluxTagsTests { @Test void uriTagValueIsBestMatchingPatternWhenAvailable() { - this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - this.parser.parse("/spring/")); + this.exchange.getAttributes() + .put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, this.parser.parse("/spring/")); this.exchange.getResponse().setStatusCode(HttpStatus.MOVED_PERMANENTLY); Tag tag = WebFluxTags.uri(this.exchange); assertThat(tag.getValue()).isEqualTo("/spring/"); @@ -76,8 +76,8 @@ class WebFluxTagsTests { @Test void uriTagValueWithBestMatchingPatternAndIgnoreTrailingSlashRemoveTrailingSlash() { - this.exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, - this.parser.parse("/spring/")); + this.exchange.getAttributes() + .put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, this.parser.parse("/spring/")); Tag tag = WebFluxTags.uri(this.exchange, true); assertThat(tag.getValue()).isEqualTo("/spring"); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java index 56b6942f99..7ef0f997bf 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/mongo/MongoReactiveHealthIndicatorTests.java @@ -58,7 +58,7 @@ class MongoReactiveHealthIndicatorTests { void testMongoIsDown() { ReactiveMongoTemplate reactiveMongoTemplate = mock(ReactiveMongoTemplate.class); given(reactiveMongoTemplate.executeCommand("{ isMaster: 1 }")) - .willThrow(new MongoException("Connection failed")); + .willThrow(new MongoException("Connection failed")); MongoReactiveHealthIndicator mongoReactiveHealthIndicator = new MongoReactiveHealthIndicator( reactiveMongoTemplate); Mono health = mongoReactiveHealthIndicator.health(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java index dd923a4199..1220e35c8c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorIntegrationTests.java @@ -50,7 +50,8 @@ class Neo4jReactiveHealthIndicatorIntegrationTests { @Container private static final Neo4jContainer neo4jServer = new Neo4jContainer<>(DockerImageNames.neo4j()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorTests.java index 67a01028d4..4eaf14553e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/neo4j/Neo4jReactiveHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -91,7 +91,7 @@ class Neo4jReactiveHealthIndicatorTests { void neo4jIsDown() { Driver driver = mock(Driver.class); given(driver.session(eq(ReactiveSession.class), any(SessionConfig.class))) - .willThrow(ServiceUnavailableException.class); + .willThrow(ServiceUnavailableException.class); Neo4jReactiveHealthIndicator healthIndicator = new Neo4jReactiveHealthIndicator(driver); healthIndicator.health().as(StepVerifier::create).consumeNextWith((health) -> { assertThat(health.getStatus()).isEqualTo(Status.DOWN); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java index 3ae1656e35..9fa95ed84f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -91,14 +91,20 @@ class QuartzEndpointTests { private static final JobDetail jobThree = JobBuilder.newJob(Job.class).withIdentity("jobThree", "samples").build(); - private static final Trigger triggerOne = TriggerBuilder.newTrigger().forJob(jobOne).withIdentity("triggerOne") - .build(); + private static final Trigger triggerOne = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withIdentity("triggerOne") + .build(); - private static final Trigger triggerTwo = TriggerBuilder.newTrigger().forJob(jobOne).withIdentity("triggerTwo") - .build(); + private static final Trigger triggerTwo = TriggerBuilder.newTrigger() + .forJob(jobOne) + .withIdentity("triggerTwo") + .build(); - private static final Trigger triggerThree = TriggerBuilder.newTrigger().forJob(jobThree) - .withIdentity("triggerThree", "samples").build(); + private static final Trigger triggerThree = TriggerBuilder.newTrigger() + .forJob(jobThree) + .withIdentity("triggerThree", "samples") + .build(); private final Scheduler scheduler; @@ -145,9 +151,9 @@ class QuartzEndpointTests { Map jobGroups = this.endpoint.quartzJobGroups().getGroups(); assertThat(jobGroups).containsOnlyKeys("DEFAULT", "samples"); assertThat(jobGroups).extractingByKey("DEFAULT", nestedMap()) - .containsOnly(entry("jobs", Arrays.asList("jobOne", "jobTwo"))); + .containsOnly(entry("jobs", Arrays.asList("jobOne", "jobTwo"))); assertThat(jobGroups).extractingByKey("samples", nestedMap()) - .containsOnly(entry("jobs", Collections.singletonList("jobThree"))); + .containsOnly(entry("jobs", Collections.singletonList("jobThree"))); } @Test @@ -163,10 +169,10 @@ class QuartzEndpointTests { given(this.scheduler.getPausedTriggerGroups()).willReturn(Collections.singleton("samples")); Map triggerGroups = this.endpoint.quartzTriggerGroups().getGroups(); assertThat(triggerGroups).containsOnlyKeys("DEFAULT", "samples"); - assertThat(triggerGroups).extractingByKey("DEFAULT", nestedMap()).containsOnly(entry("paused", false), - entry("triggers", Arrays.asList("triggerOne", "triggerTwo"))); - assertThat(triggerGroups).extractingByKey("samples", nestedMap()).containsOnly(entry("paused", true), - entry("triggers", Collections.singletonList("triggerThree"))); + assertThat(triggerGroups).extractingByKey("DEFAULT", nestedMap()) + .containsOnly(entry("paused", false), entry("triggers", Arrays.asList("triggerOne", "triggerTwo"))); + assertThat(triggerGroups).extractingByKey("samples", nestedMap()) + .containsOnly(entry("paused", true), entry("triggers", Collections.singletonList("triggerThree"))); } @Test @@ -216,7 +222,7 @@ class QuartzEndpointTests { void quartzTriggerGroupSummaryWithEmptyGroup() throws SchedulerException { given(this.scheduler.getTriggerGroupNames()).willReturn(Collections.singletonList("samples")); given(this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals("samples"))) - .willReturn(Collections.emptySet()); + .willReturn(Collections.emptySet()); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary).isNotNull(); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -230,8 +236,10 @@ class QuartzEndpointTests { @Test void quartzTriggerGroupSummaryWithCronTrigger() throws SchedulerException { - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples") - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger cronTrigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); mockTriggers(cronTrigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -248,23 +256,28 @@ class QuartzEndpointTests { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples").withPriority(3) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)).build(); + CronTrigger cronTrigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withPriority(3) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)) + .build(); ((OperableTrigger) cronTrigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) cronTrigger).setNextFireTime(nextFireTime); mockTriggers(cronTrigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getCron(); assertThat(triggers).containsOnlyKeys("3am-every-day"); - assertThat(triggers).extractingByKey("3am-every-day", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 3), - entry("expression", "0 0 3 ? * *"), entry("timeZone", timeZone)); + assertThat(triggers).extractingByKey("3am-every-day", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 3), entry("expression", "0 0 3 ? * *"), entry("timeZone", timeZone)); } @Test void quartzTriggerGroupSummaryWithSimpleTrigger() throws SchedulerException { - SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity("every-hour", "samples") - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)).build(); + SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour", "samples") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)) + .build(); mockTriggers(simpleTrigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -280,25 +293,30 @@ class QuartzEndpointTests { void quartzTriggerGroupSummaryWithSimpleTriggerDetails() throws SchedulerException { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity("every-hour", "samples").withPriority(7) - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)).build(); + SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour", "samples") + .withPriority(7) + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(1)) + .build(); ((OperableTrigger) simpleTrigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) simpleTrigger).setNextFireTime(nextFireTime); mockTriggers(simpleTrigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getSimple(); assertThat(triggers).containsOnlyKeys("every-hour"); - assertThat(triggers).extractingByKey("every-hour", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 7), - entry("interval", 3600000L)); + assertThat(triggers).extractingByKey("every-hour", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 7), entry("interval", 3600000L)); } @Test void quartzTriggerGroupSummaryWithDailyIntervalTrigger() throws SchedulerException { - DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour-9am", "samples") - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour-9am", "samples") + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); mockTriggers(trigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -314,31 +332,34 @@ class QuartzEndpointTests { void quartzTriggerGroupSummaryWithDailyIntervalTriggerDetails() throws SchedulerException { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour-tue-thu", "samples") - .withPriority(4) - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour-tue-thu", "samples") + .withPriority(4) + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getDailyTimeInterval(); assertThat(triggers).containsOnlyKeys("every-hour-tue-thu"); - assertThat(triggers).extractingByKey("every-hour-tue-thu", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 4), - entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), - entry("endTimeOfDay", LocalTime.of(18, 0)), - entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(3, 5)))); + assertThat(triggers).extractingByKey("every-hour-tue-thu", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 4), entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), + entry("endTimeOfDay", LocalTime.of(18, 0)), + entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(3, 5)))); } @Test void quartzTriggerGroupSummaryWithCalendarIntervalTrigger() throws SchedulerException { - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("once-a-week", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("once-a-week", "samples") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) + .build(); mockTriggers(trigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); assertThat(summary.getGroup()).isEqualTo("samples"); @@ -355,19 +376,22 @@ class QuartzEndpointTests { TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("once-a-week", "samples") - .withPriority(8).withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule() - .withIntervalInWeeks(1).inTimeZone(timeZone)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("once-a-week", "samples") + .withPriority(8) + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule() + .withIntervalInWeeks(1) + .inTimeZone(timeZone)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getCalendarInterval(); assertThat(triggers).containsOnlyKeys("once-a-week"); - assertThat(triggers).extractingByKey("once-a-week", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 8), - entry("interval", 604800000L), entry("timeZone", timeZone)); + assertThat(triggers).extractingByKey("once-a-week", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 8), entry("interval", 604800000L), entry("timeZone", timeZone)); } @Test @@ -398,9 +422,9 @@ class QuartzEndpointTests { QuartzTriggerGroupSummaryDescriptor summary = this.endpoint.quartzTriggerGroupSummary("samples"); Map triggers = summary.getTriggers().getCustom(); assertThat(triggers).containsOnlyKeys("custom"); - assertThat(triggers).extractingByKey("custom", nestedMap()).containsOnly( - entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("priority", 9), - entry("trigger", trigger.toString())); + assertThat(triggers).extractingByKey("custom", nestedMap()) + .containsOnly(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), + entry("priority", 9), entry("trigger", trigger.toString())); } @Test @@ -408,14 +432,17 @@ class QuartzEndpointTests { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples").withPriority(3) - .withDescription("Sample description") - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)).build(); + CronTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withPriority(3) + .withDescription("Sample description") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("3am-every-day", "samples"))) - .willReturn(TriggerState.NORMAL); + .willReturn(TriggerState.NORMAL); Map triggerDetails = this.endpoint.quartzTrigger("samples", "3am-every-day", true); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "3am-every-day"), entry("description", "Sample description"), entry("type", "cron"), entry("state", TriggerState.NORMAL), @@ -423,8 +450,8 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("simple", "dailyTimeInterval", "calendarInterval", "custom"); - assertThat(triggerDetails).extractingByKey("cron", nestedMap()).containsOnly(entry("expression", "0 0 3 ? * *"), - entry("timeZone", timeZone)); + assertThat(triggerDetails).extractingByKey("cron", nestedMap()) + .containsOnly(entry("expression", "0 0 3 ? * *"), entry("timeZone", timeZone)); } @Test @@ -433,15 +460,19 @@ class QuartzEndpointTests { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); Date endTime = Date.from(Instant.parse("2020-01-31T09:00:00Z")); - SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour", "samples").withPriority(20) - .withDescription("Every hour").startAt(startTime).endAt(endTime) - .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(1).withRepeatCount(2000)) - .build(); + SimpleTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour", "samples") + .withPriority(20) + .withDescription("Every hour") + .startAt(startTime) + .endAt(endTime) + .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(1).withRepeatCount(2000)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("every-hour", "samples"))) - .willReturn(TriggerState.COMPLETE); + .willReturn(TriggerState.COMPLETE); Map triggerDetails = this.endpoint.quartzTrigger("samples", "every-hour", true); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "every-hour"), entry("description", "Every hour"), entry("type", "simple"), entry("state", TriggerState.COMPLETE), @@ -449,26 +480,29 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("startTime", startTime), entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime), entry("endTime", endTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "dailyTimeInterval", "calendarInterval", "custom"); - assertThat(triggerDetails).extractingByKey("simple", nestedMap()).containsOnly(entry("interval", 3600000L), - entry("repeatCount", 2000), entry("timesTriggered", 0)); + assertThat(triggerDetails).extractingByKey("simple", nestedMap()) + .containsOnly(entry("interval", 3600000L), entry("repeatCount", 2000), entry("timesTriggered", 0)); } @Test void quartzTriggerWithDailyTimeIntervalTrigger() throws SchedulerException { Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("every-hour-mon-wed", "samples") - .withDescription("Every working hour Mon Wed").withPriority(4) - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.MONDAY, Calendar.WEDNESDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("every-hour-mon-wed", "samples") + .withDescription("Every working hour Mon Wed") + .withPriority(4) + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.MONDAY, Calendar.WEDNESDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("every-hour-mon-wed", "samples"))) - .willReturn(TriggerState.NORMAL); + .willReturn(TriggerState.NORMAL); Map triggerDetails = this.endpoint.quartzTrigger("samples", "every-hour-mon-wed", true); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "every-hour-mon-wed"), entry("description", "Every working hour Mon Wed"), entry("type", "dailyTimeInterval"), @@ -476,11 +510,11 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "simple", "calendarInterval", "custom"); - assertThat(triggerDetails).extractingByKey("dailyTimeInterval", nestedMap()).containsOnly( - entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), - entry("endTimeOfDay", LocalTime.of(18, 0)), - entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(2, 4))), entry("repeatCount", -1), - entry("timesTriggered", 0)); + assertThat(triggerDetails).extractingByKey("dailyTimeInterval", nestedMap()) + .containsOnly(entry("interval", 3600000L), entry("startTimeOfDay", LocalTime.of(9, 0)), + entry("endTimeOfDay", LocalTime.of(18, 0)), + entry("daysOfWeek", new LinkedHashSet<>(Arrays.asList(2, 4))), entry("repeatCount", -1), + entry("timesTriggered", 0)); } @Test @@ -488,16 +522,20 @@ class QuartzEndpointTests { TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); Date previousFireTime = Date.from(Instant.parse("2020-11-30T03:00:00Z")); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("once-a-week", "samples") - .withDescription("Once a week").withPriority(8) - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1) - .inTimeZone(timeZone).preserveHourOfDayAcrossDaylightSavings(true)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("once-a-week", "samples") + .withDescription("Once a week") + .withPriority(8) + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule() + .withIntervalInWeeks(1) + .inTimeZone(timeZone) + .preserveHourOfDayAcrossDaylightSavings(true)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("once-a-week", "samples"))) - .willReturn(TriggerState.BLOCKED); + .willReturn(TriggerState.BLOCKED); Map triggerDetails = this.endpoint.quartzTrigger("samples", "once-a-week", true); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "once-a-week"), entry("description", "Once a week"), entry("type", "calendarInterval"), @@ -505,10 +543,10 @@ class QuartzEndpointTests { assertThat(triggerDetails).contains(entry("previousFireTime", previousFireTime), entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "simple", "dailyTimeInterval", "custom"); - assertThat(triggerDetails).extractingByKey("calendarInterval", nestedMap()).containsOnly( - entry("interval", 604800000L), entry("timeZone", timeZone), - entry("preserveHourOfDayAcrossDaylightSavings", true), entry("skipDayIfHourDoesNotExist", false), - entry("timesTriggered", 0)); + assertThat(triggerDetails).extractingByKey("calendarInterval", nestedMap()) + .containsOnly(entry("interval", 604800000L), entry("timeZone", timeZone), + entry("preserveHourOfDayAcrossDaylightSavings", true), entry("skipDayIfHourDoesNotExist", false), + entry("timesTriggered", 0)); } @Test @@ -522,7 +560,7 @@ class QuartzEndpointTests { given(trigger.getPriority()).willReturn(9); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("custom", "samples"))) - .willReturn(TriggerState.ERROR); + .willReturn(TriggerState.ERROR); Map triggerDetails = this.endpoint.quartzTrigger("samples", "custom", true); assertThat(triggerDetails).contains(entry("group", "samples"), entry("name", "custom"), entry("type", "custom"), entry("state", TriggerState.ERROR), entry("priority", 9)); @@ -530,45 +568,55 @@ class QuartzEndpointTests { entry("nextFireTime", nextFireTime)); assertThat(triggerDetails).doesNotContainKeys("cron", "simple", "calendarInterval", "dailyTimeInterval"); assertThat(triggerDetails).extractingByKey("custom", nestedMap()) - .containsOnly(entry("trigger", trigger.toString())); + .containsOnly(entry("trigger", trigger.toString())); } @Test void quartzTriggerWithDataMap() throws SchedulerException { - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples") - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).usingJobData("user", "user") - .usingJobData("password", "secret").usingJobData("url", "https://user:secret@example.com").build(); + CronTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .usingJobData("user", "user") + .usingJobData("password", "secret") + .usingJobData("url", "https://user:secret@example.com") + .build(); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("3am-every-day", "samples"))) - .willReturn(TriggerState.NORMAL); + .willReturn(TriggerState.NORMAL); Map triggerDetails = this.endpoint.quartzTrigger("samples", "3am-every-day", true); - assertThat(triggerDetails).extractingByKey("data", nestedMap()).containsOnly(entry("user", "user"), - entry("password", "secret"), entry("url", "https://user:secret@example.com")); + assertThat(triggerDetails).extractingByKey("data", nestedMap()) + .containsOnly(entry("user", "user"), entry("password", "secret"), + entry("url", "https://user:secret@example.com")); } @Test void quartzTriggerWithDataMapAndShowUnsanitizedFalse() throws SchedulerException { - CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples") - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).usingJobData("user", "user") - .usingJobData("password", "secret").usingJobData("url", "https://user:secret@example.com").build(); + CronTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .usingJobData("user", "user") + .usingJobData("password", "secret") + .usingJobData("url", "https://user:secret@example.com") + .build(); mockTriggers(trigger); given(this.scheduler.getTriggerState(TriggerKey.triggerKey("3am-every-day", "samples"))) - .willReturn(TriggerState.NORMAL); + .willReturn(TriggerState.NORMAL); Map triggerDetails = this.endpoint.quartzTrigger("samples", "3am-every-day", false); - assertThat(triggerDetails).extractingByKey("data", nestedMap()).containsOnly(entry("user", "******"), - entry("password", "******"), entry("url", "******")); + assertThat(triggerDetails).extractingByKey("data", nestedMap()) + .containsOnly(entry("user", "******"), entry("password", "******"), entry("url", "******")); } @ParameterizedTest(name = "unit {1}") @MethodSource("intervalUnitParameters") void canConvertIntervalUnit(int amount, IntervalUnit unit, Duration expectedDuration) throws SchedulerException { - CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withInterval(amount, unit)) - .build(); + CalendarIntervalTrigger trigger = TriggerBuilder.newTrigger() + .withIdentity("trigger", "samples") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withInterval(amount, unit)) + .build(); mockTriggers(trigger); Map triggerDetails = this.endpoint.quartzTrigger("samples", "trigger", true); assertThat(triggerDetails).extractingByKey("calendarInterval", nestedMap()) - .contains(entry("interval", expectedDuration.toMillis())); + .contains(entry("interval", expectedDuration.toMillis())); } static Stream intervalUnitParameters() { @@ -584,8 +632,12 @@ class QuartzEndpointTests { @Test void quartzJobWithoutTrigger() throws SchedulerException { - JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").withDescription("A sample job") - .storeDurably().requestRecovery(false).build(); + JobDetail job = JobBuilder.newJob(Job.class) + .withIdentity("hello", "samples") + .withDescription("A sample job") + .storeDurably() + .requestRecovery(false) + .build(); mockJobs(job); QuartzJobDetailsDescriptor jobDetails = this.endpoint.quartzJob("samples", "hello", true); assertThat(jobDetails.getGroup()).isEqualTo("samples"); @@ -604,14 +656,17 @@ class QuartzEndpointTests { Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").build(); TimeZone timeZone = TimeZone.getTimeZone("Europe/Paris"); - Trigger trigger = TriggerBuilder.newTrigger().withIdentity("3am-every-day", "samples").withPriority(4) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)).build(); + Trigger trigger = TriggerBuilder.newTrigger() + .withIdentity("3am-every-day", "samples") + .withPriority(4) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0).inTimeZone(timeZone)) + .build(); ((OperableTrigger) trigger).setPreviousFireTime(previousFireTime); ((OperableTrigger) trigger).setNextFireTime(nextFireTime); mockJobs(job); mockTriggers(trigger); given(this.scheduler.getTriggersOfJob(JobKey.jobKey("hello", "samples"))) - .willAnswer((invocation) -> Collections.singletonList(trigger)); + .willAnswer((invocation) -> Collections.singletonList(trigger)); QuartzJobDetailsDescriptor jobDetails = this.endpoint.quartzJob("samples", "hello", true); assertThat(jobDetails.getTriggers()).hasSize(1); Map triggerDetails = jobDetails.getTriggers().get(0); @@ -624,16 +679,22 @@ class QuartzEndpointTests { JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").build(); mockJobs(job); Date triggerOneNextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CronTrigger triggerOne = TriggerBuilder.newTrigger().withIdentity("one", "samples").withPriority(5) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger triggerOne = TriggerBuilder.newTrigger() + .withIdentity("one", "samples") + .withPriority(5) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); ((OperableTrigger) triggerOne).setNextFireTime(triggerOneNextFireTime); Date triggerTwoNextFireTime = Date.from(Instant.parse("2020-12-01T02:00:00Z")); - CronTrigger triggerTwo = TriggerBuilder.newTrigger().withIdentity("two", "samples").withPriority(10) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(2, 0)).build(); + CronTrigger triggerTwo = TriggerBuilder.newTrigger() + .withIdentity("two", "samples") + .withPriority(10) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(2, 0)) + .build(); ((OperableTrigger) triggerTwo).setNextFireTime(triggerTwoNextFireTime); mockTriggers(triggerOne, triggerTwo); given(this.scheduler.getTriggersOfJob(JobKey.jobKey("hello", "samples"))) - .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); + .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); QuartzJobDetailsDescriptor jobDetails = this.endpoint.quartzJob("samples", "hello", true); assertThat(jobDetails.getTriggers()).hasSize(2); assertThat(jobDetails.getTriggers().get(0)).containsEntry("name", "two"); @@ -645,15 +706,21 @@ class QuartzEndpointTests { JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").build(); mockJobs(job); Date nextFireTime = Date.from(Instant.parse("2020-12-01T03:00:00Z")); - CronTrigger triggerOne = TriggerBuilder.newTrigger().withIdentity("one", "samples").withPriority(3) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger triggerOne = TriggerBuilder.newTrigger() + .withIdentity("one", "samples") + .withPriority(3) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); ((OperableTrigger) triggerOne).setNextFireTime(nextFireTime); - CronTrigger triggerTwo = TriggerBuilder.newTrigger().withIdentity("two", "samples").withPriority(7) - .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + CronTrigger triggerTwo = TriggerBuilder.newTrigger() + .withIdentity("two", "samples") + .withPriority(7) + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); ((OperableTrigger) triggerTwo).setNextFireTime(nextFireTime); mockTriggers(triggerOne, triggerTwo); given(this.scheduler.getTriggersOfJob(JobKey.jobKey("hello", "samples"))) - .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); + .willAnswer((invocation) -> Arrays.asList(triggerOne, triggerTwo)); QuartzJobDetailsDescriptor jobDetails = this.endpoint.quartzJob("samples", "hello", true); assertThat(jobDetails.getTriggers()).hasSize(2); assertThat(jobDetails.getTriggers().get(0)).containsEntry("name", "two"); @@ -662,8 +729,12 @@ class QuartzEndpointTests { @Test void quartzJobWithDataMap() throws SchedulerException { - JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").usingJobData("user", "user") - .usingJobData("password", "secret").usingJobData("url", "https://user:secret@example.com").build(); + JobDetail job = JobBuilder.newJob(Job.class) + .withIdentity("hello", "samples") + .usingJobData("user", "user") + .usingJobData("password", "secret") + .usingJobData("url", "https://user:secret@example.com") + .build(); mockJobs(job); QuartzJobDetailsDescriptor jobDetails = this.endpoint.quartzJob("samples", "hello", true); assertThat(jobDetails.getData()).containsOnly(entry("user", "user"), entry("password", "secret"), @@ -672,8 +743,12 @@ class QuartzEndpointTests { @Test void quartzJobWithDataMapAndShowUnsanitizedFalse() throws SchedulerException { - JobDetail job = JobBuilder.newJob(Job.class).withIdentity("hello", "samples").usingJobData("user", "user") - .usingJobData("password", "secret").usingJobData("url", "https://user:secret@example.com").build(); + JobDetail job = JobBuilder.newJob(Job.class) + .withIdentity("hello", "samples") + .usingJobData("user", "user") + .usingJobData("password", "secret") + .usingJobData("url", "https://user:secret@example.com") + .build(); mockJobs(job); QuartzJobDetailsDescriptor jobDetails = this.endpoint.quartzJob("samples", "hello", false); assertThat(jobDetails.getData()).containsOnly(entry("user", "******"), entry("password", "******"), @@ -690,7 +765,7 @@ class QuartzEndpointTests { given(this.scheduler.getJobGroupNames()).willReturn(new ArrayList<>(jobKeys.keySet())); for (Entry> entry : jobKeys.entrySet()) { given(this.scheduler.getJobKeys(GroupMatcher.jobGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } @@ -704,7 +779,7 @@ class QuartzEndpointTests { given(this.scheduler.getTriggerGroupNames()).willReturn(new ArrayList<>(triggerKeys.keySet())); for (Entry> entry : triggerKeys.entrySet()) { given(this.scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebExtensionTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebExtensionTests.java index 9d7d58ae39..2495f5ed0b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebExtensionTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -103,9 +103,10 @@ class QuartzEndpointWebExtensionTests { Set> bindingTypes = Set.of(QuartzGroupsDescriptor.class, QuartzJobDetailsDescriptor.class, QuartzJobGroupSummaryDescriptor.class, QuartzTriggerGroupSummaryDescriptor.class); for (Class bindingType : bindingTypes) { - assertThat(RuntimeHintsPredicates.reflection().onType(bindingType) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(bindingType) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java index 3ab376f606..907224e33c 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/quartz/QuartzEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,47 +62,80 @@ import static org.mockito.Mockito.mock; */ class QuartzEndpointWebIntegrationTests { - private static final JobDetail jobOne = JobBuilder.newJob(Job.class).withIdentity("jobOne", "samples") - .usingJobData(new JobDataMap(Collections.singletonMap("name", "test"))).withDescription("A sample job") - .build(); + private static final JobDetail jobOne = JobBuilder.newJob(Job.class) + .withIdentity("jobOne", "samples") + .usingJobData(new JobDataMap(Collections.singletonMap("name", "test"))) + .withDescription("A sample job") + .build(); - private static final JobDetail jobTwo = JobBuilder.newJob(DelegatingJob.class).withIdentity("jobTwo", "samples") - .build(); + private static final JobDetail jobTwo = JobBuilder.newJob(DelegatingJob.class) + .withIdentity("jobTwo", "samples") + .build(); private static final JobDetail jobThree = JobBuilder.newJob(Job.class).withIdentity("jobThree").build(); - private static final CronTrigger triggerOne = TriggerBuilder.newTrigger().withDescription("Once a day 3AM") - .withIdentity("triggerOne").withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)).build(); + private static final CronTrigger triggerOne = TriggerBuilder.newTrigger() + .withDescription("Once a day 3AM") + .withIdentity("triggerOne") + .withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(3, 0)) + .build(); - private static final SimpleTrigger triggerTwo = TriggerBuilder.newTrigger().withDescription("Once a day") - .withIdentity("triggerTwo", "tests").withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)).build(); + private static final SimpleTrigger triggerTwo = TriggerBuilder.newTrigger() + .withDescription("Once a day") + .withIdentity("triggerTwo", "tests") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)) + .build(); private static final CalendarIntervalTrigger triggerThree = TriggerBuilder.newTrigger() - .withDescription("Once a week").withIdentity("triggerThree", "tests") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)).build(); + .withDescription("Once a week") + .withIdentity("triggerThree", "tests") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) + .build(); @WebEndpointTest void quartzReport(WebTestClient client) { - client.get().uri("/actuator/quartz").exchange().expectStatus().isOk().expectBody().jsonPath("jobs.groups") - .isEqualTo(new JSONArray().appendElement("samples").appendElement("DEFAULT")) - .jsonPath("triggers.groups").isEqualTo(new JSONArray().appendElement("DEFAULT").appendElement("tests")); + client.get() + .uri("/actuator/quartz") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("jobs.groups") + .isEqualTo(new JSONArray().appendElement("samples").appendElement("DEFAULT")) + .jsonPath("triggers.groups") + .isEqualTo(new JSONArray().appendElement("DEFAULT").appendElement("tests")); } @WebEndpointTest void quartzJobNames(WebTestClient client) { - client.get().uri("/actuator/quartz/jobs").exchange().expectStatus().isOk().expectBody() - .jsonPath("groups.samples.jobs") - .isEqualTo(new JSONArray().appendElement("jobOne").appendElement("jobTwo")) - .jsonPath("groups.DEFAULT.jobs").isEqualTo(new JSONArray().appendElement("jobThree")); + client.get() + .uri("/actuator/quartz/jobs") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("groups.samples.jobs") + .isEqualTo(new JSONArray().appendElement("jobOne").appendElement("jobTwo")) + .jsonPath("groups.DEFAULT.jobs") + .isEqualTo(new JSONArray().appendElement("jobThree")); } @WebEndpointTest void quartzTriggerNames(WebTestClient client) { - client.get().uri("/actuator/quartz/triggers").exchange().expectStatus().isOk().expectBody() - .jsonPath("groups.DEFAULT.paused").isEqualTo(false).jsonPath("groups.DEFAULT.triggers") - .isEqualTo(new JSONArray().appendElement("triggerOne")).jsonPath("groups.tests.paused").isEqualTo(false) - .jsonPath("groups.tests.triggers") - .isEqualTo(new JSONArray().appendElement("triggerTwo").appendElement("triggerThree")); + client.get() + .uri("/actuator/quartz/triggers") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("groups.DEFAULT.paused") + .isEqualTo(false) + .jsonPath("groups.DEFAULT.triggers") + .isEqualTo(new JSONArray().appendElement("triggerOne")) + .jsonPath("groups.tests.paused") + .isEqualTo(false) + .jsonPath("groups.tests.triggers") + .isEqualTo(new JSONArray().appendElement("triggerTwo").appendElement("triggerThree")); } @WebEndpointTest @@ -112,9 +145,18 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzJobGroupSummary(WebTestClient client) { - client.get().uri("/actuator/quartz/jobs/samples").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("samples").jsonPath("jobs.jobOne.className").isEqualTo(Job.class.getName()) - .jsonPath("jobs.jobTwo.className").isEqualTo(DelegatingJob.class.getName()); + client.get() + .uri("/actuator/quartz/jobs/samples") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("samples") + .jsonPath("jobs.jobOne.className") + .isEqualTo(Job.class.getName()) + .jsonPath("jobs.jobTwo.className") + .isEqualTo(DelegatingJob.class.getName()); } @WebEndpointTest @@ -124,12 +166,26 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzTriggerGroupSummary(WebTestClient client) { - client.get().uri("/actuator/quartz/triggers/tests").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("tests").jsonPath("paused").isEqualTo("false").jsonPath("triggers.cron") - .isEmpty().jsonPath("triggers.simple.triggerTwo.interval").isEqualTo(86400000) - .jsonPath("triggers.dailyTimeInterval").isEmpty() - .jsonPath("triggers.calendarInterval.triggerThree.interval").isEqualTo(604800000) - .jsonPath("triggers.custom").isEmpty(); + client.get() + .uri("/actuator/quartz/triggers/tests") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("tests") + .jsonPath("paused") + .isEqualTo("false") + .jsonPath("triggers.cron") + .isEmpty() + .jsonPath("triggers.simple.triggerTwo.interval") + .isEqualTo(86400000) + .jsonPath("triggers.dailyTimeInterval") + .isEmpty() + .jsonPath("triggers.calendarInterval.triggerThree.interval") + .isEqualTo(604800000) + .jsonPath("triggers.custom") + .isEmpty(); } @WebEndpointTest @@ -139,9 +195,18 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzJobDetail(WebTestClient client) { - client.get().uri("/actuator/quartz/jobs/samples/jobOne").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("samples").jsonPath("name").isEqualTo("jobOne").jsonPath("data.name") - .isEqualTo("test"); + client.get() + .uri("/actuator/quartz/jobs/samples/jobOne") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("samples") + .jsonPath("name") + .isEqualTo("jobOne") + .jsonPath("data.name") + .isEqualTo("test"); } @WebEndpointTest @@ -151,11 +216,32 @@ class QuartzEndpointWebIntegrationTests { @WebEndpointTest void quartzTriggerDetail(WebTestClient client) { - client.get().uri("/actuator/quartz/triggers/DEFAULT/triggerOne").exchange().expectStatus().isOk().expectBody() - .jsonPath("group").isEqualTo("DEFAULT").jsonPath("name").isEqualTo("triggerOne").jsonPath("description") - .isEqualTo("Once a day 3AM").jsonPath("state").isEqualTo("NORMAL").jsonPath("type").isEqualTo("cron") - .jsonPath("simple").doesNotExist().jsonPath("calendarInterval").doesNotExist().jsonPath("dailyInterval") - .doesNotExist().jsonPath("custom").doesNotExist().jsonPath("cron.expression").isEqualTo("0 0 3 ? * *"); + client.get() + .uri("/actuator/quartz/triggers/DEFAULT/triggerOne") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("group") + .isEqualTo("DEFAULT") + .jsonPath("name") + .isEqualTo("triggerOne") + .jsonPath("description") + .isEqualTo("Once a day 3AM") + .jsonPath("state") + .isEqualTo("NORMAL") + .jsonPath("type") + .isEqualTo("cron") + .jsonPath("simple") + .doesNotExist() + .jsonPath("calendarInterval") + .doesNotExist() + .jsonPath("dailyInterval") + .doesNotExist() + .jsonPath("custom") + .doesNotExist() + .jsonPath("cron.expression") + .isEqualTo("0 0 3 ? * *"); } @WebEndpointTest @@ -194,7 +280,7 @@ class QuartzEndpointWebIntegrationTests { given(scheduler.getJobGroupNames()).willReturn(new ArrayList<>(jobKeys.keySet())); for (Entry> entry : jobKeys.entrySet()) { given(scheduler.getJobKeys(GroupMatcher.jobGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } @@ -209,7 +295,7 @@ class QuartzEndpointWebIntegrationTests { given(scheduler.getTriggerGroupNames()).willReturn(new ArrayList<>(triggerKeys.keySet())); for (Entry> entry : triggerKeys.entrySet()) { given(scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(entry.getKey()))) - .willReturn(new LinkedHashSet<>(entry.getValue())); + .willReturn(new LinkedHashSet<>(entry.getValue())); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java index f22484d7a4..2f57add1bb 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/r2dbc/ConnectionFactoryHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -100,9 +100,11 @@ class ConnectionFactoryHealthIndicatorTests { String customValidationQuery = "SELECT COUNT(*) from HEALTH_TEST"; String createTableStatement = "CREATE TABLE HEALTH_TEST (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY)"; Mono.from(connectionFactory.create()) - .flatMapMany((it) -> Flux.from(it.createStatement(createTableStatement).execute()) - .flatMap(Result::getRowsUpdated).thenMany(it.close())) - .as(StepVerifier::create).verifyComplete(); + .flatMapMany((it) -> Flux.from(it.createStatement(createTableStatement).execute()) + .flatMap(Result::getRowsUpdated) + .thenMany(it.close())) + .as(StepVerifier::create) + .verifyComplete(); ReactiveHealthIndicator healthIndicator = new ConnectionFactoryHealthIndicator(connectionFactory, customValidationQuery); healthIndicator.health().as(StepVerifier::create).assertNext((actual) -> { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java index 0499060291..899bff1265 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/redis/RedisReactiveHealthIndicatorTests.java @@ -114,8 +114,9 @@ class RedisReactiveHealthIndicatorTests { given(redisConnection.closeLater()).willReturn(Mono.empty()); RedisReactiveHealthIndicator healthIndicator = createHealthIndicator(redisConnection, commands); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); then(redisConnection).should().closeLater(); } @@ -123,11 +124,12 @@ class RedisReactiveHealthIndicatorTests { void redisConnectionIsDown() { ReactiveRedisConnectionFactory redisConnectionFactory = mock(ReactiveRedisConnectionFactory.class); given(redisConnectionFactory.getReactiveConnection()) - .willThrow(new RedisConnectionException("Unable to connect to localhost:6379")); + .willThrow(new RedisConnectionException("Unable to connect to localhost:6379")); RedisReactiveHealthIndicator healthIndicator = new RedisReactiveHealthIndicator(redisConnectionFactory); Mono health = healthIndicator.health(); - StepVerifier.create(health).consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) - .verifyComplete(); + StepVerifier.create(health) + .consumeNextWith((h) -> assertThat(h.getStatus()).isEqualTo(Status.DOWN)) + .verifyComplete(); } private RedisReactiveHealthIndicator createHealthIndicator(ReactiveRedisConnection redisConnection, diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java index 5082c28c3a..0e5a3623ab 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpointTests.java @@ -56,7 +56,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ScheduledTasksEndpointTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(BaseConfiguration.class); + .withUserConfiguration(BaseConfiguration.class); @Test void cronScheduledMethodIsReported() { @@ -95,7 +95,7 @@ class ScheduledTasksEndpointTests { assertThat(description.getInitialDelay()).isEqualTo(2); assertThat(description.getInterval()).isOne(); assertThat(description.getRunnable().getTarget()) - .isEqualTo(FixedDelayScheduledMethod.class.getName() + ".fixedDelay"); + .isEqualTo(FixedDelayScheduledMethod.class.getName() + ".fixedDelay"); }); } @@ -124,7 +124,7 @@ class ScheduledTasksEndpointTests { assertThat(description.getInitialDelay()).isEqualTo(4); assertThat(description.getInterval()).isEqualTo(3); assertThat(description.getRunnable().getTarget()) - .isEqualTo(FixedRateScheduledMethod.class.getName() + ".fixedRate"); + .isEqualTo(FixedRateScheduledMethod.class.getName() + ".fixedRate"); }); } @@ -162,15 +162,16 @@ class ScheduledTasksEndpointTests { Set> bindingTypes = Set.of(FixedRateTaskDescriptor.class, FixedDelayTaskDescriptor.class, CronTaskDescriptor.class, CustomTriggerTaskDescriptor.class); for (Class bindingType : bindingTypes) { - assertThat(RuntimeHintsPredicates.reflection().onType(bindingType) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(bindingType) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } private void run(Class configuration, Consumer consumer) { this.contextRunner.withUserConfiguration(configuration) - .run((context) -> consumer.accept(context.getBean(ScheduledTasksEndpoint.class).scheduledTasks())); + .run((context) -> consumer.accept(context.getBean(ScheduledTasksEndpoint.class).scheduledTasks())); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java index 5095187a56..eb1647e389 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class SessionsEndpointTests { @Test void sessionsForUsername() { given(this.repository.findByPrincipalName("user")) - .willReturn(Collections.singletonMap(session.getId(), session)); + .willReturn(Collections.singletonMap(session.getId(), session)); List result = this.endpoint.sessionsForUsername("user").getSessions(); assertThat(result).hasSize(1); assertThat(result.get(0).getId()).isEqualTo(session.getId()); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java index 26b1f0757f..0a6b28dd83 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/session/SessionsEndpointWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -47,29 +47,46 @@ class SessionsEndpointWebIntegrationTests { @WebEndpointTest void sessionsForUsernameWithoutUsernameParam(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/sessions").build()).exchange().expectStatus() - .isBadRequest(); + client.get() + .uri((builder) -> builder.path("/actuator/sessions").build()) + .exchange() + .expectStatus() + .isBadRequest(); } @WebEndpointTest void sessionsForUsernameNoResults(WebTestClient client) { given(repository.findByPrincipalName("user")).willReturn(Collections.emptyMap()); - client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("sessions").isEmpty(); + client.get() + .uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("sessions") + .isEmpty(); } @WebEndpointTest void sessionsForUsernameFound(WebTestClient client) { given(repository.findByPrincipalName("user")).willReturn(Collections.singletonMap(session.getId(), session)); - client.get().uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) - .exchange().expectStatus().isOk().expectBody().jsonPath("sessions.[*].id") - .isEqualTo(new JSONArray().appendElement(session.getId())); + client.get() + .uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("sessions.[*].id") + .isEqualTo(new JSONArray().appendElement(session.getId())); } @WebEndpointTest void sessionForIdNotFound(WebTestClient client) { - client.get().uri((builder) -> builder.path("/actuator/sessions/session-id-not-found").build()).exchange() - .expectStatus().isNotFound(); + client.get() + .uri((builder) -> builder.path("/actuator/sessions/session-id-not-found").build()) + .exchange() + .expectStatus() + .isNotFound(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java index b448d590e3..340a4751d1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/startup/StartupEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,7 @@ class StartupEndpointTests { StartupDescriptor startup = startupEndpoint.startup(); assertThat(startup.getSpringBootVersion()).isEqualTo(SpringBootVersion.getVersion()); assertThat(startup.getTimeline().getStartTime()) - .isEqualTo(applicationStartup.getBufferedTimeline().getStartTime()); + .isEqualTo(applicationStartup.getBufferedTimeline().getStartTime()); }); } @@ -84,15 +84,16 @@ class StartupEndpointTests { TypeReference.of("org.springframework.boot.context.metrics.buffering.BufferedStartupStep$DefaultTag"), TypeReference.of("org.springframework.core.metrics.jfr.FlightRecorderStartupStep$FlightRecorderTag")); for (TypeReference bindingType : bindingTypes) { - assertThat(RuntimeHintsPredicates.reflection().onType(bindingType) - .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(bindingType) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(runtimeHints); } } private void testStartupEndpoint(ApplicationStartup applicationStartup, Consumer startupEndpoint) { ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withInitializer((context) -> context.setApplicationStartup(applicationStartup)) - .withUserConfiguration(EndpointConfiguration.class); + .withInitializer((context) -> context.setApplicationStartup(applicationStartup)) + .withUserConfiguration(EndpointConfiguration.class); contextRunner.run((context) -> { assertThat(context).hasSingleBean(StartupEndpoint.class); startupEndpoint.accept(context.getBean(StartupEndpoint.class)); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/HttpExchangeTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/HttpExchangeTests.java index bec552feab..97cd4d898f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/HttpExchangeTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/HttpExchangeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -72,192 +72,196 @@ class HttpExchangeTests { void getTimestampReturnsTimestamp() { Instant now = Instant.now(); Clock clock = Clock.fixed(now, ZoneId.systemDefault()); - HttpExchange exchange = HttpExchange.start(clock, createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(clock, createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getTimestamp()).isEqualTo(now); } @Test void getRequestUriReturnsUri() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getRequest().getUri()).isEqualTo(URI.create("https://api.example.com")); } @Test void getRequestRemoteAddressWhenUsingDefaultIncludesReturnsNull() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getRequest().getRemoteAddress()).isNull(); } @Test void getRequestRemoteAddressWhenIncludedReturnsRemoteAddress() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.REMOTE_ADDRESS); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REMOTE_ADDRESS); assertThat(exchange.getRequest().getRemoteAddress()).isEqualTo("127.0.0.1"); } @Test void getRequestMethodReturnsHttpMethod() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getRequest().getMethod()).isEqualTo("GET"); } @Test void getRequestHeadersWhenUsingDefaultIncludesReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getRequest().getHeaders()).containsOnlyKeys(HttpHeaders.ACCEPT); } @Test void getRequestHeadersWhenIncludedReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.REQUEST_HEADERS); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS); assertThat(exchange.getRequest().getHeaders()).containsOnlyKeys(HttpHeaders.ACCEPT); } @Test void getRequestHeadersWhenNotIncludedReturnsEmptyHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID); assertThat(exchange.getRequest().getHeaders()).isEmpty(); } @Test void getRequestHeadersWhenUsingDefaultIncludesFiltersAuthorizeHeader() { - HttpExchange exchange = HttpExchange.start(createRequest(AUTHORIZATION_HEADER)).finish(createResponse(), - NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest(AUTHORIZATION_HEADER)) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getRequest().getHeaders()).isEmpty(); } @Test void getRequestHeadersWhenIncludesAuthorizationHeaderReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest(AUTHORIZATION_HEADER)).finish(createResponse(), - NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER); + HttpExchange exchange = HttpExchange.start(createRequest(AUTHORIZATION_HEADER)) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS, + Include.AUTHORIZATION_HEADER); assertThat(exchange.getRequest().getHeaders()).containsOnlyKeys(HttpHeaders.AUTHORIZATION); } @Test void getRequestHeadersWhenIncludesAuthorizationHeaderAndInDifferentCaseReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest(mixedCase(AUTHORIZATION_HEADER))).finish( - createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS, Include.AUTHORIZATION_HEADER); + HttpExchange exchange = HttpExchange.start(createRequest(mixedCase(AUTHORIZATION_HEADER))) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS, + Include.AUTHORIZATION_HEADER); assertThat(exchange.getRequest().getHeaders()).containsOnlyKeys(mixedCase(HttpHeaders.AUTHORIZATION)); } @Test void getRequestHeadersWhenUsingDefaultIncludesFiltersCookieHeader() { - HttpExchange exchange = HttpExchange.start(createRequest(COOKIE_HEADER)).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest(COOKIE_HEADER)) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getRequest().getHeaders()).isEmpty(); } @Test void getRequestHeadersWhenIncludesCookieHeaderReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest(COOKIE_HEADER)).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.REQUEST_HEADERS, Include.COOKIE_HEADERS); + HttpExchange exchange = HttpExchange.start(createRequest(COOKIE_HEADER)) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS, Include.COOKIE_HEADERS); assertThat(exchange.getRequest().getHeaders()).containsOnlyKeys(HttpHeaders.COOKIE); } @Test void getRequestHeadersWhenIncludesCookieHeaderAndInDifferentCaseReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest(mixedCase(COOKIE_HEADER))).finish(createResponse(), - NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS, Include.COOKIE_HEADERS); + HttpExchange exchange = HttpExchange.start(createRequest(mixedCase(COOKIE_HEADER))) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REQUEST_HEADERS, Include.COOKIE_HEADERS); assertThat(exchange.getRequest().getHeaders()).containsOnlyKeys(mixedCase(HttpHeaders.COOKIE)); } @Test void getResponseStatusReturnsStatus() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.REMOTE_ADDRESS); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.REMOTE_ADDRESS); assertThat(exchange.getResponse().getStatus()).isEqualTo(204); } @Test void getResponseHeadersWhenUsingDefaultIncludesReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getResponse().getHeaders()).containsOnlyKeys(HttpHeaders.CONTENT_TYPE); } @Test void getResponseHeadersWhenNotIncludedReturnsEmptyHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID); assertThat(exchange.getResponse().getHeaders()).isEmpty(); } @Test void getResponseHeadersIncludedReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.RESPONSE_HEADERS); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.RESPONSE_HEADERS); assertThat(exchange.getResponse().getHeaders()).containsOnlyKeys(HttpHeaders.CONTENT_TYPE); } @Test void getResponseHeadersWhenUsingDefaultIncludesFiltersSetCookieHeader() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(SET_COOKIE_HEADER), - NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(SET_COOKIE_HEADER), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getResponse().getHeaders()).isEmpty(); } @Test void getResponseHeadersWhenIncludesCookieHeaderReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(SET_COOKIE_HEADER), - NO_PRINCIPAL, NO_SESSION_ID, Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(SET_COOKIE_HEADER), NO_PRINCIPAL, NO_SESSION_ID, Include.RESPONSE_HEADERS, + Include.COOKIE_HEADERS); assertThat(exchange.getResponse().getHeaders()).containsKey(HttpHeaders.SET_COOKIE); } @Test void getResponseHeadersWhenIncludesCookieHeaderAndInDifferentCaseReturnsHeaders() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(mixedCase(SET_COOKIE_HEADER)), - NO_PRINCIPAL, NO_SESSION_ID, Include.RESPONSE_HEADERS, Include.COOKIE_HEADERS); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(mixedCase(SET_COOKIE_HEADER)), NO_PRINCIPAL, NO_SESSION_ID, Include.RESPONSE_HEADERS, + Include.COOKIE_HEADERS); assertThat(exchange.getResponse().getHeaders()).containsKey(mixedCase(HttpHeaders.SET_COOKIE)); } @Test void getPrincipalWhenUsingDefaultIncludesReturnsNull() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), WITH_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), WITH_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getPrincipal()).isNull(); } @Test void getPrincipalWhenIncludesPrincipalReturnsPrincipal() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), WITH_PRINCIPAL, - NO_SESSION_ID, Include.PRINCIPAL); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), WITH_PRINCIPAL, NO_SESSION_ID, Include.PRINCIPAL); assertThat(exchange.getPrincipal()).isNotNull(); assertThat(exchange.getPrincipal().getName()).isEqualTo("alice"); } @Test void getSessionIdWhenUsingDefaultIncludesReturnsNull() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - WITH_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, WITH_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getSession()).isNull(); } @Test void getSessionIdWhenIncludesSessionReturnsSessionId() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - WITH_SESSION_ID, Include.SESSION_ID); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, WITH_SESSION_ID, Include.SESSION_ID); assertThat(exchange.getSession()).isNotNull(); assertThat(exchange.getSession().getId()).isEqualTo("JSESSION_123"); } @Test void getTimeTakenWhenUsingDefaultIncludesReturnsTimeTaken() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID, Include.defaultIncludes()); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getTimeTaken()).isNotNull(); } @Test void getTimeTakenWhenNotIncludedReturnsNull() { - HttpExchange exchange = HttpExchange.start(createRequest()).finish(createResponse(), NO_PRINCIPAL, - NO_SESSION_ID); + HttpExchange exchange = HttpExchange.start(createRequest()) + .finish(createResponse(), NO_PRINCIPAL, NO_SESSION_ID); assertThat(exchange.getTimeTaken()).isNull(); } @@ -266,8 +270,8 @@ class HttpExchangeTests { Duration duration = Duration.ofSeconds(1); Clock startClock = Clock.fixed(Instant.now(), ZoneId.systemDefault()); Clock finishClock = Clock.offset(startClock, duration); - HttpExchange exchange = HttpExchange.start(startClock, createRequest()).finish(finishClock, createResponse(), - NO_PRINCIPAL, NO_SESSION_ID, Include.TIME_TAKEN); + HttpExchange exchange = HttpExchange.start(startClock, createRequest()) + .finish(finishClock, createResponse(), NO_PRINCIPAL, NO_SESSION_ID, Include.TIME_TAKEN); assertThat(exchange.getTimeTaken()).isEqualTo(duration); } @@ -281,7 +285,7 @@ class HttpExchangeTests { responseHeaders.set(HttpHeaders.SET_COOKIE, "test=test"); responseHeaders.setContentLength(0); HttpExchange exchange = HttpExchange.start(createRequest(requestHeaders)) - .finish(createResponse(responseHeaders), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); + .finish(createResponse(responseHeaders), NO_PRINCIPAL, NO_SESSION_ID, Include.defaultIncludes()); assertThat(exchange.getTimeTaken()).isNotNull(); assertThat(exchange.getPrincipal()).isNull(); assertThat(exchange.getSession()).isNull(); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterIntegrationTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterIntegrationTests.java index 8c85022c3f..c3d0d70804 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,13 +49,18 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r class HttpExchangesWebFilterIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withUserConfiguration(Config.class); + .withUserConfiguration(Config.class); @Test void exchangeForNotFoundResponseHas404Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/").exchange().expectStatus() - .isNotFound(); + WebTestClient.bindToApplicationContext(context) + .build() + .get() + .uri("/") + .exchange() + .expectStatus() + .isNotFound(); HttpExchangeRepository repository = context.getBean(HttpExchangeRepository.class); assertThat(repository.findAll()).hasSize(1); assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(404); @@ -65,8 +70,13 @@ class HttpExchangesWebFilterIntegrationTests { @Test void exchangeForMonoErrorWithRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/mono-error").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + WebTestClient.bindToApplicationContext(context) + .build() + .get() + .uri("/mono-error") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); HttpExchangeRepository repository = context.getBean(HttpExchangeRepository.class); assertThat(repository.findAll()).hasSize(1); assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); @@ -76,8 +86,13 @@ class HttpExchangesWebFilterIntegrationTests { @Test void exchangeForThrownRuntimeExceptionHas500Status() { this.contextRunner.run((context) -> { - WebTestClient.bindToApplicationContext(context).build().get().uri("/thrown").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + WebTestClient.bindToApplicationContext(context) + .build() + .get() + .uri("/thrown") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); HttpExchangeRepository repository = context.getBean(HttpExchangeRepository.class); assertThat(repository.findAll()).hasSize(1); assertThat(repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterTests.java index 21ebc21796..e7d06876e9 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/reactive/HttpExchangesWebFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,8 +58,9 @@ class HttpExchangesWebFilterTests { @Test void filterRecordsSessionIdWhenSessionIsUsed() { executeFilter(MockServerWebExchange.from(MockServerHttpRequest.get("https://api.example.com")), - (exchange) -> exchange.getSession().doOnNext((session) -> session.getAttributes().put("a", "alpha")) - .then()); + (exchange) -> exchange.getSession() + .doOnNext((session) -> session.getAttributes().put("a", "alpha")) + .then()); assertThat(this.repository.findAll()).hasSize(1); Session session = this.repository.findAll().get(0).getSession(); assertThat(session).isNotNull(); @@ -91,15 +92,17 @@ class HttpExchangesWebFilterTests { }, (exchange) -> exchange.getSession().doOnNext((session) -> session.getAttributes().put("a", "alpha")).then()); assertThat(this.repository.findAll()).hasSize(1); org.springframework.boot.actuate.web.exchanges.HttpExchange.Principal recordedPrincipal = this.repository - .findAll().get(0).getPrincipal(); + .findAll() + .get(0) + .getPrincipal(); assertThat(recordedPrincipal).isNotNull(); assertThat(recordedPrincipal.getName()).isEqualTo("alice"); } private void executeFilter(ServerWebExchange exchange, WebFilterChain chain) { - StepVerifier.create( - this.filter.filter(exchange, chain).then(Mono.defer(() -> exchange.getResponse().setComplete()))) - .verifyComplete(); + StepVerifier + .create(this.filter.filter(exchange, chain).then(Mono.defer(() -> exchange.getResponse().setComplete()))) + .verifyComplete(); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/servlet/HttpExchangesFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/servlet/HttpExchangesFilterTests.java index 0b69da1ef5..d9ff6528e5 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/servlet/HttpExchangesFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/exchanges/servlet/HttpExchangesFilterTests.java @@ -88,7 +88,9 @@ class HttpExchangesFilterTests { this.filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertThat(this.repository.findAll()).hasSize(1); org.springframework.boot.actuate.web.exchanges.HttpExchange.Principal recordedPrincipal = this.repository - .findAll().get(0).getPrincipal(); + .findAll() + .get(0) + .getPrincipal(); assertThat(recordedPrincipal).isNotNull(); assertThat(recordedPrincipal.getName()).isEqualTo("alice"); } @@ -104,10 +106,11 @@ class HttpExchangesFilterTests { throw new IOException(); } - }))).satisfies((ex) -> { - assertThat(this.repository.findAll()).hasSize(1); - assertThat(this.repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); - }); + }))) + .satisfies((ex) -> { + assertThat(this.repository.findAll()).hasSize(1); + assertThat(this.repository.findAll().get(0).getResponse().getStatus()).isEqualTo(500); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java index 2f99876a53..929b7a9e1f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/MappingsEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,60 +78,63 @@ class MappingsEndpointTests { void servletWebMappings() { Supplier contextSupplier = prepareContextSupplier(); new WebApplicationContextRunner(contextSupplier) - .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class).run((context) -> { - ContextMappingsDescriptor contextMappings = contextMappings(context); - assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", - "servlets"); - Map> dispatcherServlets = mappings( - contextMappings, "dispatcherServlets"); - assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); - List handlerMappings = dispatcherServlets - .get("dispatcherServlet"); - assertThat(handlerMappings).hasSize(1); - List servlets = mappings(contextMappings, "servlets"); - assertThat(servlets).hasSize(1); - List filters = mappings(contextMappings, "servletFilters"); - assertThat(filters).hasSize(1); - }); + .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class) + .run((context) -> { + ContextMappingsDescriptor contextMappings = contextMappings(context); + assertThat(contextMappings.getParentId()).isNull(); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", + "servlets"); + Map> dispatcherServlets = mappings(contextMappings, + "dispatcherServlets"); + assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); + List handlerMappings = dispatcherServlets.get("dispatcherServlet"); + assertThat(handlerMappings).hasSize(1); + List servlets = mappings(contextMappings, "servlets"); + assertThat(servlets).hasSize(1); + List filters = mappings(contextMappings, "servletFilters"); + assertThat(filters).hasSize(1); + }); } @Test void servletWebMappingsWithPathPatternParser() { Supplier contextSupplier = prepareContextSupplier(); - new WebApplicationContextRunner(contextSupplier).withUserConfiguration(EndpointConfiguration.class, - ServletWebConfiguration.class, PathPatternParserConfiguration.class).run((context) -> { - ContextMappingsDescriptor contextMappings = contextMappings(context); - assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", - "servlets"); - Map> dispatcherServlets = mappings( - contextMappings, "dispatcherServlets"); - assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); - List handlerMappings = dispatcherServlets - .get("dispatcherServlet"); - assertThat(handlerMappings).hasSize(1); - List servlets = mappings(contextMappings, "servlets"); - assertThat(servlets).hasSize(1); - List filters = mappings(contextMappings, "servletFilters"); - assertThat(filters).hasSize(1); - }); + new WebApplicationContextRunner(contextSupplier) + .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class, + PathPatternParserConfiguration.class) + .run((context) -> { + ContextMappingsDescriptor contextMappings = contextMappings(context); + assertThat(contextMappings.getParentId()).isNull(); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherServlets", "servletFilters", + "servlets"); + Map> dispatcherServlets = mappings(contextMappings, + "dispatcherServlets"); + assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet"); + List handlerMappings = dispatcherServlets.get("dispatcherServlet"); + assertThat(handlerMappings).hasSize(1); + List servlets = mappings(contextMappings, "servlets"); + assertThat(servlets).hasSize(1); + List filters = mappings(contextMappings, "servletFilters"); + assertThat(filters).hasSize(1); + }); } @Test void servletWebMappingsWithAdditionalDispatcherServlets() { Supplier contextSupplier = prepareContextSupplier(); - new WebApplicationContextRunner(contextSupplier).withUserConfiguration(EndpointConfiguration.class, - ServletWebConfiguration.class, CustomDispatcherServletConfiguration.class).run((context) -> { - ContextMappingsDescriptor contextMappings = contextMappings(context); - Map> dispatcherServlets = mappings( - contextMappings, "dispatcherServlets"); - assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet", - "customDispatcherServletRegistration", "anotherDispatcherServletRegistration"); - assertThat(dispatcherServlets.get("dispatcherServlet")).hasSize(1); - assertThat(dispatcherServlets.get("customDispatcherServletRegistration")).hasSize(1); - assertThat(dispatcherServlets.get("anotherDispatcherServletRegistration")).hasSize(1); - }); + new WebApplicationContextRunner(contextSupplier) + .withUserConfiguration(EndpointConfiguration.class, ServletWebConfiguration.class, + CustomDispatcherServletConfiguration.class) + .run((context) -> { + ContextMappingsDescriptor contextMappings = contextMappings(context); + Map> dispatcherServlets = mappings(contextMappings, + "dispatcherServlets"); + assertThat(dispatcherServlets).containsOnlyKeys("dispatcherServlet", + "customDispatcherServletRegistration", "anotherDispatcherServletRegistration"); + assertThat(dispatcherServlets.get("dispatcherServlet")).hasSize(1); + assertThat(dispatcherServlets.get("customDispatcherServletRegistration")).hasSize(1); + assertThat(dispatcherServlets.get("anotherDispatcherServletRegistration")).hasSize(1); + }); } @SuppressWarnings("unchecked") @@ -141,10 +144,10 @@ class MappingsEndpointTests { given(servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); FilterRegistration filterRegistration = mock(FilterRegistration.class); given((Map) servletContext.getFilterRegistrations()) - .willReturn(Collections.singletonMap("testFilter", filterRegistration)); + .willReturn(Collections.singletonMap("testFilter", filterRegistration)); ServletRegistration servletRegistration = mock(ServletRegistration.class); given((Map) servletContext.getServletRegistrations()) - .willReturn(Collections.singletonMap("testServlet", servletRegistration)); + .willReturn(Collections.singletonMap("testServlet", servletRegistration)); return () -> { AnnotationConfigServletWebApplicationContext context = new AnnotationConfigServletWebApplicationContext(); context.setServletContext(servletContext); @@ -155,16 +158,17 @@ class MappingsEndpointTests { @Test void reactiveWebMappings() { new ReactiveWebApplicationContextRunner() - .withUserConfiguration(EndpointConfiguration.class, ReactiveWebConfiguration.class).run((context) -> { - ContextMappingsDescriptor contextMappings = contextMappings(context); - assertThat(contextMappings.getParentId()).isNull(); - assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherHandlers"); - Map> dispatcherHandlers = mappings( - contextMappings, "dispatcherHandlers"); - assertThat(dispatcherHandlers).containsOnlyKeys("webHandler"); - List handlerMappings = dispatcherHandlers.get("webHandler"); - assertThat(handlerMappings).hasSize(4); - }); + .withUserConfiguration(EndpointConfiguration.class, ReactiveWebConfiguration.class) + .run((context) -> { + ContextMappingsDescriptor contextMappings = contextMappings(context); + assertThat(contextMappings.getParentId()).isNull(); + assertThat(contextMappings.getMappings()).containsOnlyKeys("dispatcherHandlers"); + Map> dispatcherHandlers = mappings(contextMappings, + "dispatcherHandlers"); + assertThat(dispatcherHandlers).containsOnlyKeys("webHandler"); + List handlerMappings = dispatcherHandlers.get("webHandler"); + assertThat(handlerMappings).hasSize(4); + }); } private ContextMappingsDescriptor contextMappings(ApplicationContext context) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProviderTests.java index f184c80128..457d76992b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/reactive/DispatcherHandlersMappingDescriptionProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,9 +37,10 @@ class DispatcherHandlersMappingDescriptionProviderTests { RuntimeHints runtimeHints = new RuntimeHints(); new DispatcherHandlersMappingDescriptionProviderRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(DispatcherHandlerMappingDescription.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(DispatcherHandlerMappingDescription.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProviderTests.java index 1cb0f46126..37e6f5e461 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,9 +37,10 @@ class DispatcherServletsMappingDescriptionProviderTests { RuntimeHints runtimeHints = new RuntimeHints(); new DispatcherServletsMappingDescriptionProviderRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(DispatcherServletMappingDescription.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(DispatcherServletMappingDescription.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProviderTests.java index ec1c329808..0cd58884ad 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,9 +36,10 @@ class FiltersMappingDescriptionProviderTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new FiltersMappingDescriptionProviderRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(FilterRegistrationMappingDescription.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(FilterRegistrationMappingDescription.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProviderTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProviderTests.java index 912f8151b1..71dd8984b4 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProviderTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,9 +36,10 @@ class ServletsMappingDescriptionProviderTests { void shouldRegisterHints() { RuntimeHints runtimeHints = new RuntimeHints(); new ServletsMappingDescriptionProviderRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); - assertThat(RuntimeHintsPredicates.reflection().onType(ServletRegistrationMappingDescription.class) - .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(ServletRegistrationMappingDescription.class) + .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS)) + .accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java index d78c8f2881..aa1ad182d9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,8 +79,8 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor implements BeanF this.beanClass = beanClass; this.factoryBeanClass = factoryBeanClass; this.dependsOn = (beanFactory) -> Arrays.stream(dependencyTypes) - .flatMap((dependencyType) -> getBeanNames(beanFactory, dependencyType).stream()) - .collect(Collectors.toSet()); + .flatMap((dependencyType) -> getBeanNames(beanFactory, dependencyType).stream()) + .collect(Collectors.toSet()); } /** diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java index 98c81a6414..ab691e235e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoad private boolean isAutoConfiguration(MetadataReader metadataReader) { boolean annotatedWithAutoConfiguration = metadataReader.getAnnotationMetadata() - .isAnnotated(AutoConfiguration.class.getName()); + .isAnnotated(AutoConfiguration.class.getName()); return annotatedWithAutoConfiguration || getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName()); } @@ -64,7 +64,7 @@ public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoad protected List getAutoConfigurations() { if (this.autoConfigurations == null) { this.autoConfigurations = ImportCandidates.load(AutoConfiguration.class, this.beanClassLoader) - .getCandidates(); + .getCandidates(); } return this.autoConfigurations; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java index d9ca022512..592f87e10f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -178,7 +178,7 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, */ protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List configurations = ImportCandidates.load(AutoConfiguration.class, getBeanClassLoader()) - .getCandidates(); + .getCandidates(); Assert.notEmpty(configurations, "No auto configuration classes found in " + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you " @@ -241,8 +241,9 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, } if (environment instanceof ConfigurableEnvironment) { Binder binder = Binder.get(environment); - return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class).map(Arrays::asList) - .orElse(Collections.emptyList()); + return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class) + .map(Arrays::asList) + .orElse(Collections.emptyList()); } String[] excludes = environment.getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class); return (excludes != null) ? Arrays.asList(excludes) : Collections.emptyList(); @@ -426,7 +427,7 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName())); AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) - .getAutoConfigurationEntry(annotationMetadata); + .getAutoConfigurationEntry(annotationMetadata); this.autoConfigurationEntries.add(autoConfigurationEntry); for (String importClassName : autoConfigurationEntry.getConfigurations()) { this.entries.putIfAbsent(importClassName, annotationMetadata); @@ -439,14 +440,18 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, return Collections.emptyList(); } Set allExclusions = this.autoConfigurationEntries.stream() - .map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet()); + .map(AutoConfigurationEntry::getExclusions) + .flatMap(Collection::stream) + .collect(Collectors.toSet()); Set processedConfigurations = this.autoConfigurationEntries.stream() - .map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .map(AutoConfigurationEntry::getConfigurations) + .flatMap(Collection::stream) + .collect(Collectors.toCollection(LinkedHashSet::new)); processedConfigurations.removeAll(allExclusions); return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream() - .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName)).toList(); + .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName)) + .toList(); } private AutoConfigurationMetadata getAutoConfigurationMetadata() { @@ -459,7 +464,7 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector, private List sortAutoConfigurations(Set configurations, AutoConfigurationMetadata autoConfigurationMetadata) { return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata) - .getInPriorityOrder(configurations); + .getInPriorityOrder(configurations); } private MetadataReaderFactory getMetadataReaderFactory() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java index 370dc082a5..873a3e8bcf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationPackages.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -106,10 +106,11 @@ public abstract class AutoConfigurationPackages { ConstructorArgumentValues constructorArgumentValues = beanDefinition.getConstructorArgumentValues(); if (constructorArgumentValues.hasIndexedArgumentValue(0)) { String[] existingPackages = (String[]) constructorArgumentValues.getIndexedArgumentValue(0, String[].class) - .getValue(); + .getValue(); constructorArgumentValues.addIndexedArgumentValue(0, - Stream.concat(Stream.of(existingPackages), Stream.of(additionalBasePackages)).distinct() - .toArray(String[]::new)); + Stream.concat(Stream.of(existingPackages), Stream.of(additionalBasePackages)) + .distinct() + .toArray(String[]::new)); } else { constructorArgumentValues.addIndexedArgumentValue(0, additionalBasePackages); @@ -143,7 +144,7 @@ public abstract class AutoConfigurationPackages { PackageImports(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false)); + .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false)); List packageNames = new ArrayList<>(Arrays.asList(attributes.getStringArray("basePackages"))); for (Class basePackageClass : attributes.getClassArray("basePackageClasses")) { packageNames.add(basePackageClass.getPackage().getName()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java index 6877a54ab9..5229834e72 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationSorter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -206,7 +206,7 @@ class AutoConfigurationSorter { AutoConfigureOrder.DEFAULT_ORDER); } Map attributes = getAnnotationMetadata() - .getAnnotationAttributes(AutoConfigureOrder.class.getName()); + .getAnnotationAttributes(AutoConfigureOrder.class.getName()); return (attributes != null) ? (Integer) attributes.get("value") : AutoConfigureOrder.DEFAULT_ORDER; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java index f2c584683f..2063a69fb2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,8 +49,9 @@ public class AutoConfigurations extends Configurations implements Ordered { protected Collection> sort(Collection> classes) { List names = classes.stream().map(Class::getName).toList(); List sorted = SORTER.getInPriorityOrder(names); - return sorted.stream().map((className) -> ClassUtils.resolveClassName(className, null)) - .collect(Collectors.toCollection(ArrayList::new)); + return sorted.stream() + .map((className) -> ClassUtils.resolveClassName(className, null)) + .collect(Collectors.toCollection(ArrayList::new)); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java index c8843e827e..d26f3d0d6b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -112,8 +112,8 @@ class SharedMetadataReaderFactoryContextInitializer implements private void register(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(SharedMetadataReaderFactoryBean.class, SharedMetadataReaderFactoryBean::new) - .getBeanDefinition(); + .rootBeanDefinition(SharedMetadataReaderFactoryBean.class, SharedMetadataReaderFactoryBean::new) + .getBeanDefinition(); registry.registerBeanDefinition(BEAN_NAME, definition); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java index 4d6160f4df..3a25c78554 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/AbstractConnectionFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -56,8 +56,9 @@ public abstract class AbstractConnectionFactoryConfigurer builder = (retryConfig.isStateless()) ? RetryInterceptorBuilder.stateless() : RetryInterceptorBuilder.stateful(); RetryTemplate retryTemplate = new RetryTemplateFactory(this.retryTemplateCustomizers) - .createRetryTemplate(retryConfig, RabbitRetryTemplateCustomizer.Target.LISTENER); + .createRetryTemplate(retryConfig, RabbitRetryTemplateCustomizer.Target.LISTENER); builder.retryOperations(retryTemplate); MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer : new RejectAndDontRequeueRecoverer(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java index 1c8ecdcca7..97ab3d661b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/CachingConnectionFactoryConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -37,12 +37,15 @@ public class CachingConnectionFactoryConfigurer extends AbstractConnectionFactor public void configure(CachingConnectionFactory connectionFactory, RabbitProperties rabbitProperties) { PropertyMapper map = PropertyMapper.get(); map.from(rabbitProperties::isPublisherReturns).to(connectionFactory::setPublisherReturns); - map.from(rabbitProperties::getPublisherConfirmType).whenNonNull() - .to(connectionFactory::setPublisherConfirmType); + map.from(rabbitProperties::getPublisherConfirmType) + .whenNonNull() + .to(connectionFactory::setPublisherConfirmType); RabbitProperties.Cache.Channel channel = rabbitProperties.getCache().getChannel(); map.from(channel::getSize).whenNonNull().to(connectionFactory::setChannelCacheSize); - map.from(channel::getCheckoutTimeout).whenNonNull().as(Duration::toMillis) - .to(connectionFactory::setChannelCheckoutTimeout); + map.from(channel::getCheckoutTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(connectionFactory::setChannelCheckoutTimeout); RabbitProperties.Cache.Connection connection = rabbitProperties.getCache().getConnection(); map.from(connection::getMode).whenNonNull().to(connectionFactory::setCacheMode); map.from(connection::getSize).whenNonNull().to(connectionFactory::setConnectionCacheSize); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java index 12a621faed..f31e8106da 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -126,7 +126,7 @@ public class RabbitAutoConfiguration { connectionFactoryBean.afterPropertiesSet(); com.rabbitmq.client.ConnectionFactory connectionFactory = connectionFactoryBean.getObject(); connectionFactoryCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(connectionFactory)); + .forEach((customizer) -> customizer.customize(connectionFactory)); CachingConnectionFactory factory = new CachingConnectionFactory(connectionFactory); rabbitCachingConnectionFactoryConfigurer.configure(factory); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java index ff0728616f..2c2149bc3e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitConnectionFactoryBeanConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -71,8 +71,10 @@ public class RabbitConnectionFactoryBeanConfigurer { map.from(this.rabbitProperties::determineUsername).whenNonNull().to(factory::setUsername); map.from(this.rabbitProperties::determinePassword).whenNonNull().to(factory::setPassword); map.from(this.rabbitProperties::determineVirtualHost).whenNonNull().to(factory::setVirtualHost); - map.from(this.rabbitProperties::getRequestedHeartbeat).whenNonNull().asInt(Duration::getSeconds) - .to(factory::setRequestedHeartbeat); + map.from(this.rabbitProperties::getRequestedHeartbeat) + .whenNonNull() + .asInt(Duration::getSeconds) + .to(factory::setRequestedHeartbeat); map.from(this.rabbitProperties::getRequestedChannelMax).to(factory::setRequestedChannelMax); RabbitProperties.Ssl ssl = this.rabbitProperties.getSsl(); if (ssl.determineEnabled()) { @@ -87,13 +89,17 @@ public class RabbitConnectionFactoryBeanConfigurer { map.from(ssl::getTrustStorePassword).to(factory::setTrustStorePassphrase); map.from(ssl::getTrustStoreAlgorithm).whenNonNull().to(factory::setTrustStoreAlgorithm); map.from(ssl::isValidateServerCertificate) - .to((validate) -> factory.setSkipServerCertificateValidation(!validate)); + .to((validate) -> factory.setSkipServerCertificateValidation(!validate)); map.from(ssl::getVerifyHostname).to(factory::setEnableHostnameVerification); } - map.from(this.rabbitProperties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) - .to(factory::setConnectionTimeout); - map.from(this.rabbitProperties::getChannelRpcTimeout).whenNonNull().asInt(Duration::toMillis) - .to(factory::setChannelRpcTimeout); + map.from(this.rabbitProperties::getConnectionTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(factory::setConnectionTimeout); + map.from(this.rabbitProperties::getChannelRpcTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(factory::setChannelRpcTimeout); map.from(this.credentialsProvider).whenNonNull().to(factory::setCredentialsProvider); map.from(this.credentialsRefreshService).whenNonNull().to(factory::setCredentialsRefreshService); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java index 6cecbb9b03..6d20e66c7b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RabbitTemplateConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -88,12 +88,16 @@ public class RabbitTemplateConfigurer { RabbitProperties.Template templateProperties = this.rabbitProperties.getTemplate(); if (templateProperties.getRetry().isEnabled()) { template.setRetryTemplate(new RetryTemplateFactory(this.retryTemplateCustomizers) - .createRetryTemplate(templateProperties.getRetry(), RabbitRetryTemplateCustomizer.Target.SENDER)); + .createRetryTemplate(templateProperties.getRetry(), RabbitRetryTemplateCustomizer.Target.SENDER)); } - map.from(templateProperties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) - .to(template::setReceiveTimeout); - map.from(templateProperties::getReplyTimeout).whenNonNull().as(Duration::toMillis) - .to(template::setReplyTimeout); + map.from(templateProperties::getReceiveTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(template::setReceiveTimeout); + map.from(templateProperties::getReplyTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(template::setReplyTimeout); map.from(templateProperties::getExchange).to(template::setExchange); map.from(templateProperties::getRoutingKey).to(template::setRoutingKey); map.from(templateProperties::getDefaultReceiveQueue).whenNonNull().to(template::setDefaultReceiveQueue); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java index b063015921..2779f91547 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/RetryTemplateFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,10 @@ class RetryTemplateFactory { map.from(properties::getMaxAttempts).to(policy::setMaxAttempts); template.setRetryPolicy(policy); ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy(); - map.from(properties::getInitialInterval).whenNonNull().as(Duration::toMillis) - .to(backOffPolicy::setInitialInterval); + map.from(properties::getInitialInterval) + .whenNonNull() + .as(Duration::toMillis) + .to(backOffPolicy::setInitialInterval); map.from(properties::getMultiplier).to(backOffPolicy::setMultiplier); map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis).to(backOffPolicy::setMaxInterval); template.setBackOffPolicy(backOffPolicy); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java index 1f95bd5dcd..32520c14db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -210,7 +210,8 @@ public class JobLauncherApplicationRunner implements ApplicationRunner, Ordered, return jobParameters; } JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.jobExplorer) - .getNextJobParameters(job).toJobParameters(); + .getNextJobParameters(job) + .toJobParameters(); return merge(nextParameters, jobParameters); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java index c50f4fea13..7dd7bc930b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,8 @@ public class CacheManagerCustomizers { @SuppressWarnings("unchecked") public T customize(T cacheManager) { LambdaSafe.callbacks(CacheManagerCustomizer.class, this.customizers, cacheManager) - .withLogger(CacheManagerCustomizers.class).invoke((customizer) -> customizer.customize(cacheManager)); + .withLogger(CacheManagerCustomizers.class) + .invoke((customizer) -> customizer.customize(cacheManager)); return cacheManager; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java index 25c035c54c..c4b4930f29 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CouchbaseCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ class CouchbaseCacheConfiguration { CouchbaseCacheManagerBuilder builder = CouchbaseCacheManager.builder(clientFactory); Couchbase couchbase = cacheProperties.getCouchbase(); org.springframework.data.couchbase.cache.CouchbaseCacheConfiguration config = org.springframework.data.couchbase.cache.CouchbaseCacheConfiguration - .defaultCacheConfig(); + .defaultCacheConfig(); if (couchbase.getExpiration() != null) { config = config.entryExpiry(couchbase.getExpiration()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java index c5e13aa513..07d9d3c402 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/JCacheCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -114,7 +114,7 @@ class JCacheCacheConfiguration implements BeanClassLoaderAware { ObjectProvider cachePropertiesCustomizers, CacheProperties cacheProperties) { Properties properties = new Properties(); cachePropertiesCustomizers.orderedStream() - .forEach((customizer) -> customizer.customize(cacheProperties, properties)); + .forEach((customizer) -> customizer.customize(cacheProperties, properties)); return properties; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java index 5e14f7daa1..ebd8ca33cf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/RedisCacheConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,9 @@ class RedisCacheConfiguration { ObjectProvider redisCacheConfiguration, ObjectProvider redisCacheManagerBuilderCustomizers, RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) { - RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults( - determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader())); + RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory) + .cacheDefaults( + determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader())); List cacheNames = cacheProperties.getCacheNames(); if (!cacheNames.isEmpty()) { builder.initialCacheNames(new LinkedHashSet<>(cacheNames)); @@ -81,9 +82,9 @@ class RedisCacheConfiguration { CacheProperties cacheProperties, ClassLoader classLoader) { Redis redisProperties = cacheProperties.getRedis(); org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration - .defaultCacheConfig(); - config = config.serializeValuesWith( - SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader))); + .defaultCacheConfig(); + config = config + .serializeValuesWith(SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader))); if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java index 377f50139b..89d290d13b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -151,77 +151,91 @@ public class CassandraAutoConfiguration { private Config mapConfig(CassandraProperties properties) { CassandraDriverOptions options = new CassandraDriverOptions(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(properties.getSessionName()).whenHasText() - .to((sessionName) -> options.add(DefaultDriverOption.SESSION_NAME, sessionName)); + map.from(properties.getSessionName()) + .whenHasText() + .to((sessionName) -> options.add(DefaultDriverOption.SESSION_NAME, sessionName)); map.from(properties::getUsername) - .to((username) -> options.add(DefaultDriverOption.AUTH_PROVIDER_USER_NAME, username) - .add(DefaultDriverOption.AUTH_PROVIDER_PASSWORD, properties.getPassword())); + .to((username) -> options.add(DefaultDriverOption.AUTH_PROVIDER_USER_NAME, username) + .add(DefaultDriverOption.AUTH_PROVIDER_PASSWORD, properties.getPassword())); map.from(properties::getCompression) - .to((compression) -> options.add(DefaultDriverOption.PROTOCOL_COMPRESSION, compression)); + .to((compression) -> options.add(DefaultDriverOption.PROTOCOL_COMPRESSION, compression)); mapConnectionOptions(properties, options); mapPoolingOptions(properties, options); mapRequestOptions(properties, options); mapControlConnectionOptions(properties, options); map.from(mapContactPoints(properties)) - .to((contactPoints) -> options.add(DefaultDriverOption.CONTACT_POINTS, contactPoints)); - map.from(properties.getLocalDatacenter()).whenHasText().to( - (localDatacenter) -> options.add(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, localDatacenter)); + .to((contactPoints) -> options.add(DefaultDriverOption.CONTACT_POINTS, contactPoints)); + map.from(properties.getLocalDatacenter()) + .whenHasText() + .to((localDatacenter) -> options.add(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, localDatacenter)); return options.build(); } private void mapConnectionOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Connection connectionProperties = properties.getConnection(); - map.from(connectionProperties::getConnectTimeout).asInt(Duration::toMillis) - .to((connectTimeout) -> options.add(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT, connectTimeout)); - map.from(connectionProperties::getInitQueryTimeout).asInt(Duration::toMillis).to( - (initQueryTimeout) -> options.add(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, initQueryTimeout)); + map.from(connectionProperties::getConnectTimeout) + .asInt(Duration::toMillis) + .to((connectTimeout) -> options.add(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT, connectTimeout)); + map.from(connectionProperties::getInitQueryTimeout) + .asInt(Duration::toMillis) + .to((initQueryTimeout) -> options.add(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, initQueryTimeout)); } private void mapPoolingOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); CassandraProperties.Pool poolProperties = properties.getPool(); - map.from(poolProperties::getIdleTimeout).asInt(Duration::toMillis) - .to((idleTimeout) -> options.add(DefaultDriverOption.HEARTBEAT_TIMEOUT, idleTimeout)); - map.from(poolProperties::getHeartbeatInterval).asInt(Duration::toMillis) - .to((heartBeatInterval) -> options.add(DefaultDriverOption.HEARTBEAT_INTERVAL, heartBeatInterval)); + map.from(poolProperties::getIdleTimeout) + .asInt(Duration::toMillis) + .to((idleTimeout) -> options.add(DefaultDriverOption.HEARTBEAT_TIMEOUT, idleTimeout)); + map.from(poolProperties::getHeartbeatInterval) + .asInt(Duration::toMillis) + .to((heartBeatInterval) -> options.add(DefaultDriverOption.HEARTBEAT_INTERVAL, heartBeatInterval)); } private void mapRequestOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Request requestProperties = properties.getRequest(); - map.from(requestProperties::getTimeout).asInt(Duration::toMillis) - .to(((timeout) -> options.add(DefaultDriverOption.REQUEST_TIMEOUT, timeout))); + map.from(requestProperties::getTimeout) + .asInt(Duration::toMillis) + .to(((timeout) -> options.add(DefaultDriverOption.REQUEST_TIMEOUT, timeout))); map.from(requestProperties::getConsistency) - .to(((consistency) -> options.add(DefaultDriverOption.REQUEST_CONSISTENCY, consistency))); - map.from(requestProperties::getSerialConsistency).to( - (serialConsistency) -> options.add(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY, serialConsistency)); + .to(((consistency) -> options.add(DefaultDriverOption.REQUEST_CONSISTENCY, consistency))); + map.from(requestProperties::getSerialConsistency) + .to((serialConsistency) -> options.add(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY, serialConsistency)); map.from(requestProperties::getPageSize) - .to((pageSize) -> options.add(DefaultDriverOption.REQUEST_PAGE_SIZE, pageSize)); + .to((pageSize) -> options.add(DefaultDriverOption.REQUEST_PAGE_SIZE, pageSize)); Throttler throttlerProperties = requestProperties.getThrottler(); - map.from(throttlerProperties::getType).as(ThrottlerType::type) - .to((type) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_CLASS, type)); + map.from(throttlerProperties::getType) + .as(ThrottlerType::type) + .to((type) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_CLASS, type)); map.from(throttlerProperties::getMaxQueueSize) - .to((maxQueueSize) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE, maxQueueSize)); - map.from(throttlerProperties::getMaxConcurrentRequests).to((maxConcurrentRequests) -> options - .add(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS, maxConcurrentRequests)); - map.from(throttlerProperties::getMaxRequestsPerSecond).to((maxRequestsPerSecond) -> options - .add(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND, maxRequestsPerSecond)); - map.from(throttlerProperties::getDrainInterval).asInt(Duration::toMillis).to( - (drainInterval) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL, drainInterval)); + .to((maxQueueSize) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE, maxQueueSize)); + map.from(throttlerProperties::getMaxConcurrentRequests) + .to((maxConcurrentRequests) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS, + maxConcurrentRequests)); + map.from(throttlerProperties::getMaxRequestsPerSecond) + .to((maxRequestsPerSecond) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND, + maxRequestsPerSecond)); + map.from(throttlerProperties::getDrainInterval) + .asInt(Duration::toMillis) + .to((drainInterval) -> options.add(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL, drainInterval)); } private void mapControlConnectionOptions(CassandraProperties properties, CassandraDriverOptions options) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); Controlconnection controlProperties = properties.getControlconnection(); - map.from(controlProperties::getTimeout).asInt(Duration::toMillis) - .to((timeout) -> options.add(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT, timeout)); + map.from(controlProperties::getTimeout) + .asInt(Duration::toMillis) + .to((timeout) -> options.add(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT, timeout)); } private List mapContactPoints(CassandraProperties properties) { if (properties.getContactPoints() != null) { - return properties.getContactPoints().stream() - .map((candidate) -> formatContactPoint(candidate, properties.getPort())).toList(); + return properties.getContactPoints() + .stream() + .map((candidate) -> formatContactPoint(candidate, properties.getPort())) + .toList(); } return null; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java index 2b615cb74b..1a317b0b5f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -167,7 +167,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition implem List getMatchOutcomes() { List outcomes = new ArrayList<>(); this.memberConditions.forEach((metadata, conditions) -> outcomes - .add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome())); + .add(new MemberOutcomes(this.context, metadata, conditions).getUltimateOutcome())); return Collections.unmodifiableList(outcomes); } @@ -199,7 +199,7 @@ public abstract class AbstractNestedCondition extends SpringBootCondition implem ConditionOutcome getUltimateOutcome() { ConditionMessage.Builder message = ConditionMessage - .forCondition("NestedCondition on " + ClassUtils.getShortName(this.metadata.getClassName())); + .forCondition("NestedCondition on " + ClassUtils.getShortName(this.metadata.getClassName())); if (this.outcomes.size() == 1) { ConditionOutcome outcome = this.outcomes.get(0); return new ConditionOutcome(outcome.isMatch(), message.because(outcome.getMessage())); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java index 58ae16d276..93e88c306e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AllNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -62,8 +62,9 @@ public abstract class AllNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = hasSameSize(memberOutcomes.getMatches(), memberOutcomes.getAll()); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("AllNestedConditions").because( - memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AllNestedConditions") + .because(memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java index ede56389ad..1c37ed0236 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AnyNestedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -65,8 +65,9 @@ public abstract class AnyNestedCondition extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = !memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("AnyNestedCondition").because( - memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("AnyNestedCondition") + .because(memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java index a7b1410dce..4a945908f2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -127,7 +127,7 @@ public final class ConditionEvaluationReport { this.outcomes.forEach((candidateSource, sourceOutcomes) -> { if (candidateSource.startsWith(prefix)) { ConditionOutcome outcome = ConditionOutcome - .noMatch(ConditionMessage.forCondition("Ancestor " + source).because("did not match")); + .noMatch(ConditionMessage.forCondition("Ancestor " + source).because("did not match")); sourceOutcomes.add(ANCESTOR_CONDITION, outcome); } }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java index 43997cddb3..c0e89e3316 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/NoneNestedConditions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -62,8 +62,9 @@ public abstract class NoneNestedConditions extends AbstractNestedCondition { protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) { boolean match = memberOutcomes.getMatches().isEmpty(); List messages = new ArrayList<>(); - messages.add(ConditionMessage.forCondition("NoneNestedConditions").because( - memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + " did not")); + messages.add(ConditionMessage.forCondition("NoneNestedConditions") + .because(memberOutcomes.getMatches().size() + " matched " + memberOutcomes.getNonMatches().size() + + " did not")); for (ConditionOutcome outcome : memberOutcomes.getAll()) { messages.add(outcome.getConditionMessage()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java index ed9e7c47f4..3e79e96fff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -104,7 +104,8 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat List missing = filter(requiredBeanTypes, ClassNameFilter.MISSING, getBeanClassLoader()); if (!missing.isEmpty()) { ConditionMessage message = ConditionMessage.forCondition(annotation) - .didNotFind("required type", "required types").items(Style.QUOTE, missing); + .didNotFind("required type", "required types") + .items(Style.QUOTE, missing); return ConditionOutcome.noMatch(message); } return null; @@ -121,8 +122,9 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat String reason = createOnBeanNoMatchReason(matchResult); return ConditionOutcome.noMatch(spec.message().because(reason)); } - matchMessage = spec.message(matchMessage).found("bean", "beans").items(Style.QUOTE, - matchResult.getNamesOfAllMatches()); + matchMessage = spec.message(matchMessage) + .found("bean", "beans") + .items(Style.QUOTE, matchResult.getNamesOfAllMatches()); } if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) { Spec spec = new SingleCandidateSpec(context, metadata, annotations); @@ -138,16 +140,16 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat List primaryBeans = getPrimaryBeans(context.getBeanFactory(), allBeans, spec.getStrategy() == SearchStrategy.ALL); if (primaryBeans.isEmpty()) { - return ConditionOutcome.noMatch( - spec.message().didNotFind("a primary bean from beans").items(Style.QUOTE, allBeans)); + return ConditionOutcome + .noMatch(spec.message().didNotFind("a primary bean from beans").items(Style.QUOTE, allBeans)); } if (primaryBeans.size() > 1) { return ConditionOutcome - .noMatch(spec.message().found("multiple primary beans").items(Style.QUOTE, primaryBeans)); + .noMatch(spec.message().found("multiple primary beans").items(Style.QUOTE, primaryBeans)); } matchMessage = spec.message(matchMessage) - .found("a single primary bean '" + primaryBeans.get(0) + "' from beans") - .items(Style.QUOTE, allBeans); + .found("a single primary bean '" + primaryBeans.get(0) + "' from beans") + .items(Style.QUOTE, allBeans); } } if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) { @@ -418,8 +420,8 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat Spec(ConditionContext context, AnnotatedTypeMetadata metadata, MergedAnnotations annotations, Class annotationType) { MultiValueMap attributes = annotations.stream(annotationType) - .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) - .collect(MergedAnnotationCollectors.toMultiValueMap(Adapt.CLASS_TO_STRING)); + .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) + .collect(MergedAnnotationCollectors.toMultiValueMap(Adapt.CLASS_TO_STRING)); MergedAnnotation annotation = annotations.get(annotationType); this.classLoader = context.getClassLoader(); this.annotationType = annotationType; @@ -567,7 +569,7 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat private boolean isBeanMethod(Method method) { return method != null && MergedAnnotations.from(method, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY) - .isPresent(Bean.class); + .isPresent(Bean.class); } private SearchStrategy getStrategy() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java index bdaef4590f..9841bf802e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -89,22 +89,24 @@ class OnClassCondition extends FilteringSpringBootCondition { List missing = filter(onClasses, ClassNameFilter.MISSING, classLoader); if (!missing.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) - .didNotFind("required class", "required classes").items(Style.QUOTE, missing)); + .didNotFind("required class", "required classes") + .items(Style.QUOTE, missing)); } matchMessage = matchMessage.andCondition(ConditionalOnClass.class) - .found("required class", "required classes") - .items(Style.QUOTE, filter(onClasses, ClassNameFilter.PRESENT, classLoader)); + .found("required class", "required classes") + .items(Style.QUOTE, filter(onClasses, ClassNameFilter.PRESENT, classLoader)); } List onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class); if (onMissingClasses != null) { List present = filter(onMissingClasses, ClassNameFilter.PRESENT, classLoader); if (!present.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingClass.class) - .found("unwanted class", "unwanted classes").items(Style.QUOTE, present)); + .found("unwanted class", "unwanted classes") + .items(Style.QUOTE, present)); } matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class) - .didNotFind("unwanted class", "unwanted classes") - .items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING, classLoader)); + .didNotFind("unwanted class", "unwanted classes") + .items(Style.QUOTE, filter(onMissingClasses, ClassNameFilter.MISSING, classLoader)); } return ConditionOutcome.match(matchMessage); } @@ -220,7 +222,8 @@ class OnClassCondition extends FilteringSpringBootCondition { private ConditionOutcome getOutcome(String className, ClassLoader classLoader) { if (ClassNameFilter.MISSING.matches(className, classLoader)) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class) - .didNotFind("required class").items(Style.QUOTE, className)); + .didNotFind("required class") + .items(Style.QUOTE, className)); } return null; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java index 703eca8244..860db28957 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnExpressionCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ class OnExpressionCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String expression = (String) metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName()) - .get("value"); + .get("value"); expression = wrapIfNecessary(expression); ConditionMessage.Builder messageBuilder = ConditionMessage.forCondition(ConditionalOnExpression.class, "(" + expression + ")"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java index 4b5b33a435..de58f03fd1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJavaCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ class OnJavaCondition extends SpringBootCondition { boolean match = isWithin(runningVersion, range, version); String expected = String.format((range != Range.EQUAL_OR_NEWER) ? "(older than %s)" : "(%s or newer)", version); ConditionMessage message = ConditionMessage.forCondition(ConditionalOnJava.class, expected) - .foundExactly(runningVersion); + .foundExactly(runningVersion); return new ConditionOutcome(match, message); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java index 55c3ccc3c0..ac7fcdc28c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnJndiCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,35 +40,36 @@ class OnJndiCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { AnnotationAttributes annotationAttributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); + .fromMap(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())); String[] locations = annotationAttributes.getStringArray("value"); try { return getMatchOutcome(locations); } catch (NoClassDefFoundError ex) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).because("JNDI class not found")); } } private ConditionOutcome getMatchOutcome(String[] locations) { if (!isJndiAvailable()) { return ConditionOutcome - .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment")); + .noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class).notAvailable("JNDI environment")); } if (locations.length == 0) { return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment")); + .match(ConditionMessage.forCondition(ConditionalOnJndi.class).available("JNDI environment")); } JndiLocator locator = getJndiLocator(locations); String location = locator.lookupFirstLocation(); String details = "(" + StringUtils.arrayToCommaDelimitedString(locations) + ")"; if (location != null) { return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .foundExactly("\"" + location + "\"")); + .foundExactly("\"" + location + "\"")); } return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnJndi.class, details) - .didNotFind("any matching JNDI location").atAll()); + .didNotFind("any matching JNDI location") + .atAll()); } protected boolean isJndiAvailable() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java index fe9773a417..5af58096ed 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnPropertyCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,9 +48,10 @@ class OnPropertyCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { List allAnnotationAttributes = metadata.getAnnotations() - .stream(ConditionalOnProperty.class.getName()) - .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) - .map(MergedAnnotation::asAnnotationAttributes).toList(); + .stream(ConditionalOnProperty.class.getName()) + .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getMetaTypes)) + .map(MergedAnnotation::asAnnotationAttributes) + .toList(); List noMatch = new ArrayList<>(); List match = new ArrayList<>(); for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) { @@ -70,15 +71,16 @@ class OnPropertyCondition extends SpringBootCondition { spec.collectProperties(resolver, missingProperties, nonMatchingProperties); if (!missingProperties.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .didNotFind("property", "properties").items(Style.QUOTE, missingProperties)); + .didNotFind("property", "properties") + .items(Style.QUOTE, missingProperties)); } if (!nonMatchingProperties.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec) - .found("different value in property", "different value in properties") - .items(Style.QUOTE, nonMatchingProperties)); + .found("different value in property", "different value in properties") + .items(Style.QUOTE, nonMatchingProperties)); } return ConditionOutcome - .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched")); + .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched")); } private static class Spec { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java index 2d79a87c77..16faa3ecb0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ class OnResourceCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { MultiValueMap attributes = metadata - .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true); + .getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true); ResourceLoader loader = context.getResourceLoader(); List locations = new ArrayList<>(); collectValues(locations, attributes.get("resources")); @@ -56,10 +56,12 @@ class OnResourceCondition extends SpringBootCondition { } if (!missing.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnResource.class) - .didNotFind("resource", "resources").items(Style.QUOTE, missing)); + .didNotFind("resource", "resources") + .items(Style.QUOTE, missing)); } return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnResource.class) - .found("location", "locations").items(locations)); + .found("location", "locations") + .items(locations)); } private void collectValues(List names, List values) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java index fb0e5388d2..568756350e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class OnWarDeploymentCondition extends SpringBootCondition { } } return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnWarDeployment.class) - .because("the application is not deployed as a WAR file.")); + .because("the application is not deployed as a WAR file.")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java index acb578357d..a4461fee80 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -80,8 +80,8 @@ public abstract class ResourceCondition extends SpringBootCondition { } } if (found.isEmpty()) { - ConditionMessage message = startConditionMessage().didNotFind("resource", "resources").items(Style.QUOTE, - Arrays.asList(this.resourceLocations)); + ConditionMessage message = startConditionMessage().didNotFind("resource", "resources") + .items(Style.QUOTE, Arrays.asList(this.resourceLocations)); return ConditionOutcome.noMatch(message); } ConditionMessage message = startConditionMessage().found("resource", "resources").items(Style.QUOTE, found); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java index 6db09ae38a..fbe0f22969 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -101,8 +101,8 @@ public abstract class SpringBootCondition implements Condition { private void recordEvaluation(ConditionContext context, String classOrMethodName, ConditionOutcome outcome) { if (context.getBeanFactory() != null) { - ConditionEvaluationReport.get(context.getBeanFactory()).recordConditionEvaluation(classOrMethodName, this, - outcome); + ConditionEvaluationReport.get(context.getBeanFactory()) + .recordConditionEvaluation(classOrMethodName, this, outcome); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java index 34ca52a8c7..ed306db988 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,7 @@ public class MessageSourceAutoConfiguration { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); if (StringUtils.hasText(properties.getBasename())) { messageSource.setBasenames(StringUtils - .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); + .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); } if (properties.getEncoding() != null) { messageSource.setDefaultEncoding(properties.getEncoding().name()); @@ -116,7 +116,7 @@ public class MessageSourceAutoConfiguration { String target = name.replace('.', '/'); try { return new PathMatchingResourcePatternResolver(classLoader) - .getResources("classpath*:" + target + ".properties"); + .getResources("classpath*:" + target + ".properties"); } catch (Exception ex) { return NO_RESOURCES; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java index 76800e3f13..11d8575e44 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,7 +73,7 @@ public class CouchbaseAutoConfiguration { @ConditionalOnMissingBean public Cluster couchbaseCluster(CouchbaseProperties properties, ClusterEnvironment couchbaseClusterEnvironment) { ClusterOptions options = ClusterOptions.clusterOptions(properties.getUsername(), properties.getPassword()) - .environment(couchbaseClusterEnvironment); + .environment(couchbaseClusterEnvironment); return Cluster.connect(properties.getConnectionString(), options); } @@ -81,16 +81,21 @@ public class CouchbaseAutoConfiguration { ClusterEnvironment.Builder builder = ClusterEnvironment.builder(); Timeouts timeouts = properties.getEnv().getTimeouts(); builder.timeoutConfig((config) -> config.kvTimeout(timeouts.getKeyValue()) - .analyticsTimeout(timeouts.getAnalytics()).kvDurableTimeout(timeouts.getKeyValueDurable()) - .queryTimeout(timeouts.getQuery()).viewTimeout(timeouts.getView()).searchTimeout(timeouts.getSearch()) - .managementTimeout(timeouts.getManagement()).connectTimeout(timeouts.getConnect()) - .disconnectTimeout(timeouts.getDisconnect())); + .analyticsTimeout(timeouts.getAnalytics()) + .kvDurableTimeout(timeouts.getKeyValueDurable()) + .queryTimeout(timeouts.getQuery()) + .viewTimeout(timeouts.getView()) + .searchTimeout(timeouts.getSearch()) + .managementTimeout(timeouts.getManagement()) + .connectTimeout(timeouts.getConnect()) + .disconnectTimeout(timeouts.getDisconnect())); CouchbaseProperties.Io io = properties.getEnv().getIo(); builder.ioConfig((config) -> config.maxHttpConnections(io.getMaxEndpoints()) - .numKvConnections(io.getMinEndpoints()).idleHttpConnectionTimeout(io.getIdleHttpConnectionTimeout())); + .numKvConnections(io.getMinEndpoints()) + .idleHttpConnectionTimeout(io.getIdleHttpConnectionTimeout())); if (properties.getEnv().getSsl().getEnabled()) { builder.securityConfig((config) -> config.enableTls(true) - .trustManagerFactory(getTrustManagerFactory(properties.getEnv().getSsl()))); + .trustManagerFactory(getTrustManagerFactory(properties.getEnv().getSsl()))); } return builder; } @@ -99,7 +104,7 @@ public class CouchbaseAutoConfiguration { String resource = ssl.getKeyStore(); try { TrustManagerFactory trustManagerFactory = TrustManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = loadKeyStore(resource, ssl.getKeyStorePassword()); trustManagerFactory.init(keyStore); return trustManagerFactory; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java index 4900574a29..7f988f52af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/OnRepositoryTypeCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class OnRepositoryTypeCondition extends SpringBootCondition { ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnRepositoryType.class); if (configuredType == requiredType || configuredType == RepositoryType.AUTO) { return ConditionOutcome - .match(message.because("configured type of '" + configuredType.name() + "' matched required type")); + .match(message.because("configured type of '" + configuredType.name() + "' matched required type")); } return ConditionOutcome.noMatch(message.because("configured type (" + configuredType.name() + ") did not match required type (" + requiredType.name() + ")")); @@ -51,8 +51,8 @@ class OnRepositoryTypeCondition extends SpringBootCondition { private RepositoryType getTypeProperty(Environment environment, String store) { return RepositoryType - .valueOf(environment.getProperty(String.format("spring.data.%s.repositories.type", store), "auto") - .toUpperCase(Locale.ENGLISH)); + .valueOf(environment.getProperty(String.format("spring.data.%s.repositories.type", store), "auto") + .toUpperCase(Locale.ENGLISH)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java index 1661384ca2..20826c607b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class CouchbaseDataConfiguration { Class fieldNamingStrategy = properties.getFieldNamingStrategy(); if (fieldNamingStrategy != null) { mappingContext - .setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(fieldNamingStrategy)); + .setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(fieldNamingStrategy)); } mappingContext.setAutoIndexCreation(properties.isAutoIndex()); return mappingContext; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java index 7bbcee4d81..ab13a3fe67 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -148,7 +148,7 @@ class LettuceConnectionConfiguration extends RedisConnectionConfiguration { ClusterClientOptions.Builder builder = ClusterClientOptions.builder(); Refresh refreshProperties = getProperties().getLettuce().getCluster().getRefresh(); Builder refreshBuilder = ClusterTopologyRefreshOptions.builder() - .dynamicRefreshSources(refreshProperties.isDynamicRefreshSources()); + .dynamicRefreshSources(refreshProperties.isDynamicRefreshSources()); if (refreshProperties.getPeriod() != null) { refreshBuilder.enablePeriodicRefresh(refreshProperties.getPeriod()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java index 5046671c00..9f2cb6ee3c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,8 +51,12 @@ public class RedisReactiveAutoConfiguration { JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer( resourceLoader.getClassLoader()); RedisSerializationContext serializationContext = RedisSerializationContext - .newSerializationContext().key(jdkSerializer).value(jdkSerializer).hashKey(jdkSerializer) - .hashValue(jdkSerializer).build(); + .newSerializationContext() + .key(jdkSerializer) + .value(jdkSerializer) + .hashKey(jdkSerializer) + .hashValue(jdkSerializer) + .build(); return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, serializationContext); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java index 07249d917a..10d5f21596 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -134,9 +134,9 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz } String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, type); return Arrays.stream(beanNames) - .map((beanName) -> new UserConfigurationResult(getFactoryMethodMetadata(beanName), - this.beanFactory.getBean(beanName).equals(null))) - .toList(); + .map((beanName) -> new UserConfigurationResult(getFactoryMethodMetadata(beanName), + this.beanFactory.getBean(beanName).equals(null))) + .toList(); } private MethodMetadata getFactoryMethodMetadata(String beanName) { @@ -150,8 +150,8 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, List results) { this.report.getConditionAndOutcomesBySource() - .forEach((source, sourceOutcomes) -> collectReportedConditionOutcomes(cause, new Source(source), - sourceOutcomes, results)); + .forEach((source, sourceOutcomes) -> collectReportedConditionOutcomes(cause, new Source(source), + sourceOutcomes, results)); } private void collectReportedConditionOutcomes(NoSuchBeanDefinitionException cause, Source source, @@ -224,9 +224,9 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz private List findBeanMethods(Source source, NoSuchBeanDefinitionException cause) { try { MetadataReader classMetadata = NoSuchBeanDefinitionFailureAnalyzer.this.metadataReaderFactory - .getMetadataReader(source.getClassName()); + .getMetadataReader(source.getClassName()); Set candidates = classMetadata.getAnnotationMetadata() - .getAnnotatedMethods(Bean.class.getName()); + .getAnnotatedMethods(Bean.class.getName()); List result = new ArrayList<>(); for (MethodMetadata candidate : candidates) { if (isMatch(candidate, source, cause)) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java index e0c27c2cf1..b947aad3bd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/domain/EntityScanPackages.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -112,7 +112,7 @@ public class EntityScanPackages { Assert.notNull(packageNames, "PackageNames must not be null"); if (registry.containsBeanDefinition(BEAN)) { EntityScanPackagesBeanDefinition beanDefinition = (EntityScanPackagesBeanDefinition) registry - .getBeanDefinition(BEAN); + .getBeanDefinition(BEAN); beanDefinition.addPackageNames(packageNames); } else { @@ -139,7 +139,7 @@ public class EntityScanPackages { private Set getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(EntityScan.class.getName())); + .fromMap(metadata.getAnnotationAttributes(EntityScan.class.getName())); Set packagesToScan = new LinkedHashSet<>(); for (String basePackage : attributes.getStringArray("basePackages")) { String[] tokenized = StringUtils.tokenizeToStringArray( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java index 24b197d6ab..93ef387e35 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientConfigurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -100,7 +100,8 @@ class ElasticsearchRestClientConfigurations { } try { return HttpHost.create(new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), - uri.getQuery(), uri.getFragment()).toString()); + uri.getQuery(), uri.getFragment()) + .toString()); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); @@ -156,16 +157,21 @@ class ElasticsearchRestClientConfigurations { @Override public void customize(HttpAsyncClientBuilder builder) { builder.setDefaultCredentialsProvider(new PropertiesCredentialsProvider(this.properties)); - map.from(this.properties::isSocketKeepAlive).to((keepAlive) -> builder + map.from(this.properties::isSocketKeepAlive) + .to((keepAlive) -> builder .setDefaultIOReactorConfig(IOReactorConfig.custom().setSoKeepAlive(keepAlive).build())); } @Override public void customize(RequestConfig.Builder builder) { - map.from(this.properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis) - .to(builder::setConnectTimeout); - map.from(this.properties::getSocketTimeout).whenNonNull().asInt(Duration::toMillis) - .to(builder::setSocketTimeout); + map.from(this.properties::getConnectionTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(builder::setConnectTimeout); + map.from(this.properties::getSocketTimeout) + .whenNonNull() + .asInt(Duration::toMillis) + .to(builder::setSocketTimeout); } } @@ -178,8 +184,11 @@ class ElasticsearchRestClientConfigurations { properties.getPassword()); setCredentials(AuthScope.ANY, credentials); } - properties.getUris().stream().map(this::toUri).filter(this::hasUserInfo) - .forEach(this::addUserInfoCredentials); + properties.getUris() + .stream() + .map(this::toUri) + .filter(this::hasUserInfo) + .forEach(this::addUserInfoCredentials); } private URI toUri(String uri) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java index 4b76b0fe06..b24d89f202 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -163,7 +163,7 @@ public class FlywayAutoConfiguration { } if (properties.getUser() != null && dataSource != null) { DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource) - .type(SimpleDriverDataSource.class); + .type(SimpleDriverDataSource.class); applyCommonBuilderProperties(properties, builder); return builder.build(); } @@ -182,13 +182,16 @@ public class FlywayAutoConfiguration { private void configureProperties(FluentConfiguration configuration, FlywayProperties properties) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); String[] locations = new LocationResolver(configuration.getDataSource()) - .resolveLocations(properties.getLocations()).toArray(new String[0]); + .resolveLocations(properties.getLocations()) + .toArray(new String[0]); map.from(properties.isFailOnMissingLocations()).to(configuration::failOnMissingLocations); map.from(locations).to(configuration::locations); map.from(properties.getEncoding()).to(configuration::encoding); map.from(properties.getConnectRetries()).to(configuration::connectRetries); - map.from(properties.getConnectRetriesInterval()).as(Duration::getSeconds).as(Long::intValue) - .to(configuration::connectRetriesInterval); + map.from(properties.getConnectRetriesInterval()) + .as(Duration::getSeconds) + .as(Long::intValue) + .to(configuration::connectRetriesInterval); map.from(properties.getLockRetryCount()).to(configuration::lockRetryCount); map.from(properties.getDefaultSchema()).to(configuration::defaultSchema); map.from(properties.getSchemas()).as(StringUtils::toStringArray).to(configuration::schemas); @@ -204,8 +207,9 @@ public class FlywayAutoConfiguration { map.from(properties.getPlaceholderSeparator()).to(configuration::placeholderSeparator); map.from(properties.isPlaceholderReplacement()).to(configuration::placeholderReplacement); map.from(properties.getSqlMigrationPrefix()).to(configuration::sqlMigrationPrefix); - map.from(properties.getSqlMigrationSuffixes()).as(StringUtils::toStringArray) - .to(configuration::sqlMigrationSuffixes); + map.from(properties.getSqlMigrationSuffixes()) + .as(StringUtils::toStringArray) + .to(configuration::sqlMigrationSuffixes); map.from(properties.getSqlMigrationSeparator()).to(configuration::sqlMigrationSeparator); map.from(properties.getRepeatableSqlMigrationPrefix()).to(configuration::repeatableSqlMigrationPrefix); map.from(properties.getTarget()).to(configuration::target); @@ -219,13 +223,14 @@ public class FlywayAutoConfiguration { map.from(properties.isSkipDefaultResolvers()).to(configuration::skipDefaultResolvers); map.from(properties.isValidateMigrationNaming()).to(configuration::validateMigrationNaming); map.from(properties.isValidateOnMigrate()).to(configuration::validateOnMigrate); - map.from(properties.getInitSqls()).whenNot(CollectionUtils::isEmpty) - .as((initSqls) -> StringUtils.collectionToDelimitedString(initSqls, "\n")) - .to(configuration::initSql); + map.from(properties.getInitSqls()) + .whenNot(CollectionUtils::isEmpty) + .as((initSqls) -> StringUtils.collectionToDelimitedString(initSqls, "\n")) + .to(configuration::initSql); map.from(properties.getScriptPlaceholderPrefix()) - .to((prefix) -> configuration.scriptPlaceholderPrefix(prefix)); + .to((prefix) -> configuration.scriptPlaceholderPrefix(prefix)); map.from(properties.getScriptPlaceholderSuffix()) - .to((suffix) -> configuration.scriptPlaceholderSuffix(suffix)); + .to((suffix) -> configuration.scriptPlaceholderSuffix(suffix)); // Flyway Teams properties map.from(properties.getBatch()).to(configuration::batch); map.from(properties.getDryRunOutput()).to(configuration::dryRunOutput); @@ -240,19 +245,22 @@ public class FlywayAutoConfiguration { map.from(properties.getKerberosConfigFile()).to(configuration::kerberosConfigFile); map.from(properties.getOracleKerberosCacheFile()).to(configuration::oracleKerberosCacheFile); map.from(properties.getOutputQueryResults()).to(configuration::outputQueryResults); - map.from(properties.getSqlServerKerberosLoginFile()).whenNonNull() - .to((sqlServerKerberosLoginFile) -> configureSqlServerKerberosLoginFile(configuration, - sqlServerKerberosLoginFile)); + map.from(properties.getSqlServerKerberosLoginFile()) + .whenNonNull() + .to((sqlServerKerberosLoginFile) -> configureSqlServerKerberosLoginFile(configuration, + sqlServerKerberosLoginFile)); map.from(properties.getSkipExecutingMigrations()).to(configuration::skipExecutingMigrations); - map.from(properties.getIgnoreMigrationPatterns()).whenNot(List::isEmpty) - .as((patterns) -> patterns.toArray(new String[0])).to(configuration::ignoreMigrationPatterns); + map.from(properties.getIgnoreMigrationPatterns()) + .whenNot(List::isEmpty) + .as((patterns) -> patterns.toArray(new String[0])) + .to(configuration::ignoreMigrationPatterns); map.from(properties.getDetectEncoding()).to(configuration::detectEncoding); } private void configureSqlServerKerberosLoginFile(FluentConfiguration configuration, String sqlServerKerberosLoginFile) { SQLServerConfigurationExtension sqlServerConfigurationExtension = configuration.getPluginRegister() - .getPlugin(SQLServerConfigurationExtension.class); + .getPlugin(SQLServerConfigurationExtension.class); Assert.state(sqlServerConfigurationExtension != null, "Flyway SQL Server extension missing"); sqlServerConfigurationExtension.setKerberosLoginFile(sqlServerKerberosLoginFile); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java index 210bfb3b23..45300bef41 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywaySchemaManagementProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,8 +42,11 @@ class FlywaySchemaManagementProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { return StreamSupport.stream(this.flywayInstances.spliterator(), false) - .map((flyway) -> flyway.getConfiguration().getDataSource()).filter(dataSource::equals).findFirst() - .map((managedDataSource) -> SchemaManagement.MANAGED).orElse(SchemaManagement.UNMANAGED); + .map((flyway) -> flyway.getConfiguration().getDataSource()) + .filter(dataSource::equals) + .findFirst() + .map((managedDataSource) -> SchemaManagement.MANAGED) + .orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/NativeImageResourceProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/NativeImageResourceProvider.java index 37baef8637..63678acf90 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/NativeImageResourceProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/NativeImageResourceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -95,11 +95,13 @@ class NativeImageResourceProvider implements ResourceProvider { } ensureInitialized(); Predicate matchesPrefixAndSuffixes = (locatedResource) -> StringUtils - .startsAndEndsWith(locatedResource.resource.getFilename(), prefix, suffixes); + .startsAndEndsWith(locatedResource.resource.getFilename(), prefix, suffixes); List result = new ArrayList<>(); result.addAll(this.scanner.getResources(prefix, suffixes)); - this.locatedResources.stream().filter(matchesPrefixAndSuffixes).map(this::asClassPathResource) - .forEach(result::add); + this.locatedResources.stream() + .filter(matchesPrefixAndSuffixes) + .map(this::asClassPathResource) + .forEach(result::add); return result; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessor.java index 140c8468a8..919cfd3f4e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class ResourceProviderCustomizerBeanRegistrationAotProcessor implements BeanRegi public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { if (registeredBean.getBeanClass().equals(ResourceProviderCustomizer.class)) { return BeanRegistrationAotContribution - .withCustomCodeFragments((codeFragments) -> new AotContribution(codeFragments, registeredBean)); + .withCustomCodeFragments((codeFragments) -> new AotContribution(codeFragments, registeredBean)); } return null; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java index 53d3f1f0da..77ead8392c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,9 +60,9 @@ class DefaultGraphQlSchemaCondition extends SpringBootCondition implements Confi ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnGraphQlSchema.class); Binder binder = Binder.get(context.getEnvironment()); GraphQlProperties.Schema schema = binder.bind("spring.graphql.schema", GraphQlProperties.Schema.class) - .orElse(new GraphQlProperties.Schema()); + .orElse(new GraphQlProperties.Schema()); ResourcePatternResolver resourcePatternResolver = ResourcePatternUtils - .getResourcePatternResolver(context.getResourceLoader()); + .getResourcePatternResolver(context.getResourceLoader()); List schemaResources = resolveSchemaResources(resourcePatternResolver, schema.getLocations(), schema.getFileExtensions()); if (!schemaResources.isEmpty()) { @@ -70,8 +70,8 @@ class DefaultGraphQlSchemaCondition extends SpringBootCondition implements Confi messages.add(message.found("schema", "schemas").items(ConditionMessage.Style.QUOTE, schemaResources)); } else { - messages.add(message.didNotFind("schema files in locations").items(ConditionMessage.Style.QUOTE, - Arrays.asList(schema.getLocations()))); + messages.add(message.didNotFind("schema files in locations") + .items(ConditionMessage.Style.QUOTE, Arrays.asList(schema.getLocations()))); } ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); String[] customizerBeans = beanFactory.getBeanNamesForType(GraphQlSourceBuilderCustomizer.class, false, false); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java index 3a580a7d2b..e38602eda7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,9 +87,10 @@ public class GraphQlAutoConfiguration { Resource[] schemaResources = resolveSchemaResources(resourcePatternResolver, schemaLocations, properties.getSchema().getFileExtensions()); GraphQlSource.SchemaResourceBuilder builder = GraphQlSource.schemaResourceBuilder() - .schemaResources(schemaResources).exceptionResolvers(exceptionResolvers.orderedStream().toList()) - .subscriptionExceptionResolvers(subscriptionExceptionResolvers.orderedStream().toList()) - .instrumentation(instrumentations.orderedStream().toList()); + .schemaResources(schemaResources) + .exceptionResolvers(exceptionResolvers.orderedStream().toList()) + .subscriptionExceptionResolvers(subscriptionExceptionResolvers.orderedStream().toList()) + .instrumentation(instrumentations.orderedStream().toList()); if (!properties.getSchema().getIntrospection().isEnabled()) { builder.configureRuntimeWiring(this::enableIntrospection); } @@ -143,7 +144,7 @@ public class GraphQlAutoConfiguration { public AnnotatedControllerConfigurer annotatedControllerConfigurer() { AnnotatedControllerConfigurer controllerConfigurer = new AnnotatedControllerConfigurer(); controllerConfigurer - .addFormatterRegistrar((registry) -> ApplicationConversionService.addBeans(registry, this.beanFactory)); + .addFormatterRegistrar((registry) -> ApplicationConversionService.addBeans(registry, this.beanFactory)); return controllerConfigurer; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java index 504ab540b2..1ea766a8be 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/GraphQlProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -100,8 +100,9 @@ public class GraphQlProperties { } private String[] appendSlashIfNecessary(String[] locations) { - return Arrays.stream(locations).map((location) -> location.endsWith("/") ? location : location + "/") - .toArray(String[]::new); + return Arrays.stream(locations) + .map((location) -> location.endsWith("/") ? location : location + "/") + .toArray(String[]::new); } public Introspection getIntrospection() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java index 9f5323d87b..af590733e2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,8 @@ public class GraphQlWebFluxAutoConfiguration { @SuppressWarnings("removal") private static final RequestPredicate SUPPORTS_MEDIATYPES = accept(MediaType.APPLICATION_GRAPHQL_RESPONSE, - MediaType.APPLICATION_JSON, MediaType.APPLICATION_GRAPHQL).and(contentType(MediaType.APPLICATION_JSON)); + MediaType.APPLICATION_JSON, MediaType.APPLICATION_GRAPHQL) + .and(contentType(MediaType.APPLICATION_JSON)); private static final Log logger = LogFactory.getLog(GraphQlWebFluxAutoConfiguration.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java index 3151e0bb90..29d0c53c24 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -114,7 +114,7 @@ public class GraphQlWebMvcAutoConfiguration { RouterFunctions.Builder builder = RouterFunctions.route(); builder = builder.GET(path, this::onlyAllowPost); builder = builder.POST(path, RequestPredicates.contentType(MediaType.APPLICATION_JSON) - .and(RequestPredicates.accept(SUPPORTED_MEDIA_TYPES)), httpHandler::handleRequest); + .and(RequestPredicates.accept(SUPPORTED_MEDIA_TYPES)), httpHandler::handleRequest); if (properties.getGraphiql().isEnabled()) { GraphiQlHandler graphiQLHandler = new GraphiQlHandler(path, properties.getWebsocket().getPath()); builder = builder.GET(properties.getGraphiql().getPath(), graphiQLHandler::handleRequest); @@ -170,9 +170,12 @@ public class GraphQlWebMvcAutoConfiguration { } private GenericHttpMessageConverter getJsonConverter(HttpMessageConverters converters) { - return converters.getConverters().stream().filter(this::canReadJsonMap).findFirst() - .map(this::asGenericHttpMessageConverter) - .orElseThrow(() -> new IllegalStateException("No JSON converter")); + return converters.getConverters() + .stream() + .filter(this::canReadJsonMap) + .findFirst() + .map(this::asGenericHttpMessageConverter) + .orElseThrow(() -> new IllegalStateException("No JSON converter")); } private boolean canReadJsonMap(HttpMessageConverter candidate) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java index d3c0d8b480..4fd3f99778 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -80,7 +80,7 @@ public class GsonAutoConfiguration { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties::getGenerateNonExecutableJson).toCall(builder::generateNonExecutableJson); map.from(properties::getExcludeFieldsWithoutExposeAnnotation) - .toCall(builder::excludeFieldsWithoutExposeAnnotation); + .toCall(builder::excludeFieldsWithoutExposeAnnotation); map.from(properties::getSerializeNulls).whenTrue().toCall(builder::serializeNulls); map.from(properties::getEnableComplexMapKeySerialization).toCall(builder::enableComplexMapKeySerialization); map.from(properties::getDisableInnerClassSerialization).toCall(builder::disableInnerClassSerialization); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java index 06d35d8cbe..2260e6f612 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastClientConfigAvailableCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class HazelcastClientConfigAvailableCondition extends HazelcastConfigResourceCon ConditionOutcome configValidationOutcome = HazelcastClientValidation.clientConfigOutcome(context, HAZELCAST_CONFIG_PROPERTY, startConditionMessage()); return (configValidationOutcome != null) ? configValidationOutcome : ConditionOutcome - .match(startConditionMessage().foundExactly("property " + HAZELCAST_CONFIG_PROPERTY)); + .match(startConditionMessage().foundExactly("property " + HAZELCAST_CONFIG_PROPERTY)); } return getResourceOutcome(context, metadata); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java index 359810d591..af5054c9eb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastConfigResourceCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -48,8 +48,8 @@ public abstract class HazelcastConfigResourceCondition extends ResourceCondition @Override protected ConditionOutcome getResourceOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { if (System.getProperty(this.configSystemProperty) != null) { - return ConditionOutcome.match( - startConditionMessage().because("System property '" + this.configSystemProperty + "' is set.")); + return ConditionOutcome + .match(startConditionMessage().because("System property '" + this.configSystemProperty + "' is set.")); } return super.getResourceOutcome(context, metadata); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java index 901db8ce0b..b8f7038971 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,8 +79,10 @@ public class CodecsAutoConfiguration { PropertyMapper map = PropertyMapper.get(); CodecConfigurer.DefaultCodecs defaultCodecs = configurer.defaultCodecs(); defaultCodecs.enableLoggingRequestDetails(codecProperties.isLogRequestDetails()); - map.from(codecProperties.getMaxInMemorySize()).whenNonNull().asInt(DataSize::toBytes) - .to(defaultCodecs::maxInMemorySize); + map.from(codecProperties.getMaxInMemorySize()) + .whenNonNull() + .asInt(DataSize::toBytes) + .to(defaultCodecs::maxInMemorySize); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java index c5f7832186..9ca2706b61 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -95,18 +95,20 @@ public class IntegrationAutoConfiguration { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties.getChannel().isAutoCreate()).to(integrationProperties::setChannelsAutoCreate); map.from(properties.getChannel().getMaxUnicastSubscribers()) - .to(integrationProperties::setChannelsMaxUnicastSubscribers); + .to(integrationProperties::setChannelsMaxUnicastSubscribers); map.from(properties.getChannel().getMaxBroadcastSubscribers()) - .to(integrationProperties::setChannelsMaxBroadcastSubscribers); + .to(integrationProperties::setChannelsMaxBroadcastSubscribers); map.from(properties.getError().isRequireSubscribers()) - .to(integrationProperties::setErrorChannelRequireSubscribers); + .to(integrationProperties::setErrorChannelRequireSubscribers); map.from(properties.getError().isIgnoreFailures()).to(integrationProperties::setErrorChannelIgnoreFailures); map.from(properties.getEndpoint().isThrowExceptionOnLateReply()) - .to(integrationProperties::setMessagingTemplateThrowExceptionOnLateReply); - map.from(properties.getEndpoint().getReadOnlyHeaders()).as(StringUtils::toStringArray) - .to(integrationProperties::setReadOnlyHeaders); - map.from(properties.getEndpoint().getNoAutoStartup()).as(StringUtils::toStringArray) - .to(integrationProperties::setNoAutoStartupEndpoints); + .to(integrationProperties::setMessagingTemplateThrowExceptionOnLateReply); + map.from(properties.getEndpoint().getReadOnlyHeaders()) + .as(StringUtils::toStringArray) + .to(integrationProperties::setReadOnlyHeaders); + map.from(properties.getEndpoint().getNoAutoStartup()) + .as(StringUtils::toStringArray) + .to(integrationProperties::setNoAutoStartupEndpoints); return integrationProperties; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java index 3ed91d7a50..a4e2657270 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -60,7 +60,8 @@ class IntegrationPropertiesEnvironmentPostProcessor implements EnvironmentPostPr PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader(); try { OriginTrackedMapPropertySource propertyFileSource = (OriginTrackedMapPropertySource) loader - .load("META-INF/spring.integration.properties", resource).get(0); + .load("META-INF/spring.integration.properties", resource) + .get(0); environment.getPropertySources().addLast(new IntegrationPropertiesPropertySource(propertyFileSource)); } catch (IOException ex) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java index dde97c57b4..a6aa97773e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -361,8 +361,9 @@ public class JacksonAutoConfiguration { } private void registerPropertyNamingStrategyHints(ReflectionHints hints, Class type) { - Stream.of(type.getDeclaredFields()).filter(this::isPropertyNamingStrategyField) - .forEach(hints::registerField); + Stream.of(type.getDeclaredFields()) + .filter(this::isPropertyNamingStrategyField) + .forEach(hints::registerField); } private boolean isPropertyNamingStrategyField(Field candidate) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java index 19e6449bf2..4b271537ae 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceBeanCreationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,14 +66,16 @@ class DataSourceBeanCreationFailureAnalyzer extends AbstractFailureAnalyzer initializeDataSourceBuilder() { - return DataSourceBuilder.create(getClassLoader()).type(getType()).driverClassName(determineDriverClassName()) - .url(determineUrl()).username(determineUsername()).password(determinePassword()); + return DataSourceBuilder.create(getClassLoader()) + .type(getType()) + .driverClassName(determineDriverClassName()) + .url(determineUrl()) + .username(determineUsername()) + .password(determinePassword()); } public boolean isGenerateUniqueName() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java index 1229335836..aba988c5d7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/EmbeddedDataSourceConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,8 @@ public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware { @Bean(destroyMethod = "shutdown") public EmbeddedDatabase dataSource(DataSourceProperties properties) { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseConnection.get(this.classLoader).getType()) - .setName(properties.determineDatabaseName()).build(); + .setName(properties.determineDatabaseName()) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java index b2bc678a32..e256a0a63d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -91,12 +91,16 @@ public class JmsAutoConfiguration { map.from(properties::getDefaultDestination).whenNonNull().to(template::setDefaultDestinationName); map.from(properties::getDeliveryDelay).whenNonNull().as(Duration::toMillis).to(template::setDeliveryDelay); map.from(properties::determineQosEnabled).to(template::setExplicitQosEnabled); - map.from(properties::getDeliveryMode).whenNonNull().as(DeliveryMode::getValue) - .to(template::setDeliveryMode); + map.from(properties::getDeliveryMode) + .whenNonNull() + .as(DeliveryMode::getValue) + .to(template::setDeliveryMode); map.from(properties::getPriority).whenNonNull().to(template::setPriority); map.from(properties::getTimeToLive).whenNonNull().as(Duration::toMillis).to(template::setTimeToLive); - map.from(properties::getReceiveTimeout).whenNonNull().as(Duration::toMillis) - .to(template::setReceiveTimeout); + map.from(properties::getReceiveTimeout) + .whenNonNull() + .as(Duration::toMillis) + .to(template::setReceiveTimeout); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java index 2939a4ebe1..40bff93c3e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/JmsPoolConnectionFactoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ public class JmsPoolConnectionFactoryFactory { pooledConnectionFactory.setBlockIfSessionPoolIsFull(this.properties.isBlockIfFull()); if (this.properties.getBlockIfFullTimeout() != null) { pooledConnectionFactory - .setBlockIfSessionPoolIsFullTimeout(this.properties.getBlockIfFullTimeout().toMillis()); + .setBlockIfSessionPoolIsFullTimeout(this.properties.getBlockIfFullTimeout().toMillis()); } if (this.properties.getIdleTimeout() != null) { pooledConnectionFactory.setConnectionIdleTimeout((int) this.properties.getIdleTimeout().toMillis()); @@ -56,7 +56,7 @@ public class JmsPoolConnectionFactoryFactory { pooledConnectionFactory.setMaxSessionsPerConnection(this.properties.getMaxSessionsPerConnection()); if (this.properties.getTimeBetweenExpirationCheck() != null) { pooledConnectionFactory - .setConnectionCheckInterval(this.properties.getTimeBetweenExpirationCheck().toMillis()); + .setConnectionCheckInterval(this.properties.getTimeBetweenExpirationCheck().toMillis()); } pooledConnectionFactory.setUseAnonymousProducers(this.properties.isUseAnonymousProducers()); return pooledConnectionFactory; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java index 7215984843..580383d865 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -77,7 +77,7 @@ class ArtemisConnectionFactoryConfiguration { private ActiveMQConnectionFactory createConnectionFactory() { return new ArtemisConnectionFactoryFactory(this.beanFactory, this.properties) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); } } @@ -90,9 +90,9 @@ class ArtemisConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") JmsPoolConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties) { ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQConnectionFactory.class); + .createConnectionFactory(ActiveMQConnectionFactory.class); return new JmsPoolConnectionFactoryFactory(properties.getPool()) - .createPooledConnectionFactory(connectionFactory); + .createPooledConnectionFactory(connectionFactory); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java index 812cfc01dc..ee5aca3498 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,13 +71,14 @@ class ArtemisEmbeddedConfigurationFactory { configuration.addAddressConfiguration(createAddressConfiguration("ExpiryQueue")); configuration.addAddressSetting("#", new AddressSettings().setDeadLetterAddress(SimpleString.toSimpleString("DLQ")) - .setExpiryAddress(SimpleString.toSimpleString("ExpiryQueue"))); + .setExpiryAddress(SimpleString.toSimpleString("ExpiryQueue"))); return configuration; } private CoreAddressConfiguration createAddressConfiguration(String name) { - return new CoreAddressConfiguration().setName(name).addRoutingType(RoutingType.ANYCAST).addQueueConfiguration( - new QueueConfiguration(name).setRoutingType(RoutingType.ANYCAST).setAddress(name)); + return new CoreAddressConfiguration().setName(name) + .addRoutingType(RoutingType.ANYCAST) + .addQueueConfiguration(new QueueConfiguration(name).setRoutingType(RoutingType.ANYCAST).setAddress(name)); } private String getDataDir() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java index 49f1b19a5d..6517739b6f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedServerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,15 +66,16 @@ class ArtemisEmbeddedServerConfiguration { ObjectProvider configurationCustomizers) { for (JMSQueueConfiguration queueConfiguration : jmsConfiguration.getQueueConfigurations()) { String queueName = queueConfiguration.getName(); - configuration.addAddressConfiguration( - new CoreAddressConfiguration().setName(queueName).addRoutingType(RoutingType.ANYCAST) - .addQueueConfiguration(new QueueConfiguration(queueName).setAddress(queueName) - .setFilterString(queueConfiguration.getSelector()) - .setDurable(queueConfiguration.isDurable()).setRoutingType(RoutingType.ANYCAST))); + configuration.addAddressConfiguration(new CoreAddressConfiguration().setName(queueName) + .addRoutingType(RoutingType.ANYCAST) + .addQueueConfiguration(new QueueConfiguration(queueName).setAddress(queueName) + .setFilterString(queueConfiguration.getSelector()) + .setDurable(queueConfiguration.isDurable()) + .setRoutingType(RoutingType.ANYCAST))); } for (TopicConfiguration topicConfiguration : jmsConfiguration.getTopicConfigurations()) { configuration.addAddressConfiguration(new CoreAddressConfiguration().setName(topicConfiguration.getName()) - .addRoutingType(RoutingType.MULTICAST)); + .addRoutingType(RoutingType.MULTICAST)); } configurationCustomizers.orderedStream().forEach((customizer) -> customizer.customize(configuration)); EmbeddedActiveMQ embeddedActiveMq = new EmbeddedActiveMQ(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java index d8a8b8118e..b296ae14b8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisXAConnectionFactoryConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,14 +46,14 @@ class ArtemisXAConnectionFactoryConfiguration { ConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties, XAConnectionFactoryWrapper wrapper) throws Exception { return wrapper.wrapConnectionFactory(new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQXAConnectionFactory.class)); + .createConnectionFactory(ActiveMQXAConnectionFactory.class)); } @Bean ActiveMQXAConnectionFactory nonXaJmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties) { return new ArtemisConnectionFactoryFactory(beanFactory, properties) - .createConnectionFactory(ActiveMQXAConnectionFactory.class); + .createConnectionFactory(ActiveMQXAConnectionFactory.class); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java index f5d0bea002..c8c866df53 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/ConcurrentKafkaListenerContainerFactoryConfigurer.java @@ -186,10 +186,13 @@ public class ConcurrentKafkaListenerContainerFactoryConfigurer { map.from(properties::getNoPollThreshold).to(container::setNoPollThreshold); map.from(properties.getIdleBetweenPolls()).as(Duration::toMillis).to(container::setIdleBetweenPolls); map.from(properties::getIdleEventInterval).as(Duration::toMillis).to(container::setIdleEventInterval); - map.from(properties::getIdlePartitionEventInterval).as(Duration::toMillis) - .to(container::setIdlePartitionEventInterval); - map.from(properties::getMonitorInterval).as(Duration::getSeconds).as(Number::intValue) - .to(container::setMonitorInterval); + map.from(properties::getIdlePartitionEventInterval) + .as(Duration::toMillis) + .to(container::setIdlePartitionEventInterval); + map.from(properties::getMonitorInterval) + .as(Duration::getSeconds) + .as(Number::intValue) + .to(container::setMonitorInterval); map.from(properties::getLogContainerConfig).to(container::setLogContainerConfig); map.from(properties::isMissingTopicsFatal).to(container::setMissingTopicsFatal); map.from(properties::isImmediateStop).to(container::setStopImmediate); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java index 4a8d091769..515829f429 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.java @@ -81,7 +81,7 @@ class KafkaAnnotationDrivenConfiguration { this.recordMessageConverter = recordMessageConverter.getIfUnique(); this.recordFilterStrategy = recordFilterStrategy.getIfUnique(); this.batchMessageConverter = batchMessageConverter - .getIfUnique(() -> new BatchMessagingMessageConverter(this.recordMessageConverter)); + .getIfUnique(() -> new BatchMessagingMessageConverter(this.recordMessageConverter)); this.kafkaTemplate = kafkaTemplate.getIfUnique(); this.transactionManager = kafkaTransactionManager.getIfUnique(); this.rebalanceListener = rebalanceListener.getIfUnique(); @@ -114,7 +114,7 @@ class KafkaAnnotationDrivenConfiguration { ObjectProvider> kafkaConsumerFactory) { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); configurer.configure(factory, kafkaConsumerFactory - .getIfAvailable(() -> new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()))); + .getIfAvailable(() -> new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()))); return factory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java index d1ed7c855c..a063d05f12 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -152,8 +152,10 @@ public class KafkaAutoConfiguration { public RetryTopicConfiguration kafkaRetryTopicConfiguration(KafkaTemplate kafkaTemplate) { KafkaProperties.Retry.Topic retryTopic = this.properties.getRetry().getTopic(); RetryTopicConfigurationBuilder builder = RetryTopicConfigurationBuilder.newInstance() - .maxAttempts(retryTopic.getAttempts()).useSingleTopicForFixedDelays().suffixTopicsWithIndexValues() - .doNotAutoCreateRetryTopics(); + .maxAttempts(retryTopic.getAttempts()) + .useSingleTopicForFixedDelays() + .suffixTopicsWithIndexValues() + .doNotAutoCreateRetryTopics(); setBackOffPolicy(builder, retryTopic); return builder.create(kafkaTemplate); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java index 2714d01b72..9a92951d5d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/kafka/KafkaProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -428,21 +428,25 @@ public class KafkaProperties { public Map buildProperties() { Properties properties = new Properties(); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(this::getAutoCommitInterval).asInt(Duration::toMillis) - .to(properties.in(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)); + map.from(this::getAutoCommitInterval) + .asInt(Duration::toMillis) + .to(properties.in(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG)); map.from(this::getAutoOffsetReset).to(properties.in(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); map.from(this::getBootstrapServers).to(properties.in(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)); map.from(this::getClientId).to(properties.in(ConsumerConfig.CLIENT_ID_CONFIG)); map.from(this::getEnableAutoCommit).to(properties.in(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)); - map.from(this::getFetchMaxWait).asInt(Duration::toMillis) - .to(properties.in(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)); - map.from(this::getFetchMinSize).asInt(DataSize::toBytes) - .to(properties.in(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)); + map.from(this::getFetchMaxWait) + .asInt(Duration::toMillis) + .to(properties.in(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG)); + map.from(this::getFetchMinSize) + .asInt(DataSize::toBytes) + .to(properties.in(ConsumerConfig.FETCH_MIN_BYTES_CONFIG)); map.from(this::getGroupId).to(properties.in(ConsumerConfig.GROUP_ID_CONFIG)); - map.from(this::getHeartbeatInterval).asInt(Duration::toMillis) - .to(properties.in(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)); + map.from(this::getHeartbeatInterval) + .asInt(Duration::toMillis) + .to(properties.in(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG)); map.from(() -> getIsolationLevel().name().toLowerCase(Locale.ROOT)) - .to(properties.in(ConsumerConfig.ISOLATION_LEVEL_CONFIG)); + .to(properties.in(ConsumerConfig.ISOLATION_LEVEL_CONFIG)); map.from(this::getKeyDeserializer).to(properties.in(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)); map.from(this::getValueDeserializer).to(properties.in(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)); map.from(this::getMaxPollRecords).to(properties.in(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)); @@ -614,8 +618,9 @@ public class KafkaProperties { map.from(this::getAcks).to(properties.in(ProducerConfig.ACKS_CONFIG)); map.from(this::getBatchSize).asInt(DataSize::toBytes).to(properties.in(ProducerConfig.BATCH_SIZE_CONFIG)); map.from(this::getBootstrapServers).to(properties.in(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)); - map.from(this::getBufferMemory).as(DataSize::toBytes) - .to(properties.in(ProducerConfig.BUFFER_MEMORY_CONFIG)); + map.from(this::getBufferMemory) + .as(DataSize::toBytes) + .to(properties.in(ProducerConfig.BUFFER_MEMORY_CONFIG)); map.from(this::getClientId).to(properties.in(ProducerConfig.CLIENT_ID_CONFIG)); map.from(this::getCompressionType).to(properties.in(ProducerConfig.COMPRESSION_TYPE_CONFIG)); map.from(this::getKeySerializer).to(properties.in(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)); @@ -827,8 +832,9 @@ public class KafkaProperties { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this::getApplicationId).to(properties.in("application.id")); map.from(this::getBootstrapServers).to(properties.in(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG)); - map.from(this::getCacheMaxSizeBuffering).asInt(DataSize::toBytes) - .to(properties.in("cache.max.bytes.buffering")); + map.from(this::getCacheMaxSizeBuffering) + .asInt(DataSize::toBytes) + .to(properties.in("cache.max.bytes.buffering")); map.from(this::getClientId).to(properties.in(CommonClientConfigs.CLIENT_ID_CONFIG)); map.from(this::getReplicationFactor).to(properties.in("replication.factor")); map.from(this::getStateDir).to(properties.in("state.dir")); @@ -1253,15 +1259,17 @@ public class KafkaProperties { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(this::getKeyPassword).to(properties.in(SslConfigs.SSL_KEY_PASSWORD_CONFIG)); map.from(this::getKeyStoreCertificateChain) - .to(properties.in(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG)); + .to(properties.in(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG)); map.from(this::getKeyStoreKey).to(properties.in(SslConfigs.SSL_KEYSTORE_KEY_CONFIG)); - map.from(this::getKeyStoreLocation).as(this::resourceToPath) - .to(properties.in(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)); + map.from(this::getKeyStoreLocation) + .as(this::resourceToPath) + .to(properties.in(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)); map.from(this::getKeyStorePassword).to(properties.in(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG)); map.from(this::getKeyStoreType).to(properties.in(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG)); map.from(this::getTrustStoreCertificates).to(properties.in(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG)); - map.from(this::getTrustStoreLocation).as(this::resourceToPath) - .to(properties.in(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)); + map.from(this::getTrustStoreLocation) + .as(this::resourceToPath) + .to(properties.in(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)); map.from(this::getTrustStorePassword).to(properties.in(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG)); map.from(this::getTrustStoreType).to(properties.in(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG)); map.from(this::getProtocol).to(properties.in(SslConfigs.SSL_PROTOCOL_CONFIG)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java index 7ca7cb9b1c..0144f9bf99 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,8 +58,8 @@ public class LdapAutoConfiguration { propertyMapper.from(properties.getAnonymousReadOnly()).to(source::setAnonymousReadOnly); propertyMapper.from(properties.getBase()).to(source::setBase); propertyMapper.from(properties.determineUrls(environment)).to(source::setUrls); - propertyMapper.from(properties.getBaseEnvironment()).to( - (baseEnvironment) -> source.setBaseEnvironmentProperties(Collections.unmodifiableMap(baseEnvironment))); + propertyMapper.from(properties.getBaseEnvironment()) + .to((baseEnvironment) -> source.setBaseEnvironmentProperties(Collections.unmodifiableMap(baseEnvironment))); return source; } @@ -70,10 +70,10 @@ public class LdapAutoConfiguration { PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); LdapTemplate ldapTemplate = new LdapTemplate(contextSource); propertyMapper.from(template.isIgnorePartialResultException()) - .to(ldapTemplate::setIgnorePartialResultException); + .to(ldapTemplate::setIgnorePartialResultException); propertyMapper.from(template.isIgnoreNameNotFoundException()).to(ldapTemplate::setIgnoreNameNotFoundException); propertyMapper.from(template.isIgnoreSizeLimitExceededException()) - .to(ldapTemplate::setIgnoreSizeLimitExceededException); + .to(ldapTemplate::setIgnoreSizeLimitExceededException); return ldapTemplate; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java index 7f192fabbe..384d4ba0e9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -186,8 +186,10 @@ public class EmbeddedLdapAutoConfiguration { public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Builder message = ConditionMessage.forCondition("Embedded LDAP"); Environment environment = context.getEnvironment(); - if (environment != null && !Binder.get(environment).bind("spring.ldap.embedded.base-dn", STRING_LIST) - .orElseGet(Collections::emptyList).isEmpty()) { + if (environment != null && !Binder.get(environment) + .bind("spring.ldap.embedded.base-dn", STRING_LIST) + .orElseGet(Collections::emptyList) + .isEmpty()) { return ConditionOutcome.match(message.because("Found base-dn property")); } return ConditionOutcome.noMatch(message.because("No base-dn property found")); @@ -220,8 +222,8 @@ public class EmbeddedLdapAutoConfiguration { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - hints.resources().registerPatternIfPresent(classLoader, "schema.ldif", - (hint) -> hint.includes("schema.ldif")); + hints.resources() + .registerPatternIfPresent(classLoader, "schema.ldif", (hint) -> hint.includes("schema.ldif")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java index 8223ffb20d..c6b65c50e3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -135,7 +135,7 @@ public class LiquibaseAutoConfiguration { } if (properties.getUser() != null && dataSource != null) { DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource) - .type(SimpleDriverDataSource.class); + .type(SimpleDriverDataSource.class); applyCommonBuilderProperties(properties, builder); return builder.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java index a5ad86c64d..e6f8c00083 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseSchemaManagementProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,9 +42,12 @@ class LiquibaseSchemaManagementProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { - return StreamSupport.stream(this.liquibaseInstances.spliterator(), false).map(SpringLiquibase::getDataSource) - .filter(dataSource::equals).findFirst().map((managedDataSource) -> SchemaManagement.MANAGED) - .orElse(SchemaManagement.UNMANAGED); + return StreamSupport.stream(this.liquibaseInstances.spliterator(), false) + .map(SpringLiquibase::getDataSource) + .filter(dataSource::equals) + .findFirst() + .map((managedDataSource) -> SchemaManagement.MANAGED) + .orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessor.java index f6c62634b2..fecb81a04b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ class ConditionEvaluationReportLoggingProcessor implements BeanFactoryInitializa private void logConditionEvaluationReport(ConfigurableListableBeanFactory beanFactory) { new ConditionEvaluationReportLogger(LogLevel.DEBUG, () -> ConditionEvaluationReport.get(beanFactory)) - .logReport(false); + .logReport(false); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java index 76b2424eaf..c9d831c120 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,8 +70,10 @@ public class ConditionEvaluationReportMessage { private void logPositiveMatches(StringBuilder message, Map shortOutcomes) { message.append(String.format("Positive matches:%n")); message.append(String.format("-----------------%n")); - List> matched = shortOutcomes.entrySet().stream() - .filter((entry) -> entry.getValue().isFullMatch()).toList(); + List> matched = shortOutcomes.entrySet() + .stream() + .filter((entry) -> entry.getValue().isFullMatch()) + .toList(); if (matched.isEmpty()) { message.append(String.format("%n None%n")); } @@ -84,8 +86,10 @@ public class ConditionEvaluationReportMessage { private void logNegativeMatches(StringBuilder message, Map shortOutcomes) { message.append(String.format("Negative matches:%n")); message.append(String.format("-----------------%n")); - List> nonMatched = shortOutcomes.entrySet().stream() - .filter((entry) -> !entry.getValue().isFullMatch()).toList(); + List> nonMatched = shortOutcomes.entrySet() + .stream() + .filter((entry) -> !entry.getValue().isFullMatch()) + .toList(); if (nonMatched.isEmpty()) { message.append(String.format("%n None%n")); } @@ -130,8 +134,8 @@ public class ConditionEvaluationReportMessage { for (String shortName : shortNames) { List fullyQualifiedNames = map.get(shortName); if (fullyQualifiedNames.size() > 1) { - fullyQualifiedNames.forEach( - (fullyQualifiedName) -> result.put(fullyQualifiedName, outcomes.get(fullyQualifiedName))); + fullyQualifiedNames + .forEach((fullyQualifiedName) -> result.put(fullyQualifiedName, outcomes.get(fullyQualifiedName))); } else { result.put(shortName, outcomes.get(fullyQualifiedNames.get(0))); @@ -142,8 +146,8 @@ public class ConditionEvaluationReportMessage { private MultiValueMap mapToFullyQualifiedNames(Set keySet) { LinkedMultiValueMap map = new LinkedMultiValueMap<>(); - keySet.forEach( - (fullyQualifiedName) -> map.add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName)); + keySet + .forEach((fullyQualifiedName) -> map.add(ClassUtils.getShortName(fullyQualifiedName), fullyQualifiedName)); return map; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java index be841adec8..d45465ab4d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,9 @@ public abstract class MongoClientFactorySupport { } private MongoDriverInformation driverInformation() { - return MongoDriverInformation.builder(MongoDriverInformation.builder().build()).driverName("spring-boot") - .build(); + return MongoDriverInformation.builder(MongoDriverInformation.builder().build()) + .driverName("spring-boot") + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java index 2b4761bcca..31319fafee 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -107,8 +107,8 @@ public class MongoReactiveAutoConfiguration { if (!isStreamFactoryFactoryDefined(this.settings.getIfAvailable())) { NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); this.eventLoopGroup = eventLoopGroup; - builder.streamFactoryFactory( - NettyStreamFactoryFactory.builder().eventLoopGroup(eventLoopGroup).build()); + builder + .streamFactoryFactory(NettyStreamFactoryFactory.builder().eventLoopGroup(eventLoopGroup).build()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java index 272987b6c3..298a093f81 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,8 +84,8 @@ public class Neo4jAutoConfiguration { boolean hasKerberosTicket = StringUtils.hasText(kerberosTicket); if (hasUsername && hasKerberosTicket) { - throw new IllegalStateException(String.format( - "Cannot specify both username ('%s') and kerberos ticket ('%s')", username, kerberosTicket)); + throw new IllegalStateException(String + .format("Cannot specify both username ('%s') and kerberos ticket ('%s')", username, kerberosTicket)); } if (hasUsername && hasPassword) { return AuthTokens.basic(username, password, realm); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java index 3af26dac6e..aaef06de21 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -52,8 +52,10 @@ class HibernateDefaultDdlAutoProvider implements SchemaManagementProvider { @Override public SchemaManagement getSchemaManagement(DataSource dataSource) { return StreamSupport.stream(this.providers.spliterator(), false) - .map((provider) -> provider.getSchemaManagement(dataSource)).filter(SchemaManagement.MANAGED::equals) - .findFirst().orElse(SchemaManagement.UNMANAGED); + .map((provider) -> provider.getSchemaManagement(dataSource)) + .filter(SchemaManagement.MANAGED::equals) + .findFirst() + .orElse(SchemaManagement.UNMANAGED); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java index 26ad37b90e..acb9f3ceba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -112,8 +112,8 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { new SpringBeanContainer(beanFactory))); } if (physicalNamingStrategy != null || implicitNamingStrategy != null) { - customizers.add( - new NamingStrategiesHibernatePropertiesCustomizer(physicalNamingStrategy, implicitNamingStrategy)); + customizers + .add(new NamingStrategiesHibernatePropertiesCustomizer(physicalNamingStrategy, implicitNamingStrategy)); } customizers.addAll(hibernatePropertiesCustomizers); return customizers; @@ -127,9 +127,9 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration { @Override protected Map getVendorProperties() { Supplier defaultDdlMode = () -> this.defaultDdlAutoProvider.getDefaultDdlAuto(getDataSource()); - return new LinkedHashMap<>(this.hibernateProperties - .determineHibernateProperties(getProperties().getProperties(), new HibernateSettings() - .ddlAuto(defaultDdlMode).hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); + return new LinkedHashMap<>(this.hibernateProperties.determineHibernateProperties( + getProperties().getProperties(), new HibernateSettings().ddlAuto(defaultDdlMode) + .hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java index f3db19f9a6..0520ff0948 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -130,8 +130,12 @@ public abstract class JpaBaseConfiguration { PersistenceManagedTypes persistenceManagedTypes) { Map vendorProperties = getVendorProperties(); customizeVendorProperties(vendorProperties); - return factoryBuilder.dataSource(this.dataSource).managedTypes(persistenceManagedTypes) - .properties(vendorProperties).mappingResources(getMappingResources()).jta(isJta()).build(); + return factoryBuilder.dataSource(this.dataSource) + .managedTypes(persistenceManagedTypes) + .properties(vendorProperties) + .mappingResources(getMappingResources()) + .jta(isJta()) + .build(); } protected abstract AbstractJpaVendorAdapter createJpaVendorAdapter(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java index a71e05e27d..c2833a6b26 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryBeanCreationFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,8 +70,10 @@ class ConnectionFactoryBeanCreationFailureAnalyzer else { action.append(String.format("\tReview the configuration of %s%n.", cause.getEmbeddedDatabaseConnection())); } - action.append("\tIf you have database settings to be loaded from a particular " - + "profile you may need to activate it").append(getActiveProfiles()); + action + .append("\tIf you have database settings to be loaded from a particular " + + "profile you may need to activate it") + .append(getActiveProfiles()); return action.toString(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java index fb5161cebe..419af5ebf1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations.java @@ -58,13 +58,14 @@ abstract class ConnectionFactoryConfigurations { List optionsCustomizers) { try { return org.springframework.boot.r2dbc.ConnectionFactoryBuilder - .withOptions(new ConnectionFactoryOptionsInitializer().initialize(properties, - () -> EmbeddedDatabaseConnection.get(classLoader))) - .configure((options) -> { - for (ConnectionFactoryOptionsBuilderCustomizer optionsCustomizer : optionsCustomizers) { - optionsCustomizer.customize(options); - } - }).build(); + .withOptions(new ConnectionFactoryOptionsInitializer().initialize(properties, + () -> EmbeddedDatabaseConnection.get(classLoader))) + .configure((options) -> { + for (ConnectionFactoryOptionsBuilderCustomizer optionsCustomizer : optionsCustomizers) { + optionsCustomizer.customize(options); + } + }) + .build(); } catch (IllegalStateException ex) { String message = ex.getMessage(); @@ -134,8 +135,8 @@ abstract class ConnectionFactoryConfigurations { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { - BindResult pool = Binder.get(context.getEnvironment()).bind("spring.r2dbc.pool", - Bindable.of(Pool.class)); + BindResult pool = Binder.get(context.getEnvironment()) + .bind("spring.r2dbc.pool", Bindable.of(Pool.class)); if (hasPoolUrl(context.getEnvironment())) { if (pool.isBound()) { throw new MultipleConnectionPoolConfigurationsException(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java index 70bbb45ac0..b913a28db5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfiguration.java @@ -109,7 +109,7 @@ public class RSocketServerAutoConfiguration { RSocketServerCustomizer frameDecoderRSocketServerCustomizer(RSocketMessageHandler rSocketMessageHandler) { return (server) -> { if (rSocketMessageHandler.getRSocketStrategies() - .dataBufferFactory() instanceof NettyDataBufferFactory) { + .dataBufferFactory() instanceof NettyDataBufferFactory) { server.payloadDecoder(PayloadDecoder.ZERO_COPY); } }; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java index c6246d4c24..43e7ef93f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ClientsConfiguredCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -40,22 +40,25 @@ import org.springframework.core.type.AnnotatedTypeMetadata; public class ClientsConfiguredCondition extends SpringBootCondition { private static final Bindable> STRING_REGISTRATION_MAP = Bindable - .mapOf(String.class, OAuth2ClientProperties.Registration.class); + .mapOf(String.class, OAuth2ClientProperties.Registration.class); @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth2 Clients Configured Condition"); Map registrations = getRegistrations(context.getEnvironment()); if (!registrations.isEmpty()) { - return ConditionOutcome.match(message.foundExactly("registered clients " + registrations.values().stream() - .map(OAuth2ClientProperties.Registration::getClientId).collect(Collectors.joining(", ")))); + return ConditionOutcome.match(message.foundExactly("registered clients " + registrations.values() + .stream() + .map(OAuth2ClientProperties.Registration::getClientId) + .collect(Collectors.joining(", ")))); } return ConditionOutcome.noMatch(message.notAvailable("registered clients")); } private Map getRegistrations(Environment environment) { - return Binder.get(environment).bind("spring.security.oauth2.client.registration", STRING_REGISTRATION_MAP) - .orElse(Collections.emptyMap()); + return Binder.get(environment) + .bind("spring.security.oauth2.client.registration", STRING_REGISTRATION_MAP) + .orElse(Collections.emptyMap()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java index d1b9777675..905602259d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -49,8 +49,9 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { public static Map getClientRegistrations(OAuth2ClientProperties properties) { Map clientRegistrations = new HashMap<>(); - properties.getRegistration().forEach((key, value) -> clientRegistrations.put(key, - getClientRegistration(key, value, properties.getProvider()))); + properties.getRegistration() + .forEach((key, value) -> clientRegistrations.put(key, + getClientRegistration(key, value, properties.getProvider()))); return clientRegistrations; } @@ -63,10 +64,12 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(properties::getClientId).to(builder::clientId); map.from(properties::getClientSecret).to(builder::clientSecret); - map.from(properties::getClientAuthenticationMethod).as(ClientAuthenticationMethod::new) - .to(builder::clientAuthenticationMethod); - map.from(properties::getAuthorizationGrantType).as(AuthorizationGrantType::new) - .to(builder::authorizationGrantType); + map.from(properties::getClientAuthenticationMethod) + .as(ClientAuthenticationMethod::new) + .to(builder::clientAuthenticationMethod); + map.from(properties::getAuthorizationGrantType) + .as(AuthorizationGrantType::new) + .to(builder::authorizationGrantType); map.from(properties::getRedirectUri).to(builder::redirectUri); map.from(properties::getScope).as(StringUtils::toStringArray).to(builder::scope); map.from(properties::getClientName).to(builder::clientName); @@ -112,8 +115,9 @@ public final class OAuth2ClientPropertiesRegistrationAdapter { map.from(provider::getAuthorizationUri).to(builder::authorizationUri); map.from(provider::getTokenUri).to(builder::tokenUri); map.from(provider::getUserInfoUri).to(builder::userInfoUri); - map.from(provider::getUserInfoAuthenticationMethod).as(AuthenticationMethod::new) - .to(builder::userInfoAuthenticationMethod); + map.from(provider::getUserInfoAuthenticationMethod) + .as(AuthenticationMethod::new) + .to(builder::userInfoAuthenticationMethod); map.from(provider::getJwkSetUri).to(builder::jwkSetUri); map.from(provider::getUserNameAttribute).to(builder::userNameAttributeName); return builder; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java index 9f282187fc..90b5d71cb0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/KeyValueCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ public class KeyValueCondition extends SpringBootCondition { ConditionMessage.Builder message = ConditionMessage.forCondition("Public Key Value Condition"); Environment environment = context.getEnvironment(); String publicKeyLocation = environment - .getProperty("spring.security.oauth2.resourceserver.jwt.public-key-location"); + .getProperty("spring.security.oauth2.resourceserver.jwt.public-key-location"); if (!StringUtils.hasText(publicKeyLocation)) { return ConditionOutcome.noMatch(message.didNotFind("public-key-location property").atAll()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java index 715aa69dd2..edaf54d1ea 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerJwkConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,7 +79,9 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { @ConditionalOnProperty(name = "spring.security.oauth2.resourceserver.jwt.jwk-set-uri") ReactiveJwtDecoder jwtDecoder() { NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = NimbusReactiveJwtDecoder - .withJwkSetUri(this.properties.getJwkSetUri()).jwsAlgorithms(this::jwsAlgorithms).build(); + .withJwkSetUri(this.properties.getJwkSetUri()) + .jwsAlgorithms(this::jwsAlgorithms) + .build(); String issuerUri = this.properties.getIssuerUri(); Supplier> defaultValidator = (issuerUri != null) ? () -> JwtValidators.createDefaultWithIssuer(issuerUri) : JwtValidators::createDefault; @@ -110,9 +112,10 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { @Conditional(KeyValueCondition.class) NimbusReactiveJwtDecoder jwtDecoderByPublicKeyValue() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") - .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); + .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withPublicKey(publicKey) - .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())).build(); + .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())) + .build(); jwtDecoder.setJwtValidator(getValidators(JwtValidators::createDefault)); return jwtDecoder; } @@ -138,7 +141,7 @@ class ReactiveOAuth2ResourceServerJwkConfiguration { SupplierReactiveJwtDecoder jwtDecoderByIssuerUri() { return new SupplierReactiveJwtDecoder(() -> { NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder) ReactiveJwtDecoders - .fromIssuerLocation(this.properties.getIssuerUri()); + .fromIssuerLocation(this.properties.getIssuerUri()); jwtDecoder.setJwtValidator( getValidators(() -> JwtValidators.createDefaultWithIssuer(this.properties.getIssuerUri()))); return jwtDecoder; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java index c91bc34cb9..b03ac8212a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerJwtConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,7 +79,8 @@ class OAuth2ResourceServerJwtConfiguration { @ConditionalOnProperty(name = "spring.security.oauth2.resourceserver.jwt.jwk-set-uri") JwtDecoder jwtDecoderByJwkKeySetUri() { NimbusJwtDecoder nimbusJwtDecoder = NimbusJwtDecoder.withJwkSetUri(this.properties.getJwkSetUri()) - .jwsAlgorithms(this::jwsAlgorithms).build(); + .jwsAlgorithms(this::jwsAlgorithms) + .build(); String issuerUri = this.properties.getIssuerUri(); Supplier> defaultValidator = (issuerUri != null) ? () -> JwtValidators.createDefaultWithIssuer(issuerUri) : JwtValidators::createDefault; @@ -110,9 +111,10 @@ class OAuth2ResourceServerJwtConfiguration { @Conditional(KeyValueCondition.class) JwtDecoder jwtDecoderByPublicKeyValue() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") - .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); + .generatePublic(new X509EncodedKeySpec(getKeySpec(this.properties.readPublicKey()))); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(publicKey) - .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())).build(); + .signatureAlgorithm(SignatureAlgorithm.from(exactlyOneAlgorithm())) + .build(); jwtDecoder.setJwtValidator(getValidators(JwtValidators::createDefault)); return jwtDecoder; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java index c2dcd14d3c..1b8692bafd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ public class RSocketSecurityAutoConfiguration { @Bean RSocketMessageHandlerCustomizer rSocketAuthenticationPrincipalMessageHandlerCustomizer() { return (messageHandler) -> messageHandler.getArgumentResolverConfigurer() - .addCustomResolver(new AuthenticationPrincipalArgumentResolver()); + .addCustomResolver(new AuthenticationPrincipalArgumentResolver()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java index fa865639f1..837307fe35 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyRegistrationConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,8 +62,11 @@ class Saml2RelyingPartyRegistrationConfiguration { @Bean RelyingPartyRegistrationRepository relyingPartyRegistrationRepository(Saml2RelyingPartyProperties properties) { - List registrations = properties.getRegistration().entrySet().stream() - .map(this::asRegistration).toList(); + List registrations = properties.getRegistration() + .entrySet() + .stream() + .map(this::asRegistration) + .toList(); return new InMemoryRelyingPartyRegistrationRepository(registrations); } @@ -73,19 +76,30 @@ class Saml2RelyingPartyRegistrationConfiguration { private RelyingPartyRegistration asRegistration(String id, Registration properties) { boolean usingMetadata = StringUtils.hasText(properties.getAssertingparty().getMetadataUri()); - Builder builder = (usingMetadata) ? RelyingPartyRegistrations - .fromMetadataLocation(properties.getAssertingparty().getMetadataUri()).registrationId(id) + Builder builder = (usingMetadata) + ? RelyingPartyRegistrations.fromMetadataLocation(properties.getAssertingparty().getMetadataUri()) + .registrationId(id) : RelyingPartyRegistration.withRegistrationId(id); builder.assertionConsumerServiceLocation(properties.getAcs().getLocation()); builder.assertionConsumerServiceBinding(properties.getAcs().getBinding()); builder.assertingPartyDetails(mapAssertingParty(properties.getAssertingparty(), usingMetadata)); - builder.signingX509Credentials((credentials) -> properties.getSigning().getCredentials().stream() - .map(this::asSigningCredential).forEach(credentials::add)); - builder.decryptionX509Credentials((credentials) -> properties.getDecryption().getCredentials().stream() - .map(this::asDecryptionCredential).forEach(credentials::add)); - builder.assertingPartyDetails((details) -> details - .verificationX509Credentials((credentials) -> properties.getAssertingparty().getVerification() - .getCredentials().stream().map(this::asVerificationCredential).forEach(credentials::add))); + builder.signingX509Credentials((credentials) -> properties.getSigning() + .getCredentials() + .stream() + .map(this::asSigningCredential) + .forEach(credentials::add)); + builder.decryptionX509Credentials((credentials) -> properties.getDecryption() + .getCredentials() + .stream() + .map(this::asDecryptionCredential) + .forEach(credentials::add)); + builder.assertingPartyDetails( + (details) -> details.verificationX509Credentials((credentials) -> properties.getAssertingparty() + .getVerification() + .getCredentials() + .stream() + .map(this::asVerificationCredential) + .forEach(credentials::add))); builder.singleLogoutServiceLocation(properties.getSinglelogout().getUrl()); builder.singleLogoutServiceResponseLocation(properties.getSinglelogout().getResponseUrl()); builder.singleLogoutServiceBinding(properties.getSinglelogout().getBinding()); @@ -103,8 +117,9 @@ class Saml2RelyingPartyRegistrationConfiguration { map.from(assertingParty::getEntityId).to(details::entityId); map.from(assertingParty.getSinglesignon()::getBinding).to(details::singleSignOnServiceBinding); map.from(assertingParty.getSinglesignon()::getUrl).to(details::singleSignOnServiceLocation); - map.from(assertingParty.getSinglesignon()::isSignRequest).when((signRequest) -> !usingMetadata) - .to(details::wantAuthnRequestsSigned); + map.from(assertingParty.getSinglesignon()::isSignRequest) + .when((signRequest) -> !usingMetadata) + .to(details::wantAuthnRequestsSigned); map.from(assertingParty.getSinglelogout()::getUrl).to(details::singleLogoutServiceLocation); map.from(assertingParty.getSinglelogout()::getResponseUrl).to(details::singleLogoutServiceResponseLocation); map.from(assertingParty.getSinglelogout()::getBinding).to(details::singleLogoutServiceBinding); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java index 72f8142b22..a9318f2f2f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/SecurityFilterAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,9 +69,11 @@ public class SecurityFilterAutoConfiguration { if (securityProperties.getFilter().getDispatcherTypes() == null) { return null; } - return securityProperties.getFilter().getDispatcherTypes().stream() - .map((type) -> DispatcherType.valueOf(type.name())) - .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); + return securityProperties.getFilter() + .getDispatcherTypes() + .stream() + .map((type) -> DispatcherType.valueOf(type.name())) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java index 3b53dacddf..13d6cf9268 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -140,8 +140,9 @@ public final class StaticResourceRequest { } private Stream getPatterns(DispatcherServletPath dispatcherServletPath) { - return this.locations.stream().flatMap(StaticResourceLocation::getPatterns) - .map(dispatcherServletPath::getRelativePath); + return this.locations.stream() + .flatMap(StaticResourceLocation::getPatterns) + .map(dispatcherServletPath::getRelativePath); } @Override diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java index e88643a038..55c3dec9a6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -75,9 +75,10 @@ public class UserDetailsServiceAutoConfiguration { ObjectProvider passwordEncoder) { SecurityProperties.User user = properties.getUser(); List roles = user.getRoles(); - return new InMemoryUserDetailsManager( - User.withUsername(user.getName()).password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())) - .roles(StringUtils.toStringArray(roles)).build()); + return new InMemoryUserDetailsManager(User.withUsername(user.getName()) + .password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())) + .roles(StringUtils.toStringArray(roles)) + .build()); } private String getOrDeducePassword(SecurityProperties.User user, PasswordEncoder encoder) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java index 108da8ac47..ed568e8b83 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/HazelcastSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ class HazelcastSessionConfiguration { return (sessionRepository) -> { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(sessionProperties.determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout())) - .to(sessionRepository::setDefaultMaxInactiveInterval); + .to(sessionRepository::setDefaultMaxInactiveInterval); map.from(hazelcastSessionProperties::getMapName).to(sessionRepository::setSessionMapName); map.from(hazelcastSessionProperties::getFlushMode).to(sessionRepository::setFlushMode); map.from(hazelcastSessionProperties::getSaveMode).to(sessionRepository::setSaveMode); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java index 4b292b75c3..7fb6e09b8e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/JdbcSessionConfiguration.java @@ -73,7 +73,7 @@ class JdbcSessionConfiguration { return (sessionRepository) -> { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(sessionProperties.determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout())) - .to(sessionRepository::setDefaultMaxInactiveInterval); + .to(sessionRepository::setDefaultMaxInactiveInterval); map.from(jdbcSessionProperties::getTableName).to(sessionRepository::setTableName); map.from(jdbcSessionProperties::getFlushMode).to(sessionRepository::setFlushMode); map.from(jdbcSessionProperties::getSaveMode).to(sessionRepository::setSaveMode); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java index ade685ee33..2010c042df 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoReactiveSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class MongoReactiveSessionConfiguration { return (sessionRepository) -> { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(sessionProperties.determineTimeout(() -> serverProperties.getReactive().getSession().getTimeout())) - .to(sessionRepository::setDefaultMaxInactiveInterval); + .to(sessionRepository::setDefaultMaxInactiveInterval); map.from(mongoSessionProperties::getCollectionName).to(sessionRepository::setCollectionName); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java index 80da42ca48..97d7c6fa9a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/MongoSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class MongoSessionConfiguration { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); return (sessionRepository) -> { map.from(sessionProperties.determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout())) - .to(sessionRepository::setDefaultMaxInactiveInterval); + .to(sessionRepository::setDefaultMaxInactiveInterval); map.from(mongoSessionProperties::getCollectionName).to(sessionRepository::setCollectionName); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java index 200d74817a..94adbae6f1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisReactiveSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class RedisReactiveSessionConfiguration { return (sessionRepository) -> { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(sessionProperties.determineTimeout(() -> serverProperties.getReactive().getSession().getTimeout())) - .to(sessionRepository::setDefaultMaxInactiveInterval); + .to(sessionRepository::setDefaultMaxInactiveInterval); map.from(redisSessionProperties::getNamespace).to(sessionRepository::setRedisKeyNamespace); map.from(redisSessionProperties::getSaveMode).to(sessionRepository::setSaveMode); }; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java index 5f51a81741..fefd83f552 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,8 +73,8 @@ class RedisSessionConfiguration { return (sessionRepository) -> { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(sessionProperties - .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout())) - .to(sessionRepository::setDefaultMaxInactiveInterval); + .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout())) + .to(sessionRepository::setDefaultMaxInactiveInterval); map.from(redisSessionProperties::getNamespace).to(sessionRepository::setRedisKeyNamespace); map.from(redisSessionProperties::getFlushMode).to(sessionRepository::setFlushMode); map.from(redisSessionProperties::getSaveMode).to(sessionRepository::setSaveMode); @@ -104,8 +104,8 @@ class RedisSessionConfiguration { return (sessionRepository) -> { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(sessionProperties - .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout())) - .to(sessionRepository::setDefaultMaxInactiveInterval); + .determineTimeout(() -> serverProperties.getServlet().getSession().getTimeout())) + .to(sessionRepository::setDefaultMaxInactiveInterval); map.from(redisSessionProperties::getNamespace).to(sessionRepository::setRedisKeyNamespace); map.from(redisSessionProperties::getFlushMode).to(sessionRepository::setFlushMode); map.from(redisSessionProperties::getSaveMode).to(sessionRepository::setSaveMode); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java index 98f9591272..4d63294628 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -109,7 +109,7 @@ public class SessionAutoConfiguration { @Bean DefaultCookieSerializerCustomizer rememberMeServicesCookieSerializerCustomizer() { return (cookieSerializer) -> cookieSerializer - .setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); + .setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java index b65cb9e937..86bec585f6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -52,8 +52,10 @@ class SessionRepositoryFilterConfiguration { if (servletProperties.getFilterDispatcherTypes() == null) { return null; } - return servletProperties.getFilterDispatcherTypes().stream().map((type) -> DispatcherType.valueOf(type.name())) - .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); + return servletProperties.getFilterDispatcherTypes() + .stream() + .map((type) -> DispatcherType.valueOf(type.name())) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java index 69bf55f10c..511f8e6d04 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,8 +43,11 @@ class DataSourceInitializationConfiguration { private static DataSource determineDataSource(DataSource dataSource, String username, String password) { if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - return DataSourceBuilder.derivedFrom(dataSource).username(username).password(password) - .type(SimpleDriverDataSource.class).build(); + return DataSourceBuilder.derivedFrom(dataSource) + .username(username) + .password(password) + .type(SimpleDriverDataSource.class) + .build(); } return dataSource; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java index f986b0bdc1..032a047314 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -61,7 +61,7 @@ public class OnDatabaseInitializationCondition extends SpringBootCondition { boolean match = match(mode); String messagePrefix = (propertyName != null) ? propertyName : "default value"; return new ConditionOutcome(match, ConditionMessage.forCondition(this.name + "Database Initialization") - .because(messagePrefix + " is " + mode)); + .because(messagePrefix + " is " + mode)); } private boolean match(DatabaseInitializationMode mode) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java index f0a6893bff..f84166cd73 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/R2dbcInitializationConfiguration.java @@ -50,8 +50,10 @@ class R2dbcInitializationConfiguration { private static ConnectionFactory determineConnectionFactory(ConnectionFactory connectionFactory, String username, String password) { if (StringUtils.hasText(username) && StringUtils.hasText(password)) { - return ConnectionFactoryBuilder.derivedFrom(connectionFactory).username(username).password(password) - .build(); + return ConnectionFactoryBuilder.derivedFrom(connectionFactory) + .username(username) + .password(password) + .build(); } return connectionFactory; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java index a60c93c041..23db871a5b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/sql/init/SettingsCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -34,8 +34,8 @@ final class SettingsCreator { static DatabaseInitializationSettings createFrom(SqlInitializationProperties properties) { DatabaseInitializationSettings settings = new DatabaseInitializationSettings(); - settings.setSchemaLocations( - scriptLocations(properties.getSchemaLocations(), "schema", properties.getPlatform())); + settings + .setSchemaLocations(scriptLocations(properties.getSchemaLocations(), "schema", properties.getPlatform())); settings.setDataLocations(scriptLocations(properties.getDataLocations(), "data", properties.getPlatform())); settings.setContinueOnError(properties.isContinueOnError()); settings.setSeparator(properties.getSeparator()); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java index 644a4bcb2b..d68d513c2f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/ScheduledBeanLazyInitializationExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -64,7 +64,7 @@ class ScheduledBeanLazyInitializationExcludeFilter implements LazyInitialization Map> annotatedMethods = MethodIntrospector.selectMethods(targetType, (MethodIntrospector.MetadataLookup>) (method) -> { Set scheduledAnnotations = AnnotatedElementUtils - .getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class); + .getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class); return (!scheduledAnnotations.isEmpty() ? scheduledAnnotations : null); }); if (annotatedMethods.isEmpty()) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java index 4a591b9e22..e497a68b57 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -207,8 +207,10 @@ public class ThymeleafAutoConfiguration { private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getMediaTypes).whenNonNull().to(resolver::setSupportedMediaTypes); - map.from(properties::getMaxChunkSize).asInt(DataSize::toBytes).when((size) -> size > 0) - .to(resolver::setResponseMaxChunkSizeBytes); + map.from(properties::getMaxChunkSize) + .asInt(DataSize::toBytes) + .when((size) -> size > 0) + .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java index 4e9b892674..2bb603c4bc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/transaction/TransactionManagerCustomizers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -41,8 +41,8 @@ public class TransactionManagerCustomizers { @SuppressWarnings("unchecked") public void customize(PlatformTransactionManager transactionManager) { LambdaSafe.callbacks(PlatformTransactionManagerCustomizer.class, this.customizers, transactionManager) - .withLogger(TransactionManagerCustomizers.class) - .invoke((customizer) -> customizer.customize(transactionManager)); + .withLogger(TransactionManagerCustomizers.class) + .invoke((customizer) -> customizer.customize(transactionManager)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java index a7bc454dc4..a3df37fb11 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,7 +59,7 @@ public class ValidationAutoConfiguration { ObjectProvider customizers) { LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean(); factoryBean.setConfigurationInitializer((configuration) -> customizers.orderedStream() - .forEach((customizer) -> customizer.customize(configuration))); + .forEach((customizer) -> customizer.customize(configuration))); MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory(applicationContext); factoryBean.setMessageInterpolator(interpolatorFactory.getObject()); return factoryBean; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java index 2127c227ff..d0ba50a51c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -574,12 +574,15 @@ public class WebProperties { map.from(this::getCachePublic).whenTrue().toCall(control::cachePublic); map.from(this::getCachePrivate).whenTrue().toCall(control::cachePrivate); map.from(this::getProxyRevalidate).whenTrue().toCall(control::proxyRevalidate); - map.from(this::getStaleWhileRevalidate).whenNonNull() - .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); - map.from(this::getStaleIfError).whenNonNull() - .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); - map.from(this::getSMaxAge).whenNonNull() - .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getStaleWhileRevalidate) + .whenNonNull() + .to((duration) -> control.staleWhileRevalidate(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getStaleIfError) + .whenNonNull() + .to((duration) -> control.staleIfError(duration.getSeconds(), TimeUnit.SECONDS)); + map.from(this::getSMaxAge) + .whenNonNull() + .to((duration) -> control.sMaxAge(duration.getSeconds(), TimeUnit.SECONDS)); // check if cacheControl remained untouched if (control.getHeaderValue() == null) { return null; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHints.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHints.java index ad3b5d7b11..b074818578 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHints.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,8 +36,9 @@ public class WebResourcesRuntimeHints implements RuntimeHintsRegistrar { public void registerHints(RuntimeHints hints, ClassLoader classLoader) { ClassLoader classLoaderToUse = (classLoader != null) ? classLoader : getClass().getClassLoader(); String[] locations = DEFAULT_LOCATIONS.stream() - .filter((candidate) -> classLoaderToUse.getResource(candidate) != null) - .map((location) -> location + "*").toArray(String[]::new); + .filter((candidate) -> classLoaderToUse.getResource(candidate) != null) + .map((location) -> location + "*") + .toArray(String[]::new); if (locations.length > 0) { hints.resources().registerPattern((hint) -> hint.includes(locations)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java index 709c908c10..ee37e5afd5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -82,15 +82,22 @@ public class JettyWebServerFactoryCustomizer PropertyMapper propertyMapper = PropertyMapper.get(); propertyMapper.from(threadProperties::getAcceptors).whenNonNull().to(factory::setAcceptors); propertyMapper.from(threadProperties::getSelectors).whenNonNull().to(factory::setSelectors); - propertyMapper.from(properties::getMaxHttpRequestHeaderSize).whenNonNull().asInt(DataSize::toBytes) - .when(this::isPositive).to((maxHttpRequestHeaderSize) -> factory - .addServerCustomizers(new MaxHttpRequestHeaderSizeCustomizer(maxHttpRequestHeaderSize))); - propertyMapper.from(jettyProperties::getMaxHttpFormPostSize).asInt(DataSize::toBytes).when(this::isPositive) - .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); - propertyMapper.from(jettyProperties::getConnectionIdleTimeout).whenNonNull() - .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); - propertyMapper.from(jettyProperties::getAccesslog).when(ServerProperties.Jetty.Accesslog::isEnabled) - .to((accesslog) -> customizeAccessLog(factory, accesslog)); + propertyMapper.from(properties::getMaxHttpRequestHeaderSize) + .whenNonNull() + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to((maxHttpRequestHeaderSize) -> factory + .addServerCustomizers(new MaxHttpRequestHeaderSizeCustomizer(maxHttpRequestHeaderSize))); + propertyMapper.from(jettyProperties::getMaxHttpFormPostSize) + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); + propertyMapper.from(jettyProperties::getConnectionIdleTimeout) + .whenNonNull() + .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); + propertyMapper.from(jettyProperties::getAccesslog) + .when(ServerProperties.Jetty.Accesslog::isEnabled) + .to((accesslog) -> customizeAccessLog(factory, accesslog)); } private boolean isPositive(Integer value) { @@ -212,7 +219,7 @@ public class JettyWebServerFactoryCustomizer private void customize(ConnectionFactory factory) { if (factory instanceof HttpConfiguration.ConnectionFactory) { ((HttpConfiguration.ConnectionFactory) factory).getHttpConfiguration() - .setRequestHeaderSize(this.maxRequestHeaderSize); + .setRequestHeaderSize(this.maxRequestHeaderSize); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java index 53ed62ad97..cc12b2efb3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/NettyWebServerFactoryCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,12 +59,14 @@ public class NettyWebServerFactoryCustomizer factory.setUseForwardHeaders(getOrDeduceUseForwardHeaders()); PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); ServerProperties.Netty nettyProperties = this.serverProperties.getNetty(); - propertyMapper.from(nettyProperties::getConnectionTimeout).whenNonNull() - .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); - propertyMapper.from(nettyProperties::getIdleTimeout).whenNonNull() - .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); + propertyMapper.from(nettyProperties::getConnectionTimeout) + .whenNonNull() + .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); + propertyMapper.from(nettyProperties::getIdleTimeout) + .whenNonNull() + .to((idleTimeout) -> customizeIdleTimeout(factory, idleTimeout)); propertyMapper.from(nettyProperties::getMaxKeepAliveRequests) - .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); + .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); customizeRequestDecoder(factory, propertyMapper); } @@ -83,21 +85,26 @@ public class NettyWebServerFactoryCustomizer private void customizeRequestDecoder(NettyReactiveWebServerFactory factory, PropertyMapper propertyMapper) { factory.addServerCustomizers((httpServer) -> httpServer.httpRequestDecoder((httpRequestDecoderSpec) -> { - propertyMapper.from(this.serverProperties.getMaxHttpRequestHeaderSize()).whenNonNull() - .to((maxHttpRequestHeader) -> httpRequestDecoderSpec - .maxHeaderSize((int) maxHttpRequestHeader.toBytes())); + propertyMapper.from(this.serverProperties.getMaxHttpRequestHeaderSize()) + .whenNonNull() + .to((maxHttpRequestHeader) -> httpRequestDecoderSpec + .maxHeaderSize((int) maxHttpRequestHeader.toBytes())); ServerProperties.Netty nettyProperties = this.serverProperties.getNetty(); maxChunkSize(propertyMapper, httpRequestDecoderSpec, nettyProperties); - propertyMapper.from(nettyProperties.getMaxInitialLineLength()).whenNonNull() - .to((maxInitialLineLength) -> httpRequestDecoderSpec - .maxInitialLineLength((int) maxInitialLineLength.toBytes())); - propertyMapper.from(nettyProperties.getH2cMaxContentLength()).whenNonNull() - .to((h2cMaxContentLength) -> httpRequestDecoderSpec - .h2cMaxContentLength((int) h2cMaxContentLength.toBytes())); - propertyMapper.from(nettyProperties.getInitialBufferSize()).whenNonNull().to( - (initialBufferSize) -> httpRequestDecoderSpec.initialBufferSize((int) initialBufferSize.toBytes())); - propertyMapper.from(nettyProperties.isValidateHeaders()).whenNonNull() - .to(httpRequestDecoderSpec::validateHeaders); + propertyMapper.from(nettyProperties.getMaxInitialLineLength()) + .whenNonNull() + .to((maxInitialLineLength) -> httpRequestDecoderSpec + .maxInitialLineLength((int) maxInitialLineLength.toBytes())); + propertyMapper.from(nettyProperties.getH2cMaxContentLength()) + .whenNonNull() + .to((h2cMaxContentLength) -> httpRequestDecoderSpec + .h2cMaxContentLength((int) h2cMaxContentLength.toBytes())); + propertyMapper.from(nettyProperties.getInitialBufferSize()) + .whenNonNull() + .to((initialBufferSize) -> httpRequestDecoderSpec.initialBufferSize((int) initialBufferSize.toBytes())); + propertyMapper.from(nettyProperties.isValidateHeaders()) + .whenNonNull() + .to(httpRequestDecoderSpec::validateHeaders); return httpRequestDecoderSpec; })); } @@ -105,8 +112,9 @@ public class NettyWebServerFactoryCustomizer @SuppressWarnings({ "deprecation", "removal" }) private void maxChunkSize(PropertyMapper propertyMapper, HttpRequestDecoderSpec httpRequestDecoderSpec, ServerProperties.Netty nettyProperties) { - propertyMapper.from(nettyProperties.getMaxChunkSize()).whenNonNull() - .to((maxChunkSize) -> httpRequestDecoderSpec.maxChunkSize((int) maxChunkSize.toBytes())); + propertyMapper.from(nettyProperties.getMaxChunkSize()) + .whenNonNull() + .to((maxChunkSize) -> httpRequestDecoderSpec.maxChunkSize((int) maxChunkSize.toBytes())); } private void customizeIdleTimeout(NettyReactiveWebServerFactory factory, Duration idleTimeout) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java index 0a5fb74756..6bcf48a865 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java @@ -84,43 +84,62 @@ public class TomcatWebServerFactoryCustomizer ServerProperties.Tomcat tomcatProperties = properties.getTomcat(); PropertyMapper propertyMapper = PropertyMapper.get(); propertyMapper.from(tomcatProperties::getBasedir).whenNonNull().to(factory::setBaseDirectory); - propertyMapper.from(tomcatProperties::getBackgroundProcessorDelay).whenNonNull().as(Duration::getSeconds) - .as(Long::intValue).to(factory::setBackgroundProcessorDelay); + propertyMapper.from(tomcatProperties::getBackgroundProcessorDelay) + .whenNonNull() + .as(Duration::getSeconds) + .as(Long::intValue) + .to(factory::setBackgroundProcessorDelay); customizeRemoteIpValve(factory); ServerProperties.Tomcat.Threads threadProperties = tomcatProperties.getThreads(); - propertyMapper.from(threadProperties::getMax).when(this::isPositive) - .to((maxThreads) -> customizeMaxThreads(factory, threadProperties.getMax())); - propertyMapper.from(threadProperties::getMinSpare).when(this::isPositive) - .to((minSpareThreads) -> customizeMinThreads(factory, minSpareThreads)); - propertyMapper.from(this.serverProperties.getMaxHttpRequestHeaderSize()).whenNonNull().asInt(DataSize::toBytes) - .when(this::isPositive) - .to((maxHttpRequestHeaderSize) -> customizeMaxHttpRequestHeaderSize(factory, maxHttpRequestHeaderSize)); - propertyMapper.from(tomcatProperties::getMaxSwallowSize).whenNonNull().asInt(DataSize::toBytes) - .to((maxSwallowSize) -> customizeMaxSwallowSize(factory, maxSwallowSize)); - propertyMapper.from(tomcatProperties::getMaxHttpFormPostSize).asInt(DataSize::toBytes) - .when((maxHttpFormPostSize) -> maxHttpFormPostSize != 0) - .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); - propertyMapper.from(tomcatProperties::getAccesslog).when(ServerProperties.Tomcat.Accesslog::isEnabled) - .to((enabled) -> customizeAccessLog(factory)); + propertyMapper.from(threadProperties::getMax) + .when(this::isPositive) + .to((maxThreads) -> customizeMaxThreads(factory, threadProperties.getMax())); + propertyMapper.from(threadProperties::getMinSpare) + .when(this::isPositive) + .to((minSpareThreads) -> customizeMinThreads(factory, minSpareThreads)); + propertyMapper.from(this.serverProperties.getMaxHttpRequestHeaderSize()) + .whenNonNull() + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to((maxHttpRequestHeaderSize) -> customizeMaxHttpRequestHeaderSize(factory, maxHttpRequestHeaderSize)); + propertyMapper.from(tomcatProperties::getMaxSwallowSize) + .whenNonNull() + .asInt(DataSize::toBytes) + .to((maxSwallowSize) -> customizeMaxSwallowSize(factory, maxSwallowSize)); + propertyMapper.from(tomcatProperties::getMaxHttpFormPostSize) + .asInt(DataSize::toBytes) + .when((maxHttpFormPostSize) -> maxHttpFormPostSize != 0) + .to((maxHttpFormPostSize) -> customizeMaxHttpFormPostSize(factory, maxHttpFormPostSize)); + propertyMapper.from(tomcatProperties::getAccesslog) + .when(ServerProperties.Tomcat.Accesslog::isEnabled) + .to((enabled) -> customizeAccessLog(factory)); propertyMapper.from(tomcatProperties::getUriEncoding).whenNonNull().to(factory::setUriEncoding); - propertyMapper.from(tomcatProperties::getConnectionTimeout).whenNonNull() - .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); - propertyMapper.from(tomcatProperties::getMaxConnections).when(this::isPositive) - .to((maxConnections) -> customizeMaxConnections(factory, maxConnections)); - propertyMapper.from(tomcatProperties::getAcceptCount).when(this::isPositive) - .to((acceptCount) -> customizeAcceptCount(factory, acceptCount)); + propertyMapper.from(tomcatProperties::getConnectionTimeout) + .whenNonNull() + .to((connectionTimeout) -> customizeConnectionTimeout(factory, connectionTimeout)); + propertyMapper.from(tomcatProperties::getMaxConnections) + .when(this::isPositive) + .to((maxConnections) -> customizeMaxConnections(factory, maxConnections)); + propertyMapper.from(tomcatProperties::getAcceptCount) + .when(this::isPositive) + .to((acceptCount) -> customizeAcceptCount(factory, acceptCount)); propertyMapper.from(tomcatProperties::getProcessorCache) - .to((processorCache) -> customizeProcessorCache(factory, processorCache)); - propertyMapper.from(tomcatProperties::getKeepAliveTimeout).whenNonNull() - .to((keepAliveTimeout) -> customizeKeepAliveTimeout(factory, keepAliveTimeout)); + .to((processorCache) -> customizeProcessorCache(factory, processorCache)); + propertyMapper.from(tomcatProperties::getKeepAliveTimeout) + .whenNonNull() + .to((keepAliveTimeout) -> customizeKeepAliveTimeout(factory, keepAliveTimeout)); propertyMapper.from(tomcatProperties::getMaxKeepAliveRequests) - .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); - propertyMapper.from(tomcatProperties::getRelaxedPathChars).as(this::joinCharacters).whenHasText() - .to((relaxedChars) -> customizeRelaxedPathChars(factory, relaxedChars)); - propertyMapper.from(tomcatProperties::getRelaxedQueryChars).as(this::joinCharacters).whenHasText() - .to((relaxedChars) -> customizeRelaxedQueryChars(factory, relaxedChars)); + .to((maxKeepAliveRequests) -> customizeMaxKeepAliveRequests(factory, maxKeepAliveRequests)); + propertyMapper.from(tomcatProperties::getRelaxedPathChars) + .as(this::joinCharacters) + .whenHasText() + .to((relaxedChars) -> customizeRelaxedPathChars(factory, relaxedChars)); + propertyMapper.from(tomcatProperties::getRelaxedQueryChars) + .as(this::joinCharacters) + .whenHasText() + .to((relaxedChars) -> customizeRelaxedQueryChars(factory, relaxedChars)); propertyMapper.from(tomcatProperties::isRejectIllegalHeader) - .to((rejectIllegalHeader) -> customizeRejectIllegalHeader(factory, rejectIllegalHeader)); + .to((rejectIllegalHeader) -> customizeRejectIllegalHeader(factory, rejectIllegalHeader)); customizeStaticResources(factory); customizeErrorReportValve(properties.getError(), factory); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java index aaeacf0b11..d5d861aad7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizer.java @@ -78,8 +78,10 @@ public class UndertowWebServerFactoryCustomizer PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); ServerOptions options = new ServerOptions(factory); ServerProperties properties = this.serverProperties; - map.from(properties::getMaxHttpRequestHeaderSize).asInt(DataSize::toBytes).when(this::isPositive) - .to(options.option(UndertowOptions.MAX_HEADER_SIZE)); + map.from(properties::getMaxHttpRequestHeaderSize) + .asInt(DataSize::toBytes) + .when(this::isPositive) + .to(options.option(UndertowOptions.MAX_HEADER_SIZE)); mapUndertowProperties(factory, options); mapAccessLogProperties(factory); map.from(this::getOrDeduceUseForwardHeaders).to(factory::setUseForwardHeaders); @@ -93,8 +95,10 @@ public class UndertowWebServerFactoryCustomizer map.from(threadProperties::getIo).to(factory::setIoThreads); map.from(threadProperties::getWorker).to(factory::setWorkerThreads); map.from(properties::getDirectBuffers).to(factory::setUseDirectBuffers); - map.from(properties::getMaxHttpPostSize).as(DataSize::toBytes).when(this::isPositive) - .to(serverOptions.option(UndertowOptions.MAX_ENTITY_SIZE)); + map.from(properties::getMaxHttpPostSize) + .as(DataSize::toBytes) + .when(this::isPositive) + .to(serverOptions.option(UndertowOptions.MAX_ENTITY_SIZE)); map.from(properties::getMaxParameters).to(serverOptions.option(UndertowOptions.MAX_PARAMETERS)); map.from(properties::getMaxHeaders).to(serverOptions.option(UndertowOptions.MAX_HEADERS)); map.from(properties::getMaxCookies).to(serverOptions.option(UndertowOptions.MAX_COOKIES)); @@ -102,8 +106,9 @@ public class UndertowWebServerFactoryCustomizer map.from(properties::isDecodeUrl).to(serverOptions.option(UndertowOptions.DECODE_URL)); map.from(properties::getUrlCharset).as(Charset::name).to(serverOptions.option(UndertowOptions.URL_CHARSET)); map.from(properties::isAlwaysSetKeepAlive).to(serverOptions.option(UndertowOptions.ALWAYS_SET_KEEP_ALIVE)); - map.from(properties::getNoRequestTimeout).asInt(Duration::toMillis) - .to(serverOptions.option(UndertowOptions.NO_REQUEST_TIMEOUT)); + map.from(properties::getNoRequestTimeout) + .asInt(Duration::toMillis) + .to(serverOptions.option(UndertowOptions.NO_REQUEST_TIMEOUT)); map.from(properties.getOptions()::getServer).to(serverOptions.forEach(serverOptions::option)); SocketOptions socketOptions = new SocketOptions(factory); map.from(properties.getOptions()::getSocket).to(socketOptions.forEach(socketOptions::option)); @@ -184,8 +189,10 @@ public class UndertowWebServerFactoryCustomizer private static String getCanonicalName(String name) { StringBuilder canonicalName = new StringBuilder(name.length()); - name.chars().filter(Character::isLetterOrDigit).map(Character::toLowerCase) - .forEach((c) -> canonicalName.append((char) c)); + name.chars() + .filter(Character::isLetterOrDigit) + .map(Character::toLowerCase) + .forEach((c) -> canonicalName.append((char) c)); return canonicalName.toString(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java index cc949ad4be..af302e459d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,23 +55,29 @@ public class ReactiveMultipartAutoConfiguration { return (configurer) -> configurer.defaultCodecs().configureDefaultCodec((codec) -> { if (codec instanceof DefaultPartHttpMessageReader defaultPartHttpMessageReader) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(multipartProperties::getMaxInMemorySize).asInt(DataSize::toBytes) - .to(defaultPartHttpMessageReader::setMaxInMemorySize); - map.from(multipartProperties::getMaxHeadersSize).asInt(DataSize::toBytes) - .to(defaultPartHttpMessageReader::setMaxHeadersSize); - map.from(multipartProperties::getMaxDiskUsagePerPart).asInt(DataSize::toBytes) - .to(defaultPartHttpMessageReader::setMaxDiskUsagePerPart); + map.from(multipartProperties::getMaxInMemorySize) + .asInt(DataSize::toBytes) + .to(defaultPartHttpMessageReader::setMaxInMemorySize); + map.from(multipartProperties::getMaxHeadersSize) + .asInt(DataSize::toBytes) + .to(defaultPartHttpMessageReader::setMaxHeadersSize); + map.from(multipartProperties::getMaxDiskUsagePerPart) + .asInt(DataSize::toBytes) + .to(defaultPartHttpMessageReader::setMaxDiskUsagePerPart); map.from(multipartProperties::getMaxParts).to(defaultPartHttpMessageReader::setMaxParts); - map.from(multipartProperties::getFileStorageDirectory).as(Paths::get) - .to((dir) -> configureFileStorageDirectory(defaultPartHttpMessageReader, dir)); + map.from(multipartProperties::getFileStorageDirectory) + .as(Paths::get) + .to((dir) -> configureFileStorageDirectory(defaultPartHttpMessageReader, dir)); map.from(multipartProperties::getHeadersCharset).to(defaultPartHttpMessageReader::setHeadersCharset); } else if (codec instanceof PartEventHttpMessageReader partEventHttpMessageReader) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(multipartProperties::getMaxInMemorySize).asInt(DataSize::toBytes) - .to(partEventHttpMessageReader::setMaxInMemorySize); - map.from(multipartProperties::getMaxHeadersSize).asInt(DataSize::toBytes) - .to(partEventHttpMessageReader::setMaxHeadersSize); + map.from(multipartProperties::getMaxInMemorySize) + .asInt(DataSize::toBytes) + .to(partEventHttpMessageReader::setMaxInMemorySize); + map.from(multipartProperties::getMaxHeadersSize) + .asInt(DataSize::toBytes) + .to(partEventHttpMessageReader::setMaxHeadersSize); map.from(multipartProperties::getHeadersCharset).to(partEventHttpMessageReader::setHeadersCharset); } }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java index 7296f6c3b4..54b1effcb9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -193,14 +193,14 @@ public class WebFluxAutoConfiguration { String webjarsPathPattern = this.webFluxProperties.getWebjarsPathPattern(); if (!registry.hasMappingForPattern(webjarsPathPattern)) { ResourceHandlerRegistration registration = registry.addResourceHandler(webjarsPathPattern) - .addResourceLocations("classpath:/META-INF/resources/webjars/"); + .addResourceLocations("classpath:/META-INF/resources/webjars/"); configureResourceCaching(registration); customizeResourceHandlerRegistration(registration); } String staticPathPattern = this.webFluxProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { ResourceHandlerRegistration registration = registry.addResourceHandler(staticPathPattern) - .addResourceLocations(this.resourceProperties.getStaticLocations()); + .addResourceLocations(this.resourceProperties.getStaticLocations()); configureResourceCaching(registration); customizeResourceHandlerRegistration(registration); } @@ -209,7 +209,7 @@ public class WebFluxAutoConfiguration { private void configureResourceCaching(ResourceHandlerRegistration registration) { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); WebProperties.Resources.Cache.Cachecontrol cacheControl = this.resourceProperties.getCache() - .getCachecontrol(); + .getCachecontrol(); if (cachePeriod != null && cacheControl.getMaxAge() == null) { cacheControl.setMaxAge(cachePeriod); } @@ -262,8 +262,10 @@ public class WebFluxAutoConfiguration { @Override public FormattingConversionService webFluxConversionService() { Format format = this.webFluxProperties.getFormat(); - WebConversionService conversionService = new WebConversionService(new DateTimeFormatters() - .dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime())); + WebConversionService conversionService = new WebConversionService( + new DateTimeFormatters().dateFormat(format.getDate()) + .timeFormat(format.getTime()) + .dateTimeFormat(format.getDateTime())); addFormatters(conversionService); return conversionService; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java index 656ff43420..677c4cc0d1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -53,8 +53,11 @@ final class WelcomePageRouterFunctionFactory { } private Resource getWelcomePage(ResourceLoader resourceLoader, String[] staticLocations) { - return Arrays.stream(staticLocations).map((location) -> getIndexHtml(resourceLoader, location)) - .filter(this::isReadable).findFirst().orElse(null); + return Arrays.stream(staticLocations) + .map((location) -> getIndexHtml(resourceLoader, location)) + .filter(this::isReadable) + .findFirst() + .orElse(null); } private Resource getIndexHtml(ResourceLoader resourceLoader, String location) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java index 5fd010af20..11c1bf536c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/AbstractErrorWebExceptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -246,10 +246,17 @@ public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExcept Object trace = error.get("trace"); Object requestId = error.get("requestId"); builder.append("

Whitelabel Error Page

") - .append("

This application has no configured error view, so you are seeing this as a fallback.

") - .append("
").append(timestamp).append("
").append("
[").append(requestId) - .append("] There was an unexpected error (type=").append(htmlEscape(error.get("error"))) - .append(", status=").append(htmlEscape(error.get("status"))).append(").
"); + .append("

This application has no configured error view, so you are seeing this as a fallback.

") + .append("
") + .append(timestamp) + .append("
") + .append("
[") + .append(requestId) + .append("] There was an unexpected error (type=") + .append(htmlEscape(error.get("error"))) + .append(", status=") + .append(htmlEscape(error.get("status"))) + .append(").
"); if (message != null) { builder.append("
").append(htmlEscape(message)).append("
"); } @@ -291,10 +298,11 @@ public abstract class AbstractErrorWebExceptionHandler implements ErrorWebExcept } this.errorAttributes.storeErrorInformation(throwable, exchange); ServerRequest request = ServerRequest.create(exchange, this.messageReaders); - return getRoutingFunction(this.errorAttributes).route(request).switchIfEmpty(Mono.error(throwable)) - .flatMap((handler) -> handler.handle(request)) - .doOnNext((response) -> logError(request, response, throwable)) - .flatMap((response) -> write(exchange, response)); + return getRoutingFunction(this.errorAttributes).route(request) + .switchIfEmpty(Mono.error(throwable)) + .flatMap((handler) -> handler.handle(request)) + .doOnNext((response) -> logError(request, response, throwable)) + .flatMap((response) -> write(exchange, response)); } private boolean isDisconnectedClientError(Throwable ex) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java index 124ebecb7e..5bc52de7c7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -121,10 +121,10 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa int errorStatus = getHttpStatus(error); ServerResponse.BodyBuilder responseBody = ServerResponse.status(errorStatus).contentType(TEXT_HTML_UTF8); return Flux.just(getData(errorStatus).toArray(new String[] {})) - .flatMap((viewName) -> renderErrorView(viewName, responseBody, error)) - .switchIfEmpty(this.errorProperties.getWhitelabel().isEnabled() - ? renderDefaultErrorView(responseBody, error) : Mono.error(getError(request))) - .next(); + .flatMap((viewName) -> renderErrorView(viewName, responseBody, error)) + .switchIfEmpty(this.errorProperties.getWhitelabel().isEnabled() + ? renderDefaultErrorView(responseBody, error) : Mono.error(getError(request))) + .next(); } private List getData(int errorStatus) { @@ -145,8 +145,9 @@ public class DefaultErrorWebExceptionHandler extends AbstractErrorWebExceptionHa */ protected Mono renderErrorResponse(ServerRequest request) { Map error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); - return ServerResponse.status(getHttpStatus(error)).contentType(MediaType.APPLICATION_JSON) - .body(BodyInserters.fromValue(error)); + return ServerResponse.status(getHttpStatus(error)) + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(error)); } protected ErrorAttributeOptions getErrorAttributeOptions(ServerRequest request, MediaType mediaType) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java index 68e1e4b4a8..ade9dac75b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/ClientHttpConnectorConfiguration.java @@ -61,8 +61,8 @@ class ClientHttpConnectorConfiguration { ReactorClientHttpConnector reactorClientHttpConnector(ReactorResourceFactory reactorResourceFactory, ObjectProvider mapperProvider) { ReactorNettyHttpClientMapper mapper = mapperProvider.orderedStream() - .reduce((before, after) -> (client) -> after.configure(before.configure(client))) - .orElse((client) -> client); + .reduce((before, after) -> (client) -> after.configure(before.configure(client))) + .orElse((client) -> client); return new ReactorClientHttpConnector(reactorResourceFactory, mapper::configure); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java index 8a812baa6b..548bbee818 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/function/client/WebClientCodecCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ public class WebClientCodecCustomizer implements WebClientCustomizer { @Override public void customize(WebClient.Builder webClientBuilder) { webClientBuilder - .codecs((codecs) -> this.codecCustomizers.forEach((customizer) -> customizer.customize(codecs))); + .codecs((codecs) -> this.codecCustomizers.forEach((customizer) -> customizer.customize(codecs))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java index a718afe613..77bcda62b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DefaultJerseyApplicationPath.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,9 @@ public class DefaultJerseyApplicationPath implements JerseyApplicationPath { } // Jersey doesn't like to be the default servlet, so map to /* as a fallback return MergedAnnotations.from(this.config.getApplication().getClass(), SearchStrategy.TYPE_HIERARCHY) - .get(ApplicationPath.class).getValue(MergedAnnotation.VALUE, String.class).orElse("/*"); + .get(ApplicationPath.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse("/*"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java index 12ac6e8d5b..5575bde20a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -134,21 +134,21 @@ public class DispatcherServletAutoConfiguration { ConditionMessage.Builder message = ConditionMessage.forCondition("Default DispatcherServlet"); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); List dispatchServletBeans = Arrays - .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); if (dispatchServletBeans.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { return ConditionOutcome - .noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + .noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { - return ConditionOutcome.noMatch( - message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + return ConditionOutcome + .noMatch(message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } if (dispatchServletBeans.isEmpty()) { return ConditionOutcome.match(message.didNotFind("dispatcher servlet beans").atAll()); } return ConditionOutcome.match(message.found("dispatcher servlet bean", "dispatcher servlet beans") - .items(Style.QUOTE, dispatchServletBeans) - .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); + .items(Style.QUOTE, dispatchServletBeans) + .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); } } @@ -172,7 +172,7 @@ public class DispatcherServletAutoConfiguration { return ConditionOutcome.match(); } List servlets = Arrays - .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); + .asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false)); if (!servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) { return ConditionOutcome.noMatch( startMessage().found("non dispatcher servlet").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)); @@ -183,26 +183,27 @@ public class DispatcherServletAutoConfiguration { private ConditionOutcome checkServletRegistration(ConfigurableListableBeanFactory beanFactory) { ConditionMessage.Builder message = startMessage(); List registrations = Arrays - .asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false)); + .asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false)); boolean containsDispatcherRegistrationBean = beanFactory - .containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); + .containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME); if (registrations.isEmpty()) { if (containsDispatcherRegistrationBean) { return ConditionOutcome.noMatch(message.found("non servlet registration bean") - .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } return ConditionOutcome.match(message.didNotFind("servlet registration bean").atAll()); } if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) { return ConditionOutcome.noMatch(message.found("servlet registration bean") - .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } if (containsDispatcherRegistrationBean) { return ConditionOutcome.noMatch(message.found("non servlet registration bean") - .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + .items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } - return ConditionOutcome.match(message.found("servlet registration beans").items(Style.QUOTE, registrations) - .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); + return ConditionOutcome.match(message.found("servlet registration beans") + .items(Style.QUOTE, registrations) + .append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); } private ConditionMessage.Builder startMessage() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java index 7ef353439a..fb532075fc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -222,14 +222,14 @@ public class WebMvcAutoConfiguration { @Override public void configureMessageConverters(List> converters) { this.messageConvertersProvider - .ifAvailable((customConverters) -> converters.addAll(customConverters.getConverters())); + .ifAvailable((customConverters) -> converters.addAll(customConverters.getConverters())); } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { if (this.beanFactory.containsBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)) { Object taskExecutor = this.beanFactory - .getBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); + .getBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME); if (taskExecutor instanceof AsyncTaskExecutor asyncTaskExecutor) { configurer.setTaskExecutor(asyncTaskExecutor); } @@ -243,7 +243,7 @@ public class WebMvcAutoConfiguration { @Override public void configurePathMatch(PathMatchConfigurer configurer) { if (this.mvcProperties.getPathmatch() - .getMatchingStrategy() == WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER) { + .getMatchingStrategy() == WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER) { configurer.setPathMatcher(new AntPathMatcher()); this.dispatcherServletPath.ifAvailable((dispatcherPath) -> { String servletUrlMapping = dispatcherPath.getServletUrlMapping(); @@ -257,8 +257,10 @@ public class WebMvcAutoConfiguration { } private boolean singleDispatcherServlet() { - return this.servletRegistrations.stream().map(ServletRegistrationBean::getServlet) - .filter(DispatcherServlet.class::isInstance).count() == 1; + return this.servletRegistrations.stream() + .map(ServletRegistrationBean::getServlet) + .filter(DispatcherServlet.class::isInstance) + .count() == 1; } @Override @@ -502,8 +504,10 @@ public class WebMvcAutoConfiguration { @Override public FormattingConversionService mvcConversionService() { Format format = this.mvcProperties.getFormat(); - WebConversionService conversionService = new WebConversionService(new DateTimeFormatters() - .dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime())); + WebConversionService conversionService = new WebConversionService( + new DateTimeFormatters().dateFormat(format.getDate()) + .timeFormat(format.getTime()) + .dateTimeFormat(format.getDateTime())); addFormatters(conversionService); return conversionService; } @@ -543,7 +547,7 @@ public class WebMvcAutoConfiguration { protected ExceptionHandlerExceptionResolver createExceptionHandlerExceptionResolver() { if (this.mvcRegistrations != null) { ExceptionHandlerExceptionResolver resolver = this.mvcRegistrations - .getExceptionHandlerExceptionResolver(); + .getExceptionHandlerExceptionResolver(); if (resolver != null) { return resolver; } @@ -665,7 +669,7 @@ public class WebMvcAutoConfiguration { @SuppressWarnings("deprecation") private static final String SKIP_ATTRIBUTE = org.springframework.web.accept.PathExtensionContentNegotiationStrategy.class - .getName() + ".SKIP"; + .getName() + ".SKIP"; private final ContentNegotiationStrategy delegate; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java index 137d194345..6037fa974a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -437,6 +437,7 @@ public class WebMvcProperties { /** * Matching strategy options. + * * @since 2.4.0 */ public enum MatchingStrategy { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java index 94ad14db51..610f24517f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorController.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -85,7 +85,7 @@ public class BasicErrorController extends AbstractErrorController { public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map model = Collections - .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); + .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java index 20e47b5f56..c28b7dfc79 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java @@ -210,11 +210,16 @@ public class ErrorMvcAutoConfiguration { if (response.getContentType() == null) { response.setContentType(getContentType()); } - builder.append("

Whitelabel Error Page

").append( - "

This application has no explicit mapping for /error, so you are seeing this as a fallback.

") - .append("
").append(timestamp).append("
") - .append("
There was an unexpected error (type=").append(htmlEscape(model.get("error"))) - .append(", status=").append(htmlEscape(model.get("status"))).append(").
"); + builder.append("

Whitelabel Error Page

") + .append("

This application has no explicit mapping for /error, so you are seeing this as a fallback.

") + .append("
") + .append(timestamp) + .append("
") + .append("
There was an unexpected error (type=") + .append(htmlEscape(model.get("error"))) + .append(", status=") + .append(htmlEscape(model.get("status"))) + .append(").
"); if (message != null) { builder.append("
").append(htmlEscape(message)).append("
"); } @@ -287,7 +292,7 @@ public class ErrorMvcAutoConfiguration { for (String errorControllerBean : errorControllerBeans) { try { beanFactory.getBeanDefinition(errorControllerBean) - .setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); + .setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); } catch (Throwable ex) { // Ignore diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java index 69edbc4ede..77f7a6b9e1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -108,7 +108,7 @@ public class WebServicesAutoConfiguration { public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Binder binder = Binder.get(this.applicationContext.getEnvironment()); List wsdlLocations = binder.bind("spring.webservices.wsdl-locations", Bindable.listOf(String.class)) - .orElse(Collections.emptyList()); + .orElse(Collections.emptyList()); for (String wsdlLocation : wsdlLocations) { registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, SimpleWsdl11Definition::new, registry); @@ -124,7 +124,8 @@ public class WebServicesAutoConfiguration { Function beanSupplier, BeanDefinitionRegistry registry) { for (Resource resource : getResources(location, pattern)) { BeanDefinition beanDefinition = BeanDefinitionBuilder - .genericBeanDefinition(type, () -> beanSupplier.apply(resource)).getBeanDefinition(); + .genericBeanDefinition(type, () -> beanSupplier.apply(resource)) + .getBeanDefinition(); registry.registerBeanDefinition(StringUtils.stripFilenameExtension(resource.getFilename()), beanDefinition); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java index 6472b322b8..b634faac91 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java @@ -39,28 +39,29 @@ import static org.assertj.core.api.Assertions.assertThat; class AbstractDependsOnBeanFactoryPostProcessorTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(FooBarConfiguration.class); + .withUserConfiguration(FooBarConfiguration.class); @Test void fooBeansShouldDependOnBarBeanNames() { this.contextRunner - .withUserConfiguration(FooDependsOnBarNamePostProcessor.class, FooBarFactoryBeanConfiguration.class) - .run(this::assertThatFooDependsOnBar); + .withUserConfiguration(FooDependsOnBarNamePostProcessor.class, FooBarFactoryBeanConfiguration.class) + .run(this::assertThatFooDependsOnBar); } @Test void fooBeansShouldDependOnBarBeanTypes() { this.contextRunner - .withUserConfiguration(FooDependsOnBarTypePostProcessor.class, FooBarFactoryBeanConfiguration.class) - .run(this::assertThatFooDependsOnBar); + .withUserConfiguration(FooDependsOnBarTypePostProcessor.class, FooBarFactoryBeanConfiguration.class) + .run(this::assertThatFooDependsOnBar); } @Test void fooBeansShouldDependOnBarBeanNamesParentContext() { try (AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext( FooBarFactoryBeanConfiguration.class)) { - this.contextRunner.withUserConfiguration(FooDependsOnBarNamePostProcessor.class).withParent(parentContext) - .run(this::assertThatFooDependsOnBar); + this.contextRunner.withUserConfiguration(FooDependsOnBarNamePostProcessor.class) + .withParent(parentContext) + .run(this::assertThatFooDependsOnBar); } } @@ -68,8 +69,9 @@ class AbstractDependsOnBeanFactoryPostProcessorTests { void fooBeansShouldDependOnBarBeanTypesParentContext() { try (AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext( FooBarFactoryBeanConfiguration.class)) { - this.contextRunner.withUserConfiguration(FooDependsOnBarTypePostProcessor.class).withParent(parentContext) - .run(this::assertThatFooDependsOnBar); + this.contextRunner.withUserConfiguration(FooDependsOnBarTypePostProcessor.class) + .withParent(parentContext) + .run(this::assertThatFooDependsOnBar); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java index 69e7ff697d..eefce28976 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -40,27 +40,27 @@ class AutoConfigurationImportSelectorIntegrationTests { @Test void singleSelectorWithNoImports() { this.contextRunner.withUserConfiguration(NoConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).isEmpty()); + .run((context) -> assertThat(getImportedConfigBeans(context)).isEmpty()); } @Test void singleSelector() { this.contextRunner.withUserConfiguration(SingleConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigC")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigC")); } @Test void multipleSelectorsShouldMergeAndSortCorrectly() { this.contextRunner.withUserConfiguration(Config.class, AnotherConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", - "ConfigC", "ConfigD")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD")); } @Test void multipleSelectorsWithRedundantImportsShouldMergeAndSortCorrectly() { this.contextRunner.withUserConfiguration(SingleConfig.class, Config.class, AnotherConfig.class) - .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", - "ConfigC", "ConfigD")); + .run((context) -> assertThat(getImportedConfigBeans(context)).containsExactly("ConfigA", "ConfigB", + "ConfigC", "ConfigD")); } private List getImportedConfigBeans(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java index 82685205d4..bd14794b70 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -77,7 +77,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(EnableAutoConfigurationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -85,7 +85,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(SpringBootApplicationWithClassExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -93,7 +93,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(EnableAutoConfigurationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(MustacheAutoConfiguration.class.getName()); + .contains(MustacheAutoConfiguration.class.getName()); } @Test @@ -101,7 +101,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(SpringBootApplicationWithClassNameExclusions.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(MustacheAutoConfiguration.class.getName()); + .contains(MustacheAutoConfiguration.class.getName()); } @Test @@ -110,7 +110,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 1); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName()); } @Test @@ -138,7 +138,7 @@ class AutoConfigurationImportSelectorTests { String[] imports = selectImports(BasicEnableAutoConfiguration.class); assertThat(imports).hasSize(getAutoConfigurationClassNames().size() - 2); assertThat(this.importSelector.getLastEvent().getExclusions()) - .contains(FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName()); + .contains(FreeMarkerAutoConfiguration.class.getName(), MustacheAutoConfiguration.class.getName()); } @Test @@ -154,13 +154,13 @@ class AutoConfigurationImportSelectorTests { @Test void nonAutoConfigurationClassExclusionsShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); + .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); } @Test void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class)); + .isThrownBy(() -> selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java index f7a2dd9486..d53a22ca76 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,14 +42,14 @@ class AutoConfigurationPackagesTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ConfigWithAutoConfigurationPackage.class); assertThat(AutoConfigurationPackages.get(context.getBeanFactory())) - .containsExactly(getClass().getPackage().getName()); + .containsExactly(getClass().getPackage().getName()); } @Test void getWithoutSet() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EmptyConfig.class); assertThatIllegalStateException().isThrownBy(() -> AutoConfigurationPackages.get(context.getBeanFactory())) - .withMessageContaining("Unable to retrieve @EnableAutoConfiguration base packages"); + .withMessageContaining("Unable to retrieve @EnableAutoConfiguration base packages"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java index fa0284ceb1..6f00a40248 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -176,7 +176,7 @@ class AutoConfigurationSorterTests { void byAutoConfigureAfterWithCycle() { this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), this.autoConfigurationMetadata); assertThatIllegalStateException().isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D))) - .withMessageContaining("AutoConfigure cycle detected"); + .withMessageContaining("AutoConfigure cycle detected"); } @Test @@ -203,7 +203,7 @@ class AutoConfigurationSorterTests { this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, D); this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); assertThatIllegalStateException().isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(D, B))) - .withMessageContaining("AutoConfigure cycle detected"); + .withMessageContaining("AutoConfigure cycle detected"); } private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames) throws Exception { @@ -221,7 +221,7 @@ class AutoConfigurationSorterTests { private void addAutoConfigureAfter(Properties properties, String className, AnnotationMetadata annotationMetadata) { Map autoConfigureAfter = annotationMetadata - .getAnnotationAttributes(AutoConfigureAfter.class.getName(), true); + .getAnnotationAttributes(AutoConfigureAfter.class.getName(), true); if (autoConfigureAfter != null) { String value = merge((String[]) autoConfigureAfter.get("value"), (String[]) autoConfigureAfter.get("name")); if (!value.isEmpty()) { @@ -233,7 +233,7 @@ class AutoConfigurationSorterTests { private void addAutoConfigureBefore(Properties properties, String className, AnnotationMetadata annotationMetadata) { Map autoConfigureBefore = annotationMetadata - .getAnnotationAttributes(AutoConfigureBefore.class.getName(), true); + .getAnnotationAttributes(AutoConfigureBefore.class.getName(), true); if (autoConfigureBefore != null) { String value = merge((String[]) autoConfigureBefore.get("value"), (String[]) autoConfigureBefore.get("name")); @@ -245,7 +245,7 @@ class AutoConfigurationSorterTests { private void addAutoConfigureOrder(Properties properties, String className, AnnotationMetadata annotationMetadata) { Map autoConfigureOrder = annotationMetadata - .getAnnotationAttributes(AutoConfigureOrder.class.getName()); + .getAnnotationAttributes(AutoConfigureOrder.class.getName()); if (autoConfigureOrder != null) { Integer order = (Integer) autoConfigureOrder.get("order"); if (order != null) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java index 19381d8ee0..d08cbc2eb2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java @@ -121,9 +121,9 @@ class ImportAutoConfigurationImportSelectorTests { @Test void determineImportsWhenUsingMetaWithoutClassesShouldBeEqual() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1).hasSameHashCodeAs(set2); } @@ -131,27 +131,27 @@ class ImportAutoConfigurationImportSelectorTests { @Test void determineImportsWhenUsingNonMetaWithoutClassesShouldBeSame() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); } @Test void determineImportsWhenUsingNonMetaWithClassesShouldBeSame() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); + .determineImports(getAnnotationMetadata(ImportAutoConfigurationWithItemsTwo.class)); assertThat(set1).isEqualTo(set2); } @Test void determineImportsWhenUsingMetaExcludeWithoutClassesShouldBeEqual() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedTwo.class)); assertThat(set1).isEqualTo(set2); assertThat(set1).hasSameHashCodeAs(set2); } @@ -159,18 +159,18 @@ class ImportAutoConfigurationImportSelectorTests { @Test void determineImportsWhenUsingMetaDifferentExcludeWithoutClassesShouldBeDifferent() throws Exception { Set set1 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); Set set2 = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationWithUnrelatedTwo.class)); assertThat(set1).isNotEqualTo(set2); } @Test void determineImportsShouldNotSetPackageImport() throws Exception { - Class packageImportsClass = ClassUtils.resolveClassName( - "org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImports", null); + Class packageImportsClass = ClassUtils + .resolveClassName("org.springframework.boot.autoconfigure.AutoConfigurationPackages.PackageImports", null); Set selectedImports = this.importSelector - .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); + .determineImports(getAnnotationMetadata(ImportMetaAutoConfigurationExcludeWithUnrelatedOne.class)); for (Object selectedImport : selectedImports) { assertThat(selectedImport).isNotInstanceOf(packageImportsClass); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java index ba4f4aa661..cee16660f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ class SharedMetadataReaderFactoryContextInitializerTests { SpringApplication application = new SpringApplication(TestConfig.class); application.setWebApplicationType(WebApplicationType.NONE); List> initializers = (List>) ReflectionTestUtils - .getField(application, "initializers"); + .getField(application, "initializers"); // Simulate what would happen if an initializer was added using spring.factories // and happened to be loaded first initializers.add(0, new Initializer()); @@ -72,7 +72,8 @@ class SharedMetadataReaderFactoryContextInitializerTests { ConfigurationClassPostProcessor configurationAnnotationPostProcessor = mock( ConfigurationClassPostProcessor.class); BeanDefinition beanDefinition = BeanDefinitionBuilder - .genericBeanDefinition(ConfigurationClassPostProcessor.class).getBeanDefinition(); + .genericBeanDefinition(ConfigurationClassPostProcessor.class) + .getBeanDefinition(); ((AbstractBeanDefinition) beanDefinition).setInstanceSupplier(() -> configurationAnnotationPostProcessor); registry.registerBeanDefinition(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME, beanDefinition); @@ -83,10 +84,10 @@ class SharedMetadataReaderFactoryContextInitializerTests { ConfigurationClassPostProcessor bean = context.getBean(ConfigurationClassPostProcessor.class); assertThat(bean).isSameAs(configurationAnnotationPostProcessor); ArgumentCaptor metadataReaderFactory = ArgumentCaptor - .forClass(MetadataReaderFactory.class); + .forClass(MetadataReaderFactory.class); then(configurationAnnotationPostProcessor).should().setMetadataReaderFactory(metadataReaderFactory.capture()); assertThat(metadataReaderFactory.getValue()) - .isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class); + .isInstanceOf(ConcurrentReferenceCachingMetadataReaderFactory.class); } static class TestConfig { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java index 978607bd1d..3ed1577c34 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/SpringBootApplicationTests.java @@ -38,28 +38,28 @@ class SpringBootApplicationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", true); } @Test void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootApplication.class, Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootApplication.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", false); } @Test void nameGeneratorDefaultToBeanNameGenerator() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, ComponentScan.class); + .getMergedAnnotationAttributes(DefaultSpringBootApplication.class, ComponentScan.class); assertThat(attributes).containsEntry("nameGenerator", BeanNameGenerator.class); } @Test void nameGeneratorCanBeSpecified() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(CustomNameGeneratorConfiguration.class, ComponentScan.class); + .getMergedAnnotationAttributes(CustomNameGeneratorConfiguration.class, ComponentScan.class); assertThat(attributes).containsEntry("nameGenerator", TestBeanNameGenerator.class); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java index bb78ced983..f417db4c52 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/TestAutoConfigurationPackageRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -32,7 +32,7 @@ public class TestAutoConfigurationPackageRegistrar implements ImportBeanDefiniti @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(TestAutoConfigurationPackage.class.getName(), true)); + .fromMap(metadata.getAnnotationAttributes(TestAutoConfigurationPackage.class.getName(), true)); AutoConfigurationPackages.register(registry, ClassUtils.getPackageName(attributes.getString("value"))); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index 389ec27b0a..cbf6b84edf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -61,7 +61,7 @@ class SpringApplicationAdminJmxAutoConfigurationTests { private final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SpringApplicationAdminJmxAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SpringApplicationAdminJmxAutoConfiguration.class)); @Test void notRegisteredWhenThereAreNoMBeanExporter() { @@ -75,46 +75,48 @@ class SpringApplicationAdminJmxAutoConfigurationTests { @Test void notRegisteredByDefaultWhenThereAreMultipleMBeanExporters() { this.contextRunner.withUserConfiguration(MultipleMBeanExportersConfiguration.class) - .run((context) -> assertThatExceptionOfType(InstanceNotFoundException.class) - .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName()))); + .run((context) -> assertThatExceptionOfType(InstanceNotFoundException.class) + .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName()))); } @Test void registeredWithPropertyWhenThereAreMultipleMBeanExporters() { this.contextRunner.withUserConfiguration(MultipleMBeanExportersConfiguration.class) - .withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { - ObjectName objectName = createDefaultObjectName(); - ObjectInstance objectInstance = this.server.getObjectInstance(objectName); - assertThat(objectInstance).as("Lifecycle bean should have been registered").isNotNull(); - }); + .withPropertyValues(ENABLE_ADMIN_PROP) + .run((context) -> { + ObjectName objectName = createDefaultObjectName(); + ObjectInstance objectInstance = this.server.getObjectInstance(objectName); + assertThat(objectInstance).as("Lifecycle bean should have been registered").isNotNull(); + }); } @Test void registerWithCustomJmxNameWhenThereAreMultipleMBeanExporters() { String customJmxName = "org.acme:name=FooBar"; this.contextRunner.withUserConfiguration(MultipleMBeanExportersConfiguration.class) - .withSystemProperties("spring.application.admin.jmx-name=" + customJmxName) - .withPropertyValues(ENABLE_ADMIN_PROP).run((context) -> { - try { - this.server.getObjectInstance(createObjectName(customJmxName)); - } - catch (InstanceNotFoundException ex) { - fail("Admin MBean should have been exposed with custom name"); - } - assertThatExceptionOfType(InstanceNotFoundException.class) - .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName())); - }); + .withSystemProperties("spring.application.admin.jmx-name=" + customJmxName) + .withPropertyValues(ENABLE_ADMIN_PROP) + .run((context) -> { + try { + this.server.getObjectInstance(createObjectName(customJmxName)); + } + catch (InstanceNotFoundException ex) { + fail("Admin MBean should have been exposed with custom name"); + } + assertThatExceptionOfType(InstanceNotFoundException.class) + .isThrownBy(() -> this.server.getObjectInstance(createDefaultObjectName())); + }); } @Test void registerWithSimpleWebApp() throws Exception { try (ConfigurableApplicationContext context = new SpringApplicationBuilder() - .sources(ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, - MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) - .run("--" + ENABLE_ADMIN_PROP, "--server.port=0")) { + .sources(ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, + MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) + .run("--" + ENABLE_ADMIN_PROP, "--server.port=0")) { assertThat(context).isInstanceOf(ServletWebServerApplicationContext.class); assertThat(this.server.getAttribute(createDefaultObjectName(), "EmbeddedWebApplication")) - .isEqualTo(Boolean.TRUE); + .isEqualTo(Boolean.TRUE); int expected = ((ServletWebServerApplicationContext) context).getWebServer().getPort(); String actual = getProperty(createDefaultObjectName(), "local.server.port"); assertThat(actual).isEqualTo(String.valueOf(expected)); @@ -124,15 +126,15 @@ class SpringApplicationAdminJmxAutoConfigurationTests { @Test void onlyRegisteredOnceWhenThereIsAChildContext() { SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder().web(WebApplicationType.NONE) - .sources(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class); + .sources(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class); SpringApplicationBuilder childBuilder = parentBuilder - .child(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) - .web(WebApplicationType.NONE); + .child(MultipleMBeanExportersConfiguration.class, SpringApplicationAdminJmxAutoConfiguration.class) + .web(WebApplicationType.NONE); try (ConfigurableApplicationContext parent = parentBuilder.run("--" + ENABLE_ADMIN_PROP); ConfigurableApplicationContext child = childBuilder.run("--" + ENABLE_ADMIN_PROP)) { BeanFactoryUtils.beanOfType(parent.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> BeanFactoryUtils - .beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class)); + .beanOfType(child.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java index c7ea9beeed..bb3f63adf6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -101,7 +101,7 @@ import static org.mockito.Mockito.mock; class RabbitAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); @Test void testDefaultRabbitConfiguration() { @@ -116,13 +116,14 @@ class RabbitAutoConfigurationTests { assertThat(amqpAdmin).isNotNull(); assertThat(connectionFactory.getHost()).isEqualTo("localhost"); assertThat(getTargetConnectionFactory(context).getRequestedChannelMax()) - .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_MAX); + .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_MAX); assertThat(connectionFactory.isPublisherConfirms()).isFalse(); assertThat(connectionFactory.isPublisherReturns()).isFalse(); assertThat(connectionFactory.getRabbitConnectionFactory().getChannelRpcTimeout()) - .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_RPC_TIMEOUT); + .isEqualTo(com.rabbitmq.client.ConnectionFactory.DEFAULT_CHANNEL_RPC_TIMEOUT); assertThat(context.containsBean("rabbitListenerContainerFactory")) - .as("Listener container factory should be created by default").isTrue(); + .as("Listener container factory should be created by default") + .isTrue(); }); } @@ -150,22 +151,22 @@ class RabbitAutoConfigurationTests { @SuppressWarnings("unchecked") void testConnectionFactoryWithOverrides() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", - "spring.rabbitmq.address-shuffle-mode=random", "spring.rabbitmq.username:alice", - "spring.rabbitmq.password:secret", "spring.rabbitmq.virtual_host:/vhost", - "spring.rabbitmq.connection-timeout:123", "spring.rabbitmq.channel-rpc-timeout:140") - .run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); - assertThat(connectionFactory.getPort()).isEqualTo(9000); - assertThat(connectionFactory).hasFieldOrPropertyWithValue("addressShuffleMode", - AddressShuffleMode.RANDOM); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); - com.rabbitmq.client.ConnectionFactory rcf = connectionFactory.getRabbitConnectionFactory(); - assertThat(rcf.getConnectionTimeout()).isEqualTo(123); - assertThat(rcf.getChannelRpcTimeout()).isEqualTo(140); - assertThat((List
) ReflectionTestUtils.getField(connectionFactory, "addresses")).hasSize(1); - }); + .withPropertyValues("spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", + "spring.rabbitmq.address-shuffle-mode=random", "spring.rabbitmq.username:alice", + "spring.rabbitmq.password:secret", "spring.rabbitmq.virtual_host:/vhost", + "spring.rabbitmq.connection-timeout:123", "spring.rabbitmq.channel-rpc-timeout:140") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); + assertThat(connectionFactory.getPort()).isEqualTo(9000); + assertThat(connectionFactory).hasFieldOrPropertyWithValue("addressShuffleMode", + AddressShuffleMode.RANDOM); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); + com.rabbitmq.client.ConnectionFactory rcf = connectionFactory.getRabbitConnectionFactory(); + assertThat(rcf.getConnectionTimeout()).isEqualTo(123); + assertThat(rcf.getChannelRpcTimeout()).isEqualTo(140); + assertThat((List
) ReflectionTestUtils.getField(connectionFactory, "addresses")).hasSize(1); + }); } @Test @@ -179,12 +180,12 @@ class RabbitAutoConfigurationTests { given(rcf.newConnection(isNull(), eq(addresses), anyString())).willReturn(mock(Connection.class)); ReflectionTestUtils.setField(connectionFactory, "rabbitConnectionFactory", rcf); try (org.springframework.amqp.rabbit.connection.Connection connection = connectionFactory - .createConnection()) { + .createConnection()) { then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#0")); } connectionFactory.resetConnection(); try (org.springframework.amqp.rabbit.connection.Connection connection = connectionFactory - .createConnection()) { + .createConnection()) { then(rcf).should().newConnection(isNull(), eq(addresses), eq("test#1")); } }); @@ -193,68 +194,75 @@ class RabbitAutoConfigurationTests { @Test void testConnectionFactoryEmptyVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); + }); } @Test void testConnectionFactoryVirtualHostNoLeadingSlash() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:foo").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:foo") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("foo"); + }); } @Test void testConnectionFactoryVirtualHostMultiLeadingSlashes() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:///foo").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("///foo"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:///foo") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("///foo"); + }); } @Test void testConnectionFactoryDefaultVirtualHost() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.virtual_host:/").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); - }); + .withPropertyValues("spring.rabbitmq.virtual_host:/") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getVirtualHost()).isEqualTo("/"); + }); } @Test void testConnectionFactoryPublisherConfirmTypeCorrelated() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.publisher-confirm-type=correlated").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.isPublisherConfirms()).isTrue(); - assertThat(connectionFactory.isSimplePublisherConfirms()).isFalse(); - }); + .withPropertyValues("spring.rabbitmq.publisher-confirm-type=correlated") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.isPublisherConfirms()).isTrue(); + assertThat(connectionFactory.isSimplePublisherConfirms()).isFalse(); + }); } @Test void testConnectionFactoryPublisherConfirmTypeSimple() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.publisher-confirm-type=simple").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.isPublisherConfirms()).isFalse(); - assertThat(connectionFactory.isSimplePublisherConfirms()).isTrue(); - }); + .withPropertyValues("spring.rabbitmq.publisher-confirm-type=simple") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.isPublisherConfirms()).isFalse(); + assertThat(connectionFactory.isSimplePublisherConfirms()).isTrue(); + }); } @Test void testConnectionFactoryPublisherReturns() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.publisher-returns=true").run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(connectionFactory.isPublisherReturns()).isTrue(); - assertThat(getMandatory(rabbitTemplate)).isTrue(); - }); + .withPropertyValues("spring.rabbitmq.publisher-returns=true") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(connectionFactory.isPublisherReturns()).isTrue(); + assertThat(getMandatory(rabbitTemplate)).isTrue(); + }); } @Test @@ -268,108 +276,113 @@ class RabbitAutoConfigurationTests { @Test void testRabbitTemplateRetry() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.rabbitmq.template.retry.enabled:true", "spring.rabbitmq.template.retry.maxAttempts:4", - "spring.rabbitmq.template.retry.initialInterval:2000", "spring.rabbitmq.template.retry.multiplier:1.5", - "spring.rabbitmq.template.retry.maxInterval:5000", "spring.rabbitmq.template.receiveTimeout:123", - "spring.rabbitmq.template.replyTimeout:456").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("receiveTimeout", 123L); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("replyTimeout", 456L); - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, - "retryTemplate"); - assertThat(retryTemplate).isNotNull(); - SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, - "retryPolicy"); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils - .getField(retryTemplate, "backOffPolicy"); - assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); - assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); - assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); - assertThat(backOffPolicy.getMaxInterval()).isEqualTo(5000); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", + "spring.rabbitmq.template.retry.maxAttempts:4", + "spring.rabbitmq.template.retry.initialInterval:2000", + "spring.rabbitmq.template.retry.multiplier:1.5", "spring.rabbitmq.template.retry.maxInterval:5000", + "spring.rabbitmq.template.receiveTimeout:123", "spring.rabbitmq.template.replyTimeout:456") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("receiveTimeout", 123L); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("replyTimeout", 456L); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, + "retryTemplate"); + assertThat(retryTemplate).isNotNull(); + SimpleRetryPolicy retryPolicy = (SimpleRetryPolicy) ReflectionTestUtils.getField(retryTemplate, + "retryPolicy"); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils + .getField(retryTemplate, "backOffPolicy"); + assertThat(retryPolicy.getMaxAttempts()).isEqualTo(4); + assertThat(backOffPolicy.getInitialInterval()).isEqualTo(2000); + assertThat(backOffPolicy.getMultiplier()).isEqualTo(1.5); + assertThat(backOffPolicy.getMaxInterval()).isEqualTo(5000); + }); } @Test void testRabbitTemplateRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", - "spring.rabbitmq.template.retry.initialInterval:2000") - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, - "retryTemplate"); - assertThat(retryTemplate).isNotNull(); - ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils - .getField(retryTemplate, "backOffPolicy"); - assertThat(backOffPolicy) - .isSameAs(context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy); - assertThat(backOffPolicy.getInitialInterval()).isEqualTo(100); - }); + .withPropertyValues("spring.rabbitmq.template.retry.enabled:true", + "spring.rabbitmq.template.retry.initialInterval:2000") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(rabbitTemplate, + "retryTemplate"); + assertThat(retryTemplate).isNotNull(); + ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) ReflectionTestUtils + .getField(retryTemplate, "backOffPolicy"); + assertThat(backOffPolicy) + .isSameAs(context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).backOffPolicy); + assertThat(backOffPolicy.getInitialInterval()).isEqualTo(100); + }); } @Test void testRabbitTemplateExchangeAndRoutingKey() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", - "spring.rabbitmq.template.routing-key:my-routing-key") - .run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate.getExchange()).isEqualTo("my-exchange"); - assertThat(rabbitTemplate.getRoutingKey()).isEqualTo("my-routing-key"); - }); + .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", + "spring.rabbitmq.template.routing-key:my-routing-key") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate.getExchange()).isEqualTo("my-exchange"); + assertThat(rabbitTemplate.getRoutingKey()).isEqualTo("my-routing-key"); + }); } @Test void testRabbitTemplateDefaultReceiveQueue() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.default-receive-queue:default-queue").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("defaultReceiveQueue", "default-queue"); - }); + .withPropertyValues("spring.rabbitmq.template.default-receive-queue:default-queue") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(rabbitTemplate).hasFieldOrPropertyWithValue("defaultReceiveQueue", "default-queue"); + }); } @Test void testRabbitTemplateMandatory() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.mandatory:true").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(getMandatory(rabbitTemplate)).isTrue(); - }); + .withPropertyValues("spring.rabbitmq.template.mandatory:true") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(getMandatory(rabbitTemplate)).isTrue(); + }); } @Test void testRabbitTemplateMandatoryDisabledEvenIfPublisherReturnsIsSet() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.rabbitmq.template.mandatory:false", "spring.rabbitmq.publisher-returns=true").run((context) -> { - RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); - assertThat(getMandatory(rabbitTemplate)).isFalse(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.template.mandatory:false", "spring.rabbitmq.publisher-returns=true") + .run((context) -> { + RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.class); + assertThat(getMandatory(rabbitTemplate)).isFalse(); + }); } @Test void testRabbitTemplateConfigurersIsAvailable() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(RabbitTemplateConfigurer.class)); + .run((context) -> assertThat(context).hasSingleBean(RabbitTemplateConfigurer.class)); } @Test void testRabbitTemplateConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", - "spring.rabbitmq.template.routing-key:my-routing-key", - "spring.rabbitmq.template.default-receive-queue:default-queue") - .run((context) -> { - RabbitTemplateConfigurer configurer = context.getBean(RabbitTemplateConfigurer.class); - RabbitTemplate template = mock(RabbitTemplate.class); - ConnectionFactory connectionFactory = mock(ConnectionFactory.class); - configurer.configure(template, connectionFactory); - then(template).should() - .setMessageConverter(context.getBean("myMessageConverter", MessageConverter.class)); - then(template).should().setExchange("my-exchange"); - then(template).should().setRoutingKey("my-routing-key"); - then(template).should().setDefaultReceiveQueue("default-queue"); - }); + .withPropertyValues("spring.rabbitmq.template.exchange:my-exchange", + "spring.rabbitmq.template.routing-key:my-routing-key", + "spring.rabbitmq.template.default-receive-queue:default-queue") + .run((context) -> { + RabbitTemplateConfigurer configurer = context.getBean(RabbitTemplateConfigurer.class); + RabbitTemplate template = mock(RabbitTemplate.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + configurer.configure(template, connectionFactory); + then(template).should() + .setMessageConverter(context.getBean("myMessageConverter", MessageConverter.class)); + then(template).should().setExchange("my-exchange"); + then(template).should().setRoutingKey("my-routing-key"); + then(template).should().setDefaultReceiveQueue("default-queue"); + }); } @Test @@ -386,16 +399,16 @@ class RabbitAutoConfigurationTests { @Test void testConnectionFactoryCacheSettings() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.cache.channel.size=23", - "spring.rabbitmq.cache.channel.checkoutTimeout=1000", - "spring.rabbitmq.cache.connection.mode=CONNECTION", "spring.rabbitmq.cache.connection.size=2") - .run((context) -> { - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(connectionFactory.getChannelCacheSize()).isEqualTo(23); - assertThat(connectionFactory.getCacheMode()).isEqualTo(CacheMode.CONNECTION); - assertThat(connectionFactory.getConnectionCacheSize()).isEqualTo(2); - assertThat(connectionFactory).hasFieldOrPropertyWithValue("channelCheckoutTimeout", 1000L); - }); + .withPropertyValues("spring.rabbitmq.cache.channel.size=23", + "spring.rabbitmq.cache.channel.checkoutTimeout=1000", + "spring.rabbitmq.cache.connection.mode=CONNECTION", "spring.rabbitmq.cache.connection.size=2") + .run((context) -> { + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(connectionFactory.getChannelCacheSize()).isEqualTo(23); + assertThat(connectionFactory.getCacheMode()).isEqualTo(CacheMode.CONNECTION); + assertThat(connectionFactory.getConnectionCacheSize()).isEqualTo(2); + assertThat(connectionFactory).hasFieldOrPropertyWithValue("channelCheckoutTimeout", 1000L); + }); } @Test @@ -418,17 +431,17 @@ class RabbitAutoConfigurationTests { void testStaticQueues() { // There should NOT be an AmqpAdmin bean when dynamic is switch to false this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.dynamic:false") - .run((context) -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> context.getBean(AmqpAdmin.class)) - .withMessageContaining("No qualifying bean of type '" + AmqpAdmin.class.getName() + "'")); + .withPropertyValues("spring.rabbitmq.dynamic:false") + .run((context) -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> context.getBean(AmqpAdmin.class)) + .withMessageContaining("No qualifying bean of type '" + AmqpAdmin.class.getName() + "'")); } @Test void testEnableRabbitCreateDefaultContainerFactory() { this.contextRunner.withUserConfiguration(EnableRabbitConfiguration.class).run((context) -> { RabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", RabbitListenerContainerFactory.class); assertThat(rabbitListenerContainerFactory.getClass()).isEqualTo(SimpleRabbitListenerContainerFactory.class); }); } @@ -437,7 +450,7 @@ class RabbitAutoConfigurationTests { void testRabbitListenerContainerFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration5.class).run((context) -> { SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); rabbitListenerContainerFactory.setBatchSize(10); then(rabbitListenerContainerFactory).should().setBatchSize(10); assertThat(rabbitListenerContainerFactory.getAdviceChain()).isNull(); @@ -447,84 +460,82 @@ class RabbitAutoConfigurationTests { @Test void testSimpleRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner - .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", - "spring.rabbitmq.listener.simple.retry.maxAttempts:4", - "spring.rabbitmq.listener.simple.retry.initialInterval:2000", - "spring.rabbitmq.listener.simple.retry.multiplier:1.5", - "spring.rabbitmq.listener.simple.retry.maxInterval:5000", - "spring.rabbitmq.listener.simple.autoStartup:false", - "spring.rabbitmq.listener.simple.acknowledgeMode:manual", - "spring.rabbitmq.listener.simple.concurrency:5", - "spring.rabbitmq.listener.simple.maxConcurrency:10", - "spring.rabbitmq.listener.simple.prefetch:40", - "spring.rabbitmq.listener.simple.defaultRequeueRejected:false", - "spring.rabbitmq.listener.simple.idleEventInterval:5", - "spring.rabbitmq.listener.simple.batchSize:20", - "spring.rabbitmq.listener.simple.missingQueuesFatal:false") - .run((context) -> { - SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("concurrentConsumers", 5); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("maxConcurrentConsumers", - 10); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("batchSize", 20); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", false); - checkCommonProps(context, rabbitListenerContainerFactory); - }); + .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) + .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", + "spring.rabbitmq.listener.simple.retry.maxAttempts:4", + "spring.rabbitmq.listener.simple.retry.initialInterval:2000", + "spring.rabbitmq.listener.simple.retry.multiplier:1.5", + "spring.rabbitmq.listener.simple.retry.maxInterval:5000", + "spring.rabbitmq.listener.simple.autoStartup:false", + "spring.rabbitmq.listener.simple.acknowledgeMode:manual", + "spring.rabbitmq.listener.simple.concurrency:5", + "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40", + "spring.rabbitmq.listener.simple.defaultRequeueRejected:false", + "spring.rabbitmq.listener.simple.idleEventInterval:5", + "spring.rabbitmq.listener.simple.batchSize:20", + "spring.rabbitmq.listener.simple.missingQueuesFatal:false") + .run((context) -> { + SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("concurrentConsumers", 5); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("maxConcurrentConsumers", 10); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("batchSize", 20); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", false); + checkCommonProps(context, rabbitListenerContainerFactory); + }); } @Test void testDirectRabbitListenerContainerFactoryWithCustomSettings() { this.contextRunner - .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:direct", - "spring.rabbitmq.listener.direct.retry.enabled:true", - "spring.rabbitmq.listener.direct.retry.maxAttempts:4", - "spring.rabbitmq.listener.direct.retry.initialInterval:2000", - "spring.rabbitmq.listener.direct.retry.multiplier:1.5", - "spring.rabbitmq.listener.direct.retry.maxInterval:5000", - "spring.rabbitmq.listener.direct.autoStartup:false", - "spring.rabbitmq.listener.direct.acknowledgeMode:manual", - "spring.rabbitmq.listener.direct.consumers-per-queue:5", - "spring.rabbitmq.listener.direct.prefetch:40", - "spring.rabbitmq.listener.direct.defaultRequeueRejected:false", - "spring.rabbitmq.listener.direct.idleEventInterval:5", - "spring.rabbitmq.listener.direct.missingQueuesFatal:true") - .run((context) -> { - DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("consumersPerQueue", 5); - assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", true); - checkCommonProps(context, rabbitListenerContainerFactory); - }); + .withUserConfiguration(MessageConvertersConfiguration.class, MessageRecoverersConfiguration.class) + .withPropertyValues("spring.rabbitmq.listener.type:direct", + "spring.rabbitmq.listener.direct.retry.enabled:true", + "spring.rabbitmq.listener.direct.retry.maxAttempts:4", + "spring.rabbitmq.listener.direct.retry.initialInterval:2000", + "spring.rabbitmq.listener.direct.retry.multiplier:1.5", + "spring.rabbitmq.listener.direct.retry.maxInterval:5000", + "spring.rabbitmq.listener.direct.autoStartup:false", + "spring.rabbitmq.listener.direct.acknowledgeMode:manual", + "spring.rabbitmq.listener.direct.consumers-per-queue:5", + "spring.rabbitmq.listener.direct.prefetch:40", + "spring.rabbitmq.listener.direct.defaultRequeueRejected:false", + "spring.rabbitmq.listener.direct.idleEventInterval:5", + "spring.rabbitmq.listener.direct.missingQueuesFatal:true") + .run((context) -> { + DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("consumersPerQueue", 5); + assertThat(rabbitListenerContainerFactory).hasFieldOrPropertyWithValue("missingQueuesFatal", true); + checkCommonProps(context, rabbitListenerContainerFactory); + }); } @Test void testSimpleRabbitListenerContainerFactoryRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", - "spring.rabbitmq.listener.simple.retry.maxAttempts:4") - .run((context) -> { - SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); - assertListenerRetryTemplate(rabbitListenerContainerFactory, - context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); - }); + .withPropertyValues("spring.rabbitmq.listener.simple.retry.enabled:true", + "spring.rabbitmq.listener.simple.retry.maxAttempts:4") + .run((context) -> { + SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", SimpleRabbitListenerContainerFactory.class); + assertListenerRetryTemplate(rabbitListenerContainerFactory, + context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); + }); } @Test void testDirectRabbitListenerContainerFactoryRetryWithCustomizer() { this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:direct", - "spring.rabbitmq.listener.direct.retry.enabled:true", - "spring.rabbitmq.listener.direct.retry.maxAttempts:4") - .run((context) -> { - DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context - .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); - assertListenerRetryTemplate(rabbitListenerContainerFactory, - context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); - }); + .withPropertyValues("spring.rabbitmq.listener.type:direct", + "spring.rabbitmq.listener.direct.retry.enabled:true", + "spring.rabbitmq.listener.direct.retry.maxAttempts:4") + .run((context) -> { + DirectRabbitListenerContainerFactory rabbitListenerContainerFactory = context + .getBean("rabbitListenerContainerFactory", DirectRabbitListenerContainerFactory.class); + assertListenerRetryTemplate(rabbitListenerContainerFactory, + context.getBean(RabbitRetryTemplateCustomizerConfiguration.class).retryPolicy); + }); } private void assertListenerRetryTemplate(AbstractRabbitListenerContainerFactory rabbitListenerContainerFactory, @@ -539,59 +550,61 @@ class RabbitAutoConfigurationTests { @Test void testRabbitListenerContainerFactoryConfigurersAreAvailable() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues( - "spring.rabbitmq.listener.simple.concurrency:5", "spring.rabbitmq.listener.simple.maxConcurrency:10", - "spring.rabbitmq.listener.simple.prefetch:40", "spring.rabbitmq.listener.direct.consumers-per-queue:5", - "spring.rabbitmq.listener.direct.prefetch:40").run((context) -> { - assertThat(context).hasSingleBean(SimpleRabbitListenerContainerFactoryConfigurer.class); - assertThat(context).hasSingleBean(DirectRabbitListenerContainerFactoryConfigurer.class); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.listener.simple.concurrency:5", + "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40", + "spring.rabbitmq.listener.direct.consumers-per-queue:5", + "spring.rabbitmq.listener.direct.prefetch:40") + .run((context) -> { + assertThat(context).hasSingleBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + assertThat(context).hasSingleBean(DirectRabbitListenerContainerFactoryConfigurer.class); + }); } @Test void testSimpleRabbitListenerContainerFactoryConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.concurrency:5", - "spring.rabbitmq.listener.simple.maxConcurrency:10", - "spring.rabbitmq.listener.simple.prefetch:40") - .run((context) -> { - SimpleRabbitListenerContainerFactoryConfigurer configurer = context - .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); - SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); - configurer.configure(factory, mock(ConnectionFactory.class)); - then(factory).should().setConcurrentConsumers(5); - then(factory).should().setMaxConcurrentConsumers(10); - then(factory).should().setPrefetchCount(40); - }); + .withPropertyValues("spring.rabbitmq.listener.simple.concurrency:5", + "spring.rabbitmq.listener.simple.maxConcurrency:10", "spring.rabbitmq.listener.simple.prefetch:40") + .run((context) -> { + SimpleRabbitListenerContainerFactoryConfigurer configurer = context + .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); + configurer.configure(factory, mock(ConnectionFactory.class)); + then(factory).should().setConcurrentConsumers(5); + then(factory).should().setMaxConcurrentConsumers(10); + then(factory).should().setPrefetchCount(40); + }); } @Test void testSimpleRabbitListenerContainerFactoryConfigurerEnableDeBatchingWithConsumerBatchEnabled() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.simple.consumer-batch-enabled:true").run((context) -> { - SimpleRabbitListenerContainerFactoryConfigurer configurer = context - .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); - SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); - configurer.configure(factory, mock(ConnectionFactory.class)); - then(factory).should().setConsumerBatchEnabled(true); - }); + .withPropertyValues("spring.rabbitmq.listener.simple.consumer-batch-enabled:true") + .run((context) -> { + SimpleRabbitListenerContainerFactoryConfigurer configurer = context + .getBean(SimpleRabbitListenerContainerFactoryConfigurer.class); + SimpleRabbitListenerContainerFactory factory = mock(SimpleRabbitListenerContainerFactory.class); + configurer.configure(factory, mock(ConnectionFactory.class)); + then(factory).should().setConsumerBatchEnabled(true); + }); } @Test void testDirectRabbitListenerContainerFactoryConfigurerUsesConfig() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.direct.consumers-per-queue:5", - "spring.rabbitmq.listener.direct.prefetch:40", - "spring.rabbitmq.listener.direct.de-batching-enabled:false") - .run((context) -> { - DirectRabbitListenerContainerFactoryConfigurer configurer = context - .getBean(DirectRabbitListenerContainerFactoryConfigurer.class); - DirectRabbitListenerContainerFactory factory = mock(DirectRabbitListenerContainerFactory.class); - configurer.configure(factory, mock(ConnectionFactory.class)); - then(factory).should().setConsumersPerQueue(5); - then(factory).should().setPrefetchCount(40); - then(factory).should().setDeBatchingEnabled(false); - }); + .withPropertyValues("spring.rabbitmq.listener.direct.consumers-per-queue:5", + "spring.rabbitmq.listener.direct.prefetch:40", + "spring.rabbitmq.listener.direct.de-batching-enabled:false") + .run((context) -> { + DirectRabbitListenerContainerFactoryConfigurer configurer = context + .getBean(DirectRabbitListenerContainerFactoryConfigurer.class); + DirectRabbitListenerContainerFactory factory = mock(DirectRabbitListenerContainerFactory.class); + configurer.configure(factory, mock(ConnectionFactory.class)); + then(factory).should().setConsumersPerQueue(5); + then(factory).should().setPrefetchCount(40); + then(factory).should().setDeBatchingEnabled(false); + }); } private void checkCommonProps(AssertableApplicationContext context, @@ -636,19 +649,21 @@ class RabbitAutoConfigurationTests { @Test void customizeRequestedHeartBeat() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.getRequestedHeartbeat()).isEqualTo(20); - }); + .withPropertyValues("spring.rabbitmq.requestedHeartbeat:20") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.getRequestedHeartbeat()).isEqualTo(20); + }); } @Test void customizeRequestedChannelMax() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.requestedChannelMax:12").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.getRequestedChannelMax()).isEqualTo(12); - }); + .withPropertyValues("spring.rabbitmq.requestedChannelMax:12") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.getRequestedChannelMax()).isEqualTo(12); + }); } @Test @@ -663,218 +678,223 @@ class RabbitAutoConfigurationTests { @Test void enableSsl() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.isSSL()).isTrue(); - assertThat(rabbitConnectionFactory.getSocketFactory()).as("SocketFactory must use SSL") - .isInstanceOf(SSLSocketFactory.class); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.isSSL()).isTrue(); + assertThat(rabbitConnectionFactory.getSocketFactory()).as("SocketFactory must use SSL") + .isInstanceOf(SSLSocketFactory.class); + }); } @Test // Make sure that we at least attempt to load the store void enableSslWithNonExistingKeystoreShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStorePassword=secret") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("foo"); - assertThat(context).getFailure().hasMessageContaining("does not exist"); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=foo", + "spring.rabbitmq.ssl.keyStorePassword=secret") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("foo"); + assertThat(context).getFailure().hasMessageContaining("does not exist"); + }); } @Test // Make sure that we at least attempt to load the store void enableSslWithNonExistingTrustStoreShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStorePassword=secret") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("bar"); - assertThat(context).getFailure().hasMessageContaining("does not exist"); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.trustStore=bar", + "spring.rabbitmq.ssl.trustStorePassword=secret") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("bar"); + assertThat(context).getFailure().hasMessageContaining("does not exist"); + }); } @Test void enableSslWithInvalidKeystoreTypeShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=foo", "spring.rabbitmq.ssl.keyStoreType=fooType") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("fooType"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.keyStore=foo", + "spring.rabbitmq.ssl.keyStoreType=fooType") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("fooType"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void enableSslWithInvalidTrustStoreTypeShouldFail() { - this.contextRunner - .withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=bar", "spring.rabbitmq.ssl.trustStoreType=barType") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("barType"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", "spring.rabbitmq.ssl.trustStore=bar", + "spring.rabbitmq.ssl.trustStoreType=barType") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("barType"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void enableSslWithKeystoreTypeAndTrustStoreTypeShouldWork() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", - "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", + "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void enableSslWithValidateServerCertificateFalse(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.validateServerCertificate=false") - .run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.isSSL()).isTrue(); - assertThat(output).contains("TrustEverythingTrustManager", "SECURITY ALERT"); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.validateServerCertificate=false") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.isSSL()).isTrue(); + assertThat(output).contains("TrustEverythingTrustManager", "SECURITY ALERT"); + }); } @Test void enableSslWithValidateServerCertificateDefault(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true").run((context) -> { - com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); - assertThat(rabbitConnectionFactory.isSSL()).isTrue(); - assertThat(output).doesNotContain("TrustEverythingTrustManager", "SECURITY ALERT"); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true") + .run((context) -> { + com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = getTargetConnectionFactory(context); + assertThat(rabbitConnectionFactory.isSSL()).isTrue(); + assertThat(output).doesNotContain("TrustEverythingTrustManager", "SECURITY ALERT"); + }); } @Test void enableSslWithValidStoreAlgorithmShouldWork() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", - "spring.rabbitmq.ssl.keyStoreAlgorithm=PKIX", - "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", - "spring.rabbitmq.ssl.trustStoreAlgorithm=PKIX") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", + "spring.rabbitmq.ssl.keyStoreAlgorithm=PKIX", + "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", + "spring.rabbitmq.ssl.trustStoreAlgorithm=PKIX") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void enableSslWithInvalidKeyStoreAlgorithmShouldFail() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", - "spring.rabbitmq.ssl.keyStoreAlgorithm=test-invalid-algo") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.keyStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.keyStoreType=jks", "spring.rabbitmq.ssl.keyStorePassword=secret", + "spring.rabbitmq.ssl.keyStoreAlgorithm=test-invalid-algo") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void enableSslWithInvalidTrustStoreAlgorithmShouldFail() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.ssl.enabled:true", - "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", - "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", - "spring.rabbitmq.ssl.trustStoreAlgorithm=test-invalid-algo") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); - assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); - }); + .withPropertyValues("spring.rabbitmq.ssl.enabled:true", + "spring.rabbitmq.ssl.trustStore=/org/springframework/boot/autoconfigure/amqp/test.jks", + "spring.rabbitmq.ssl.trustStoreType=jks", "spring.rabbitmq.ssl.trustStorePassword=secret", + "spring.rabbitmq.ssl.trustStoreAlgorithm=test-invalid-algo") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasMessageContaining("test-invalid-algo"); + assertThat(context).getFailure().hasRootCauseInstanceOf(NoSuchAlgorithmException.class); + }); } @Test void whenACredentialsProviderIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { this.contextRunner.withUserConfiguration(CredentialsProviderConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) - .isEqualTo(CredentialsProviderConfiguration.credentialsProvider)); + .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) + .isEqualTo(CredentialsProviderConfiguration.credentialsProvider)); } @Test void whenAPrimaryCredentialsProviderIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { this.contextRunner.withUserConfiguration(PrimaryCredentialsProviderConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) - .isEqualTo(PrimaryCredentialsProviderConfiguration.credentialsProvider)); + .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) + .isEqualTo(PrimaryCredentialsProviderConfiguration.credentialsProvider)); } @Test void whenMultipleCredentialsProvidersAreAvailableThenConnectionFactoryUsesDefaultProvider() { this.contextRunner.withUserConfiguration(MultipleCredentialsProvidersConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) - .isInstanceOf(DefaultCredentialsProvider.class)); + .run((context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsProvider()) + .isInstanceOf(DefaultCredentialsProvider.class)); } @Test void whenACredentialsRefreshServiceIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { - this.contextRunner.withUserConfiguration(CredentialsRefreshServiceConfiguration.class).run( - (context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) - .isEqualTo(CredentialsRefreshServiceConfiguration.credentialsRefreshService)); + this.contextRunner.withUserConfiguration(CredentialsRefreshServiceConfiguration.class) + .run((context) -> assertThat( + getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) + .isEqualTo(CredentialsRefreshServiceConfiguration.credentialsRefreshService)); } @Test void whenAPrimaryCredentialsRefreshServiceIsAvailableThenConnectionFactoryIsConfiguredToUseIt() { - this.contextRunner.withUserConfiguration(PrimaryCredentialsRefreshServiceConfiguration.class).run( - (context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) - .isEqualTo(PrimaryCredentialsRefreshServiceConfiguration.credentialsRefreshService)); + this.contextRunner.withUserConfiguration(PrimaryCredentialsRefreshServiceConfiguration.class) + .run((context) -> assertThat( + getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) + .isEqualTo(PrimaryCredentialsRefreshServiceConfiguration.credentialsRefreshService)); } @Test void whenMultipleCredentialsRefreshServiceAreAvailableThenConnectionFactoryHasNoCredentialsRefreshService() { - this.contextRunner.withUserConfiguration(MultipleCredentialsRefreshServicesConfiguration.class).run( - (context) -> assertThat(getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) - .isNull()); + this.contextRunner.withUserConfiguration(MultipleCredentialsRefreshServicesConfiguration.class) + .run((context) -> assertThat( + getTargetConnectionFactory(context).params(null).getCredentialsRefreshService()) + .isNull()); } @Test void whenAConnectionFactoryCustomizerIsDefinedThenItCustomizesTheConnectionFactory() { this.contextRunner.withUserConfiguration(SaslConfigCustomizerConfiguration.class) - .run((context) -> assertThat(getTargetConnectionFactory(context).getSaslConfig()) - .isInstanceOf(JDKSaslConfig.class)); + .run((context) -> assertThat(getTargetConnectionFactory(context).getSaslConfig()) + .isInstanceOf(JDKSaslConfig.class)); } @Test void whenMultipleConnectionFactoryCustomizersAreDefinedThenTheyAreCalledInOrder() { this.contextRunner.withUserConfiguration(MultipleConnectionFactoryCustomizersConfiguration.class) - .run((context) -> { - ConnectionFactoryCustomizer firstCustomizer = context.getBean("firstCustomizer", - ConnectionFactoryCustomizer.class); - ConnectionFactoryCustomizer secondCustomizer = context.getBean("secondCustomizer", - ConnectionFactoryCustomizer.class); - InOrder inOrder = inOrder(firstCustomizer, secondCustomizer); - com.rabbitmq.client.ConnectionFactory targetConnectionFactory = getTargetConnectionFactory(context); - then(firstCustomizer).should(inOrder).customize(targetConnectionFactory); - then(secondCustomizer).should(inOrder).customize(targetConnectionFactory); - inOrder.verifyNoMoreInteractions(); - }); + .run((context) -> { + ConnectionFactoryCustomizer firstCustomizer = context.getBean("firstCustomizer", + ConnectionFactoryCustomizer.class); + ConnectionFactoryCustomizer secondCustomizer = context.getBean("secondCustomizer", + ConnectionFactoryCustomizer.class); + InOrder inOrder = inOrder(firstCustomizer, secondCustomizer); + com.rabbitmq.client.ConnectionFactory targetConnectionFactory = getTargetConnectionFactory(context); + then(firstCustomizer).should(inOrder).customize(targetConnectionFactory); + then(secondCustomizer).should(inOrder).customize(targetConnectionFactory); + inOrder.verifyNoMoreInteractions(); + }); } @Test @SuppressWarnings("unchecked") void whenASimpleContainerCustomizerIsDefinedThenItIsCalledToConfigureTheContainer() { this.contextRunner.withUserConfiguration(SimpleContainerCustomizerConfiguration.class) - .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() - .configure(any(SimpleMessageListenerContainer.class))); + .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() + .configure(any(SimpleMessageListenerContainer.class))); } @Test @SuppressWarnings("unchecked") void whenADirectContainerCustomizerIsDefinedThenItIsCalledToConfigureTheContainer() { this.contextRunner.withUserConfiguration(DirectContainerCustomizerConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:direct") - .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() - .configure(any(DirectMessageListenerContainer.class))); + .withPropertyValues("spring.rabbitmq.listener.type:direct") + .run((context) -> then(context.getBean(ContainerCustomizer.class)).should() + .configure(any(DirectMessageListenerContainer.class))); } private com.rabbitmq.client.ConnectionFactory getTargetConnectionFactory(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java index 8a13cd4b3b..78c36a1e81 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitPropertiesTests.java @@ -237,7 +237,7 @@ class RabbitPropertiesTests { void customAddresses() { this.properties.setAddresses("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); assertThat(this.properties.getAddresses()) - .isEqualTo("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); + .isEqualTo("user:secret@rabbit1.example.com:1234/alpha,rabbit2.example.com"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java index d50c20e59a..eec28db57a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitStreamConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,31 +58,34 @@ import static org.mockito.Mockito.mock; class RabbitStreamConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); @Test @SuppressWarnings("unchecked") void whenListenerTypeIsStreamThenStreamListenerContainerAndEnvironmentAreAutoConfigured() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.listener.type:stream").run((context) -> { - RabbitListenerEndpointRegistry registry = context.getBean(RabbitListenerEndpointRegistry.class); - MessageListenerContainer listenerContainer = registry.getListenerContainer("test"); - assertThat(listenerContainer).isInstanceOf(StreamListenerContainer.class); - assertThat(listenerContainer).extracting("consumerCustomizer").isNotNull(); - assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) - .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN).isFalse(); - then(context.getBean(ContainerCustomizer.class)).should().configure(listenerContainer); - assertThat(context).hasSingleBean(Environment.class); - }); + .withPropertyValues("spring.rabbitmq.listener.type:stream") + .run((context) -> { + RabbitListenerEndpointRegistry registry = context.getBean(RabbitListenerEndpointRegistry.class); + MessageListenerContainer listenerContainer = registry.getListenerContainer("test"); + assertThat(listenerContainer).isInstanceOf(StreamListenerContainer.class); + assertThat(listenerContainer).extracting("consumerCustomizer").isNotNull(); + assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) + .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN) + .isFalse(); + then(context.getBean(ContainerCustomizer.class)).should().configure(listenerContainer); + assertThat(context).hasSingleBean(Environment.class); + }); } @Test void whenNativeListenerIsEnabledThenContainerFactoryIsConfiguredToUseNativeListeners() { this.contextRunner - .withPropertyValues("spring.rabbitmq.listener.type:stream", - "spring.rabbitmq.listener.stream.native-listener:true") - .run((context) -> assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) - .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN).isTrue()); + .withPropertyValues("spring.rabbitmq.listener.type:stream", + "spring.rabbitmq.listener.stream.native-listener:true") + .run((context) -> assertThat(context.getBean(StreamRabbitListenerContainerFactory.class)) + .extracting("nativeListener", InstanceOfAssertFactories.BOOLEAN) + .isTrue()); } @Test @@ -95,18 +98,18 @@ class RabbitStreamConfigurationTests { this.contextRunner.withUserConfiguration(CustomEnvironmentConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Environment.class); assertThat(context.getBean(Environment.class)) - .isSameAs(context.getBean(CustomEnvironmentConfiguration.class).environment); + .isSameAs(context.getBean(CustomEnvironmentConfiguration.class).environment); }); } @Test void whenCustomMessageListenerContainerFactoryIsDefinedThenAutoConfiguredContainerFactoryBacksOff() { this.contextRunner.withUserConfiguration(CustomMessageListenerContainerFactoryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(RabbitListenerContainerFactory.class); - assertThat(context.getBean(RabbitListenerContainerFactory.class)).isSameAs(context.getBean( - CustomMessageListenerContainerFactoryConfiguration.class).listenerContainerFactory); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RabbitListenerContainerFactory.class); + assertThat(context.getBean(RabbitListenerContainerFactory.class)).isSameAs(context + .getBean(CustomMessageListenerContainerFactoryConfiguration.class).listenerContainerFactory); + }); } @Test @@ -176,42 +179,45 @@ class RabbitStreamConfigurationTests { @Test void testDefaultRabbitStreamTemplateConfigurationWithoutStreamName() { this.contextRunner.withPropertyValues("spring.rabbitmq.listener.type:stream") - .run((context) -> assertThat(context).doesNotHaveBean(RabbitStreamTemplate.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RabbitStreamTemplate.class)); } @Test void testRabbitStreamTemplateConfigurationWithCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .withPropertyValues("spring.rabbitmq.stream.name:stream-test").run((context) -> { - assertThat(context).hasSingleBean(RabbitStreamTemplate.class); - RabbitStreamTemplate streamTemplate = context.getBean(RabbitStreamTemplate.class); - assertThat(streamTemplate).hasFieldOrPropertyWithValue("streamName", "stream-test"); - assertThat(streamTemplate).extracting("messageConverter") - .isSameAs(context.getBean(MessageConverter.class)); - }); + .withPropertyValues("spring.rabbitmq.stream.name:stream-test") + .run((context) -> { + assertThat(context).hasSingleBean(RabbitStreamTemplate.class); + RabbitStreamTemplate streamTemplate = context.getBean(RabbitStreamTemplate.class); + assertThat(streamTemplate).hasFieldOrPropertyWithValue("streamName", "stream-test"); + assertThat(streamTemplate).extracting("messageConverter") + .isSameAs(context.getBean(MessageConverter.class)); + }); } @Test void testRabbitStreamTemplateConfigurationWithCustomStreamMessageConverter() { this.contextRunner - .withBean("myStreamMessageConverter", StreamMessageConverter.class, - () -> mock(StreamMessageConverter.class)) - .withPropertyValues("spring.rabbitmq.stream.name:stream-test").run((context) -> { - assertThat(context).hasSingleBean(RabbitStreamTemplate.class); - assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("messageConverter") - .isSameAs(context.getBean("myStreamMessageConverter")); - }); + .withBean("myStreamMessageConverter", StreamMessageConverter.class, + () -> mock(StreamMessageConverter.class)) + .withPropertyValues("spring.rabbitmq.stream.name:stream-test") + .run((context) -> { + assertThat(context).hasSingleBean(RabbitStreamTemplate.class); + assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("messageConverter") + .isSameAs(context.getBean("myStreamMessageConverter")); + }); } @Test void testRabbitStreamTemplateConfigurationWithCustomProducerCustomizer() { this.contextRunner - .withBean("myProducerCustomizer", ProducerCustomizer.class, () -> mock(ProducerCustomizer.class)) - .withPropertyValues("spring.rabbitmq.stream.name:stream-test").run((context) -> { - assertThat(context).hasSingleBean(RabbitStreamTemplate.class); - assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("producerCustomizer") - .isSameAs(context.getBean("myProducerCustomizer")); - }); + .withBean("myProducerCustomizer", ProducerCustomizer.class, () -> mock(ProducerCustomizer.class)) + .withPropertyValues("spring.rabbitmq.stream.name:stream-test") + .run((context) -> { + assertThat(context).hasSingleBean(RabbitStreamTemplate.class); + assertThat(context.getBean(RabbitStreamTemplate.class)).extracting("producerCustomizer") + .isSameAs(context.getBean("myProducerCustomizer")); + }); } @Test @@ -219,9 +225,9 @@ class RabbitStreamConfigurationTests { this.contextRunner.withUserConfiguration(EnvironmentBuilderCustomizers.class).run((context) -> { Environment environment = context.getBean(Environment.class); assertThat(environment).extracting("codec") - .isEqualTo(context.getBean(EnvironmentBuilderCustomizers.class).codec); + .isEqualTo(context.getBean(EnvironmentBuilderCustomizers.class).codec); assertThat(environment).extracting("recoveryBackOffDelayPolicy") - .isEqualTo(context.getBean(EnvironmentBuilderCustomizers.class).recoveryBackOffDelayPolicy); + .isEqualTo(context.getBean(EnvironmentBuilderCustomizers.class).recoveryBackOffDelayPolicy); }); } @@ -305,7 +311,7 @@ class RabbitStreamConfigurationTests { @Order(0) EnvironmentBuilderCustomizer customizerB() { return (builder) -> builder.codec(mock(Codec.class)) - .recoveryBackOffDelayPolicy(this.recoveryBackOffDelayPolicy); + .recoveryBackOffDelayPolicy(this.recoveryBackOffDelayPolicy); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java index 243f8165eb..9cca79a157 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/AopAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,18 +46,19 @@ import static org.assertj.core.api.Assertions.assertThat; class AopAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); @Test void aopDisabled() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).withPropertyValues("spring.aop.auto:false") - .run((context) -> { - TestAspect aspect = context.getBean(TestAspect.class); - assertThat(aspect.isCalled()).isFalse(); - TestBean bean = context.getBean(TestBean.class); - bean.foo(); - assertThat(aspect.isCalled()).isFalse(); - }); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .withPropertyValues("spring.aop.auto:false") + .run((context) -> { + TestAspect aspect = context.getBean(TestAspect.class); + assertThat(aspect.isCalled()).isFalse(); + TestBean bean = context.getBean(TestBean.class); + bean.foo(); + assertThat(aspect.isCalled()).isFalse(); + }); } @Test @@ -68,13 +69,15 @@ class AopAutoConfigurationTests { @Test void aopWithEnabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class:true").run(proxyTargetClassEnabled()); + .withPropertyValues("spring.aop.proxy-target-class:true") + .run(proxyTargetClassEnabled()); } @Test void aopWithDisabledProxyTargetClass() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class:false").run(proxyTargetClassDisabled()); + .withPropertyValues("spring.aop.proxy-target-class:false") + .run(proxyTargetClassDisabled()); } @Test @@ -86,11 +89,11 @@ class AopAutoConfigurationTests { @Test void whenGlobalMethodSecurityIsEnabledAndAspectJIsNotAvailableThenClassProxyingIsStillUsedByDefault() { this.contextRunner.withClassLoader(new FilteredClassLoader(Advice.class)) - .withUserConfiguration(ExampleController.class, EnableGlobalMethodSecurityConfiguration.class) - .run((context) -> { - ExampleController exampleController = context.getBean(ExampleController.class); - assertThat(AopUtils.isCglibProxy(exampleController)).isTrue(); - }); + .withUserConfiguration(ExampleController.class, EnableGlobalMethodSecurityConfiguration.class) + .run((context) -> { + ExampleController exampleController = context.getBean(ExampleController.class); + assertThat(AopUtils.isCglibProxy(exampleController)).isTrue(); + }); } private ContextConsumer proxyTargetClassEnabled() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java index 9c4c46ce10..76b3242a42 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/aop/NonAspectJAopAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,13 +35,13 @@ import static org.assertj.core.api.Assertions.assertThat; class NonAspectJAopAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AopAutoConfiguration.class)); @Test void whenAspectJIsAbsentAndProxyTargetClassIsEnabledProxyCreatorBeanIsDefined() { this.contextRunner.run((context) -> { BeanDefinition autoProxyCreator = context.getBeanFactory() - .getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); + .getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME); assertThat(autoProxyCreator.getPropertyValues().get("proxyTargetClass")).isEqualTo(Boolean.TRUE); }); } @@ -49,7 +49,7 @@ class NonAspectJAopAutoConfigurationTests { @Test void whenAspectJIsAbsentAndProxyTargetClassIsDisabledNoProxyCreatorBeanIsDefined() { this.contextRunner.withPropertyValues("spring.aop.proxy-target-class:false") - .run((context) -> assertThat(context).doesNotHaveBean(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME)); + .run((context) -> assertThat(context).doesNotHaveBean(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java index 63df9dbc52..60e8c7d5dc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java @@ -94,302 +94,310 @@ import static org.mockito.Mockito.mock; class BatchAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)); @Test void testDefaultContext() { this.contextRunner.withInitializer(ConditionEvaluationReportLoggingListener.forLogLevel(LogLevel.INFO)) - .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context).hasSingleBean(JobExplorer.class); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); - }); + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context).hasSingleBean(JobExplorer.class); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); + }); } @Test void autoconfigurationBacksOffEntirelyIfSpringJdbcAbsent() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)).run((context) -> { - assertThat(context).doesNotHaveBean(JobLauncherApplicationRunner.class); - assertThat(context).doesNotHaveBean(BatchDataSourceScriptDatabaseInitializer.class); - }); + .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(JobLauncherApplicationRunner.class); + assertThat(context).doesNotHaveBean(BatchDataSourceScriptDatabaseInitializer.class); + }); } @Test void autoConfigurationBacksOffWhenUserEnablesBatchProcessing() { this.contextRunner - .withUserConfiguration(EnableBatchProcessingConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)) - .run((context) -> assertThat(context).doesNotHaveBean(SpringBootBatchConfiguration.class)); + .withUserConfiguration(EnableBatchProcessingConfiguration.class, EmbeddedDataSourceConfiguration.class) + .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)) + .run((context) -> assertThat(context).doesNotHaveBean(SpringBootBatchConfiguration.class)); } @Test void autoConfigurationBacksOffWhenUserProvidesBatchConfiguration() { this.contextRunner.withUserConfiguration(CustomBatchConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)) - .run((context) -> assertThat(context).doesNotHaveBean(SpringBootBatchConfiguration.class)); + .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)) + .run((context) -> assertThat(context).doesNotHaveBean(SpringBootBatchConfiguration.class)); } @Test void testDefinesAndLaunchesJob() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class) - .run(new DefaultApplicationArguments("jobParam=test")); - JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") - .toJobParameters(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)) - .isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class) + .run(new DefaultApplicationArguments("jobParam=test")); + JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") + .toJobParameters(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)).isNotNull(); + }); } @Test void testDefinesAndLaunchesJobIgnoreOptionArguments() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class) - .run(new DefaultApplicationArguments("--spring.property=value", "jobParam=test")); - JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") - .toJobParameters(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)) - .isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class) + .run(new DefaultApplicationArguments("--spring.property=value", "jobParam=test")); + JobParameters jobParameters = new JobParametersBuilder().addString("jobParam", "test") + .toJobParameters(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", jobParameters)).isNotNull(); + }); } @Test void testDefinesAndLaunchesNamedRegisteredJob() { this.contextRunner - .withUserConfiguration(NamedJobConfigurationWithRegisteredJob.class, - EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.name:discreteRegisteredJob").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class).run(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("discreteRegisteredJob", - new JobParameters())).isNotNull(); - }); + .withUserConfiguration(NamedJobConfigurationWithRegisteredJob.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.batch.job.name:discreteRegisteredJob") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class).run(); + assertThat(context.getBean(JobRepository.class) + .getLastJobExecution("discreteRegisteredJob", new JobParameters())).isNotNull(); + }); } @Test void testRegisteredAndLocalJob() { this.contextRunner - .withUserConfiguration(NamedJobConfigurationWithRegisteredAndLocalJob.class, - EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.name:discreteRegisteredJob").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class).run(); - assertThat(context.getBean(JobRepository.class) - .getLastJobExecution("discreteRegisteredJob", new JobParameters()).getStatus()) - .isEqualTo(BatchStatus.COMPLETED); - }); + .withUserConfiguration(NamedJobConfigurationWithRegisteredAndLocalJob.class, + EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.batch.job.name:discreteRegisteredJob") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class).run(); + assertThat(context.getBean(JobRepository.class) + .getLastJobExecution("discreteRegisteredJob", new JobParameters()) + .getStatus()).isEqualTo(BatchStatus.COMPLETED); + }); } @Test void testDefinesAndLaunchesLocalJob() { this.contextRunner - .withUserConfiguration(NamedJobConfigurationWithLocalJob.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.name:discreteLocalJob").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class).run(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("discreteLocalJob", - new JobParameters())).isNotNull(); - }); + .withUserConfiguration(NamedJobConfigurationWithLocalJob.class, EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.batch.job.name:discreteLocalJob") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class).run(); + assertThat(context.getBean(JobRepository.class) + .getLastJobExecution("discreteLocalJob", new JobParameters())).isNotNull(); + }); } @Test void testMultipleJobsAndNoJobName() { this.contextRunner.withUserConfiguration(MultipleJobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getCause().getMessage()) - .contains("Job name must be specified in case of multiple jobs"); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure().getCause().getMessage()) + .contains("Job name must be specified in case of multiple jobs"); + }); } @Test void testMultipleJobsAndJobName() { this.contextRunner.withUserConfiguration(MultipleJobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.name:discreteLocalJob").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - context.getBean(JobLauncherApplicationRunner.class).run(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("discreteLocalJob", - new JobParameters())).isNotNull(); - }); + .withPropertyValues("spring.batch.job.name:discreteLocalJob") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + context.getBean(JobLauncherApplicationRunner.class).run(); + assertThat(context.getBean(JobRepository.class) + .getLastJobExecution("discreteLocalJob", new JobParameters())).isNotNull(); + }); } @Test void testDisableLaunchesJob() { this.contextRunner.withUserConfiguration(JobConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.batch.job.enabled:false").run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context).doesNotHaveBean(CommandLineRunner.class); - }); + .withPropertyValues("spring.batch.job.enabled:false") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context).doesNotHaveBean(CommandLineRunner.class); + }); } @Test void testDisableSchemaLoader() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.initialize-schema:never") - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.NEVER); - assertThat(context).doesNotHaveBean(BatchDataSourceScriptDatabaseInitializer.class); - assertThatExceptionOfType(BadSqlGrammarException.class) - .isThrownBy(() -> new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION")); - }); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.initialize-schema:never") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.NEVER); + assertThat(context).doesNotHaveBean(BatchDataSourceScriptDatabaseInitializer.class); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")); + }); } @Test void testUsingJpa() { - this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class).run((context) -> { - PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); - // It's a lazy proxy, but it does render its target if you ask for - // toString(): - assertThat(transactionManager.toString()).contains("JpaTransactionManager"); - assertThat(context).hasSingleBean(EntityManagerFactory.class); - // Ensure the JobRepository can be used (no problem with isolation - // level) - assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())) - .isNull(); - }); + this.contextRunner + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .run((context) -> { + PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); + // It's a lazy proxy, but it does render its target if you ask for + // toString(): + assertThat(transactionManager.toString()).contains("JpaTransactionManager"); + assertThat(context).hasSingleBean(EntityManagerFactory.class); + // Ensure the JobRepository can be used (no problem with isolation + // level) + assertThat(context.getBean(JobRepository.class).getLastJobExecution("job", new JobParameters())) + .isNull(); + }); } @Test void testRenamePrefix() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", - "spring.batch.jdbc.tablePrefix:PREFIX_") - .run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); - JobExplorer jobExplorer = context.getBean(JobExplorer.class); - assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); - JobRepository jobRepository = context.getBean(JobRepository.class); - assertThat(jobRepository.getLastJobExecution("test", new JobParameters())).isNull(); - }); + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", + "spring.batch.jdbc.tablePrefix:PREFIX_") + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); + JobExplorer jobExplorer = context.getBean(JobExplorer.class); + assertThat(jobExplorer.findRunningJobExecutions("test")).isEmpty(); + JobRepository jobRepository = context.getBean(JobRepository.class); + assertThat(jobRepository.getLastJobExecution("test", new JobParameters())).isNull(); + }); } @Test void testCustomizeJpaTransactionManagerUsingProperties() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, - HibernateJpaAutoConfiguration.class) - .withPropertyValues("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") - .run((context) -> { - assertThat(context).hasSingleBean(BatchAutoConfiguration.class); - JpaTransactionManager transactionManager = JpaTransactionManager.class - .cast(context.getBean(SpringBootBatchConfiguration.class).getTransactionManager()); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + .withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class, + HibernateJpaAutoConfiguration.class) + .withPropertyValues("spring.transaction.default-timeout:30", + "spring.transaction.rollback-on-commit-failure:true") + .run((context) -> { + assertThat(context).hasSingleBean(BatchAutoConfiguration.class); + JpaTransactionManager transactionManager = JpaTransactionManager.class + .cast(context.getBean(SpringBootBatchConfiguration.class).getTransactionManager()); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void testCustomizeDataSourceTransactionManagerUsingProperties() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true") - .run((context) -> { - assertThat(context).hasSingleBean(SpringBootBatchConfiguration.class); - DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class - .cast(context.getBean(SpringBootBatchConfiguration.class).getTransactionManager()); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + .withPropertyValues("spring.transaction.default-timeout:30", + "spring.transaction.rollback-on-commit-failure:true") + .run((context) -> { + assertThat(context).hasSingleBean(SpringBootBatchConfiguration.class); + DataSourceTransactionManager transactionManager = DataSourceTransactionManager.class + .cast(context.getBean(SpringBootBatchConfiguration.class).getTransactionManager()); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void testBatchDataSource() { this.contextRunner.withUserConfiguration(TestConfiguration.class, BatchDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(SpringBootBatchConfiguration.class) - .hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class).hasBean("batchDataSource"); - DataSource batchDataSource = context.getBean("batchDataSource", DataSource.class); - assertThat(context.getBean(SpringBootBatchConfiguration.class).getDataSource()) - .isEqualTo(batchDataSource); - assertThat(context.getBean(BatchDataSourceScriptDatabaseInitializer.class)) - .hasFieldOrPropertyWithValue("dataSource", batchDataSource); - }); + .run((context) -> { + assertThat(context).hasSingleBean(SpringBootBatchConfiguration.class) + .hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) + .hasBean("batchDataSource"); + DataSource batchDataSource = context.getBean("batchDataSource", DataSource.class); + assertThat(context.getBean(SpringBootBatchConfiguration.class).getDataSource()) + .isEqualTo(batchDataSource); + assertThat(context.getBean(BatchDataSourceScriptDatabaseInitializer.class)) + .hasFieldOrPropertyWithValue("dataSource", batchDataSource); + }); } @Test void jobRepositoryBeansDependOnBatchDataSourceInitializer() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); - assertThat(jobRepositoryNames).isNotEmpty(); - for (String jobRepositoryName : jobRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()) - .contains("batchDataSourceInitializer"); - } - }); + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); + assertThat(jobRepositoryNames).isNotEmpty(); + for (String jobRepositoryName : jobRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()) + .contains("batchDataSourceInitializer"); + } + }); } @Test void jobRepositoryBeansDependOnFlyway() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withUserConfiguration(FlywayAutoConfiguration.class) - .withPropertyValues("spring.batch.initialize-schema=never").run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); - assertThat(jobRepositoryNames).isNotEmpty(); - for (String jobRepositoryName : jobRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()).contains("flyway", - "flywayInitializer"); - } - }); + .withUserConfiguration(FlywayAutoConfiguration.class) + .withPropertyValues("spring.batch.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); + assertThat(jobRepositoryNames).isNotEmpty(); + for (String jobRepositoryName : jobRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()).contains("flyway", + "flywayInitializer"); + } + }); } @Test void jobRepositoryBeansDependOnLiquibase() { this.contextRunner.withUserConfiguration(TestConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withUserConfiguration(LiquibaseAutoConfiguration.class) - .withPropertyValues("spring.batch.initialize-schema=never").run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); - assertThat(jobRepositoryNames).isNotEmpty(); - for (String jobRepositoryName : jobRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()) - .contains("liquibase"); - } - }); + .withUserConfiguration(LiquibaseAutoConfiguration.class) + .withPropertyValues("spring.batch.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] jobRepositoryNames = beanFactory.getBeanNamesForType(JobRepository.class); + assertThat(jobRepositoryNames).isNotEmpty(); + for (String jobRepositoryName : jobRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(jobRepositoryName).getDependsOn()).contains("liquibase"); + } + }); } @Test void whenTheUserDefinesTheirOwnBatchDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner - .withUserConfiguration(TestConfiguration.class, CustomBatchDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("batchDataSourceScriptDatabaseInitializer").hasBean("customInitializer")); + .withUserConfiguration(TestConfiguration.class, CustomBatchDatabaseInitializerConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("batchDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredBatchInitializerRemains() { this.contextRunner.withUserConfiguration(TestConfiguration.class, CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(BatchDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java index dd133a1774..85b1f8543e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationWithoutJpaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,50 +50,51 @@ import static org.assertj.core.api.Assertions.assertThat; class BatchAutoConfigurationWithoutJpaTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)); @Test void jdbcWithDefaultSettings() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true") - .withInitializer(ConditionEvaluationReportLoggingListener.forLogLevel(LogLevel.INFO)).run((context) -> { - assertThat(context).hasSingleBean(JobLauncher.class); - assertThat(context).hasSingleBean(JobExplorer.class); - assertThat(context).hasSingleBean(JobRepository.class); - assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); - assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) - .isNull(); - }); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .withInitializer(ConditionEvaluationReportLoggingListener.forLogLevel(LogLevel.INFO)) + .run((context) -> { + assertThat(context).hasSingleBean(JobLauncher.class); + assertThat(context).hasSingleBean(JobExplorer.class); + assertThat(context).hasSingleBean(JobRepository.class); + assertThat(context.getBean(BatchProperties.class).getJdbc().getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")).isEmpty(); + assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) + .isNull(); + }); } @Test void jdbcWithCustomPrefix() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", - "spring.batch.jdbc.tablePrefix:PREFIX_") - .run((context) -> { - assertThat(new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); - assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); - assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) - .isNull(); - }); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.schema:classpath:batch/custom-schema.sql", + "spring.batch.jdbc.tablePrefix:PREFIX_") + .run((context) -> { + assertThat(new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from PREFIX_JOB_EXECUTION")).isEmpty(); + assertThat(context.getBean(JobExplorer.class).findRunningJobExecutions("test")).isEmpty(); + assertThat(context.getBean(JobRepository.class).getLastJobExecution("test", new JobParameters())) + .isNull(); + }); } @Test void jdbcWithCustomIsolationLevel() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class, EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.batch.jdbc.isolation-level-for-create=read_committed") - .run((context) -> assertThat( - context.getBean(SpringBootBatchConfiguration.class).getIsolationLevelForCreate()) - .isEqualTo(Isolation.READ_COMMITTED)); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.batch.jdbc.isolation-level-for-create=read_committed") + .run((context) -> assertThat( + context.getBean(SpringBootBatchConfiguration.class).getIsolationLevelForCreate()) + .isEqualTo(Isolation.READ_COMMITTED)); } @TestAutoConfigurationPackage(City.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java index ed47fe4e29..6b04e877c6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ class BatchDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = BatchDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties.getJdbc()); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/springframework/batch/core/schema-test.sql"); + .containsOnly("classpath:org/springframework/batch/core/schema-test.sql"); then(dataSource).shouldHaveNoInteractions(); } @@ -77,16 +77,17 @@ class BatchDataSourceScriptDatabaseInitializerTests { properties.getJdbc()); List schemaLocations = settings.getSchemaLocations(); assertThat(schemaLocations) - .allSatisfy((location) -> assertThat(resourceLoader.getResource(location).exists()).isTrue()); + .allSatisfy((location) -> assertThat(resourceLoader.getResource(location).exists()).isTrue()); } @Test void batchHasExpectedBuiltInSchemas() throws IOException { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); List schemaNames = Stream - .of(resolver.getResources("classpath:org/springframework/batch/core/schema-*.sql")) - .map((resource) -> resource.getFilename()).filter((resourceName) -> !resourceName.contains("-drop-")) - .toList(); + .of(resolver.getResources("classpath:org/springframework/batch/core/schema-*.sql")) + .map((resource) -> resource.getFilename()) + .filter((resourceName) -> !resourceName.contains("-drop-")) + .toList(); assertThat(schemaNames).containsExactlyInAnyOrder("schema-derby.sql", "schema-sqlserver.sql", "schema-mariadb.sql", "schema-mysql.sql", "schema-sqlite.sql", "schema-postgresql.sql", "schema-hana.sql", "schema-oracle.sql", "schema-db2.sql", "schema-hsqldb.sql", "schema-sybase.sql", diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java index 0c42538d69..b5149782e6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,9 +66,9 @@ import static org.assertj.core.api.Assertions.fail; class JobLauncherApplicationRunnerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(BatchConfiguration.class); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(BatchConfiguration.class); @Test void basicExecution() { @@ -98,8 +98,9 @@ class JobLauncherApplicationRunnerTests { PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); Job job = jobLauncherContext.jobBuilder() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) - .incrementer(new RunIdIncrementer()).build(); + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) + .incrementer(new RunIdIncrementer()) + .build(); jobLauncherContext.runner.execute(job, new JobParameters()); jobLauncherContext.runner.execute(job, new JobParametersBuilder().addLong("run.id", 1L).toJobParameters()); assertThat(jobLauncherContext.jobInstances()).hasSize(1); @@ -112,8 +113,8 @@ class JobLauncherApplicationRunnerTests { PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); Job job = jobLauncherContext.jobBuilder() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) - .build(); + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) + .build(); // start a job instance JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo").toJobParameters(); jobLauncherContext.runner.execute(job, jobParameters); @@ -130,9 +131,11 @@ class JobLauncherApplicationRunnerTests { this.contextRunner.run((context) -> { PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); - Job job = jobLauncherContext.jobBuilder().preventRestart() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) - .incrementer(new RunIdIncrementer()).build(); + Job job = jobLauncherContext.jobBuilder() + .preventRestart() + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) + .incrementer(new RunIdIncrementer()) + .build(); jobLauncherContext.runner.execute(job, new JobParameters()); jobLauncherContext.runner.execute(job, new JobParameters()); // A failed job that is not restartable does not re-use the job params of @@ -153,10 +156,12 @@ class JobLauncherApplicationRunnerTests { PlatformTransactionManager transactionManager = context.getBean(PlatformTransactionManager.class); JobLauncherApplicationRunnerContext jobLauncherContext = new JobLauncherApplicationRunnerContext(context); Job job = jobLauncherContext.jobBuilder() - .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) - .incrementer(new RunIdIncrementer()).build(); - JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false) - .toJobParameters(); + .start(jobLauncherContext.stepBuilder().tasklet(throwingTasklet(), transactionManager).build()) + .incrementer(new RunIdIncrementer()) + .build(); + JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false) + .addLong("foo", 2L, false) + .toJobParameters(); jobLauncherContext.runner.execute(job, jobParameters); assertThat(jobLauncherContext.jobInstances()).hasSize(1); // try to re-run a failed execution with non identifying parameters diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java index 68b041c293..7567f91287 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/AbstractCacheAutoConfigurationTests.java @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; abstract class AbstractCacheAutoConfigurationTests { protected final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); protected T getCacheManager(AssertableApplicationContext loaded, Class type) { CacheManager cacheManager = loaded.getBean(CacheManager.class); @@ -62,7 +62,7 @@ abstract class AbstractCacheAutoConfigurationTests { CacheManager cacheManager = getCacheManager(context, CacheManager.class); List expected = new ArrayList<>(Arrays.asList(expectedCustomizerNames)); Map customizer = context - .getBeansOfType(CacheManagerTestCustomizer.class); + .getBeansOfType(CacheManagerTestCustomizer.class); customizer.forEach((key, value) -> { if (expected.contains(key)) { expected.remove(key); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index ca65231a0a..d5e780b67e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -94,70 +94,74 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void noEnableCaching() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test void cacheManagerBackOff() { this.contextRunner.withUserConfiguration(CustomCacheManagerConfiguration.class) - .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) - .containsOnly("custom1")); + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .containsOnly("custom1")); } @Test void cacheManagerFromSupportBackOff() { this.contextRunner.withUserConfiguration(CustomCacheManagerFromSupportConfiguration.class) - .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) - .containsOnly("custom1")); + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .containsOnly("custom1")); } @Test void cacheResolverFromSupportBackOff() { this.contextRunner.withUserConfiguration(CustomCacheResolverFromSupportConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CacheManager.class)); } @Test void customCacheResolverCanBeDefined() { this.contextRunner.withUserConfiguration(SpecificCacheResolverConfiguration.class) - .withPropertyValues("spring.cache.type=simple").run((context) -> { - getCacheManager(context, ConcurrentMapCacheManager.class); - assertThat(context).hasSingleBean(CacheResolver.class); - }); + .withPropertyValues("spring.cache.type=simple") + .run((context) -> { + getCacheManager(context, ConcurrentMapCacheManager.class); + assertThat(context).hasSingleBean(CacheResolver.class); + }); } @Test void notSupportedCachingMode() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=foobar") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class).rootCause() - .hasMessageContaining("No enum constant").hasMessageContaining("foobar")); + .withPropertyValues("spring.cache.type=foobar") + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .rootCause() + .hasMessageContaining("No enum constant") + .hasMessageContaining("foobar")); } @Test void simpleCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=simple") - .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) - .isEmpty()); + .withPropertyValues("spring.cache.type=simple") + .run((context) -> assertThat(getCacheManager(context, ConcurrentMapCacheManager.class).getCacheNames()) + .isEmpty()); } @Test void simpleCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=simple") - .run(verifyCustomizers("allCacheManagerCustomizer", "simpleCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=simple") + .run(verifyCustomizers("allCacheManagerCustomizer", "simpleCacheManagerCustomizer")); } @Test void simpleCacheExplicitWithCacheNames() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - ConcurrentMapCacheManager cacheManager = getCacheManager(context, ConcurrentMapCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=simple", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + ConcurrentMapCacheManager cacheManager = getCacheManager(context, ConcurrentMapCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } @Test @@ -173,228 +177,236 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void genericCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=generic") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("No cache manager could be auto-configured") - .hasMessageContaining("GENERIC")); + .withPropertyValues("spring.cache.type=generic") + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("No cache manager could be auto-configured") + .hasMessageContaining("GENERIC")); } @Test void genericCacheWithCustomizers() { this.contextRunner.withUserConfiguration(GenericCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=generic") - .run(verifyCustomizers("allCacheManagerCustomizer", "genericCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=generic") + .run(verifyCustomizers("allCacheManagerCustomizer", "genericCacheManagerCustomizer")); } @Test void genericCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(GenericCacheConfiguration.class) - .withPropertyValues("spring.cache.type=generic").run((context) -> { - SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); - assertThat(cacheManager.getCache("first")).isEqualTo(context.getBean("firstCache")); - assertThat(cacheManager.getCache("second")).isEqualTo(context.getBean("secondCache")); - assertThat(cacheManager.getCacheNames()).hasSize(2); - }); + .withPropertyValues("spring.cache.type=generic") + .run((context) -> { + SimpleCacheManager cacheManager = getCacheManager(context, SimpleCacheManager.class); + assertThat(cacheManager.getCache("first")).isEqualTo(context.getBean("firstCache")); + assertThat(cacheManager.getCache("second")).isEqualTo(context.getBean("secondCache")); + assertThat(cacheManager.getCacheNames()).hasSize(2); + }); } @Test void couchbaseCacheExplicit() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase").run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - }); + .withPropertyValues("spring.cache.type=couchbase") + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + }); } @Test void couchbaseCacheWithCustomizers() { this.contextRunner.withUserConfiguration(CouchbaseWithCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase") - .run(verifyCustomizers("allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=couchbase") + .run(verifyCustomizers("allCacheManagerCustomizer", "couchbaseCacheManagerCustomizer")); } @Test void couchbaseCacheExplicitWithCaches() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - Cache cache = cacheManager.getCache("foo"); - assertThat(cache).isInstanceOf(CouchbaseCache.class); - assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(0); - }); + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + Cache cache = cacheManager.getCache("foo"); + assertThat(cache).isInstanceOf(CouchbaseCache.class); + assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(0); + }); } @Test void couchbaseCacheExplicitWithTtl() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", - "spring.cache.couchbase.expiration=2000") - .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - Cache cache = cacheManager.getCache("foo"); - assertThat(cache).isInstanceOf(CouchbaseCache.class); - assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(2); - }); + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.cacheNames=foo,bar", + "spring.cache.couchbase.expiration=2000") + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + Cache cache = cacheManager.getCache("foo"); + assertThat(cache).isInstanceOf(CouchbaseCache.class); + assertThat(((CouchbaseCache) cache).getCacheConfiguration().getExpiry()).hasSeconds(2); + }); } @Test void couchbaseCacheWithCouchbaseCacheManagerBuilderCustomizer() { this.contextRunner.withUserConfiguration(CouchbaseConfiguration.class) - .withPropertyValues("spring.cache.type=couchbase", "spring.cache.couchbase.expiration=15s") - .withBean(CouchbaseCacheManagerBuilderCustomizer.class, () -> (builder) -> builder.cacheDefaults( - CouchbaseCacheConfiguration.defaultCacheConfig().entryExpiry(java.time.Duration.ofSeconds(10)))) - .run((context) -> { - CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); - CouchbaseCacheConfiguration couchbaseCacheConfiguration = getDefaultCouchbaseCacheConfiguration( - cacheManager); - assertThat(couchbaseCacheConfiguration.getExpiry()).isEqualTo(java.time.Duration.ofSeconds(10)); - }); + .withPropertyValues("spring.cache.type=couchbase", "spring.cache.couchbase.expiration=15s") + .withBean(CouchbaseCacheManagerBuilderCustomizer.class, + () -> (builder) -> builder.cacheDefaults(CouchbaseCacheConfiguration.defaultCacheConfig() + .entryExpiry(java.time.Duration.ofSeconds(10)))) + .run((context) -> { + CouchbaseCacheManager cacheManager = getCacheManager(context, CouchbaseCacheManager.class); + CouchbaseCacheConfiguration couchbaseCacheConfiguration = getDefaultCouchbaseCacheConfiguration( + cacheManager); + assertThat(couchbaseCacheConfiguration.getExpiry()).isEqualTo(java.time.Duration.ofSeconds(10)); + }); } @Test void redisCacheExplicit() { this.contextRunner.withUserConfiguration(RedisConfiguration.class) - .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", - "spring.cache.redis.cacheNullValues=false", "spring.cache.redis.keyPrefix=prefix", - "spring.cache.redis.useKeyPrefix=true") - .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(15)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isFalse(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("MyCache")).isEqualTo("prefixMyCache::"); - assertThat(redisCacheConfiguration.usePrefix()).isTrue(); - }); + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", + "spring.cache.redis.cacheNullValues=false", "spring.cache.redis.keyPrefix=prefix", + "spring.cache.redis.useKeyPrefix=true") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(15)); + assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isFalse(); + assertThat(redisCacheConfiguration.getKeyPrefixFor("MyCache")).isEqualTo("prefixMyCache::"); + assertThat(redisCacheConfiguration.usePrefix()).isTrue(); + }); } @Test void redisCacheWithRedisCacheConfiguration() { this.contextRunner.withUserConfiguration(RedisWithCacheConfigurationConfiguration.class) - .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", - "spring.cache.redis.keyPrefix=foo") - .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(30)); - assertThat(redisCacheConfiguration.getKeyPrefixFor("")).isEqualTo("bar::"); - }); + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000", + "spring.cache.redis.keyPrefix=foo") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(30)); + assertThat(redisCacheConfiguration.getKeyPrefixFor("")).isEqualTo("bar::"); + }); } @Test void redisCacheWithRedisCacheManagerBuilderCustomizer() { this.contextRunner.withUserConfiguration(RedisWithRedisCacheManagerBuilderCustomizerConfiguration.class) - .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000") - .run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(10)); - }); + .withPropertyValues("spring.cache.type=redis", "spring.cache.redis.time-to-live=15000") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofSeconds(10)); + }); } @Test void redisCacheWithCustomizers() { this.contextRunner.withUserConfiguration(RedisWithCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=redis") - .run(verifyCustomizers("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=redis") + .run(verifyCustomizers("allCacheManagerCustomizer", "redisCacheManagerCustomizer")); } @Test void redisCacheExplicitWithCaches() { - this.contextRunner.withUserConfiguration(RedisConfiguration.class).withPropertyValues("spring.cache.type=redis", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar").run((context) -> { - RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); - assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofMinutes(0)); - assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isTrue(); - assertThat(redisCacheConfiguration.getKeyPrefixFor("test")).isEqualTo("test::"); - assertThat(redisCacheConfiguration.usePrefix()).isTrue(); - }); + this.contextRunner.withUserConfiguration(RedisConfiguration.class) + .withPropertyValues("spring.cache.type=redis", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + RedisCacheManager cacheManager = getCacheManager(context, RedisCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + RedisCacheConfiguration redisCacheConfiguration = getDefaultRedisCacheConfiguration(cacheManager); + assertThat(redisCacheConfiguration.getTtl()).isEqualTo(java.time.Duration.ofMinutes(0)); + assertThat(redisCacheConfiguration.getAllowCacheNullValues()).isTrue(); + assertThat(redisCacheConfiguration.getKeyPrefixFor("test")).isEqualTo("test::"); + assertThat(redisCacheConfiguration.usePrefix()).isTrue(); + }); } @Test void noOpCacheExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=none").run((context) -> { - NoOpCacheManager cacheManager = getCacheManager(context, NoOpCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - }); + .withPropertyValues("spring.cache.type=none") + .run((context) -> { + NoOpCacheManager cacheManager = getCacheManager(context, NoOpCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + }); } @Test void jCacheCacheNoProviderExplicit() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("No cache manager could be auto-configured") - .hasMessageContaining("JCACHE")); + .withPropertyValues("spring.cache.type=jcache") + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("No cache manager could be auto-configured") + .hasMessageContaining("JCACHE")); } @Test void jCacheCacheWithProvider() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).isEmpty(); - assertThat(context.getBean(javax.cache.CacheManager.class)) - .isEqualTo(cacheManager.getCacheManager()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).isEmpty(); + assertThat(context.getBean(javax.cache.CacheManager.class)).isEqualTo(cacheManager.getCacheManager()); + }); } @Test void jCacheCacheWithCaches() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } @Test void jCacheCacheWithCachesAndCustomConfig() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); - CompleteConfiguration defaultCacheConfiguration = context - .getBean(CompleteConfiguration.class); - MockCacheManager mockCacheManager = (MockCacheManager) cacheManager.getCacheManager(); - assertThat(mockCacheManager.getConfigurations()).containsEntry("one", defaultCacheConfiguration) - .containsEntry("two", defaultCacheConfiguration); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=one", "spring.cache.cacheNames[1]=two") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("one", "two"); + CompleteConfiguration defaultCacheConfiguration = context.getBean(CompleteConfiguration.class); + MockCacheManager mockCacheManager = (MockCacheManager) cacheManager.getCacheManager(); + assertThat(mockCacheManager.getConfigurations()).containsEntry("one", defaultCacheConfiguration) + .containsEntry("two", defaultCacheConfiguration); + }); } @Test void jCacheCacheWithExistingJCacheManager() { this.contextRunner.withUserConfiguration(JCacheCustomCacheManager.class) - .withPropertyValues("spring.cache.type=jcache").run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customJCacheCacheManager")); - }); + .withPropertyValues("spring.cache.type=jcache") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheManager()).isEqualTo(context.getBean("customJCacheCacheManager")); + }); } @Test void jCacheCacheWithUnknownProvider() { String wrongCachingProviderClassName = "org.acme.FooBar"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + wrongCachingProviderClassName) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining(wrongCachingProviderClassName)); + .withPropertyValues("spring.cache.type=jcache", + "spring.cache.jcache.provider=" + wrongCachingProviderClassName) + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining(wrongCachingProviderClassName)); } @Test @@ -402,13 +414,13 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + Resource configResource = new ClassPathResource(configLocation); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); + }); } @Test @@ -416,69 +428,72 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = MockCachingProvider.class.getName(); String configLocation = "org/springframework/boot/autoconfigure/cache/does-not-exist.xml"; this.contextRunner.withUserConfiguration(JCacheCustomConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("does not exist").hasMessageContaining(configLocation)); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("does not exist") + .hasMessageContaining(configLocation)); } @Test void jCacheCacheUseBeanClassLoader() { String cachingProviderFqn = MockCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheManager().getClassLoader()).isEqualTo(context.getClassLoader()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheManager().getClassLoader()).isEqualTo(context.getClassLoader()); + }); } @Test void hazelcastCacheExplicit() { this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); - // NOTE: the hazelcast implementation knows about a cache in a lazy - // manner. - cacheManager.getCache("defaultCache"); - assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); - assertThat(context.getBean(HazelcastInstance.class)).isEqualTo(cacheManager.getHazelcastInstance()); - }); + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=hazelcast") + .run((context) -> { + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); + // NOTE: the hazelcast implementation knows about a cache in a lazy + // manner. + cacheManager.getCache("defaultCache"); + assertThat(cacheManager.getCacheNames()).containsOnly("defaultCache"); + assertThat(context.getBean(HazelcastInstance.class)).isEqualTo(cacheManager.getHazelcastInstance()); + }); } @Test void hazelcastCacheWithCustomizers() { this.contextRunner.withUserConfiguration(HazelcastCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=hazelcast") - .run(verifyCustomizers("allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=hazelcast") + .run(verifyCustomizers("allCacheManagerCustomizer", "hazelcastCacheManagerCustomizer")); } @Test void hazelcastCacheWithExistingHazelcastInstance() { this.contextRunner.withUserConfiguration(HazelcastCustomHazelcastInstance.class) - .withPropertyValues("spring.cache.type=hazelcast").run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); - assertThat(cacheManager.getHazelcastInstance()) - .isEqualTo(context.getBean("customHazelcastInstance")); - }); + .withPropertyValues("spring.cache.type=hazelcast") + .run((context) -> { + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); + assertThat(cacheManager.getHazelcastInstance()).isEqualTo(context.getBean("customHazelcastInstance")); + }); } @Test void hazelcastCacheWithHazelcastAutoConfiguration() { String hazelcastConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=hazelcast", "spring.hazelcast.config=" + hazelcastConfig) - .run((context) -> { - HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); - HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); - assertThat(cacheManager.getHazelcastInstance()).isSameAs(hazelcastInstance); - assertThat(hazelcastInstance.getConfig().getConfigurationFile()) - .isEqualTo(new ClassPathResource(hazelcastConfig).getFile()); - assertThat(cacheManager.getCache("foobar")).isNotNull(); - assertThat(cacheManager.getCacheNames()).containsOnly("foobar"); - }); + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=hazelcast", "spring.hazelcast.config=" + hazelcastConfig) + .run((context) -> { + HazelcastCacheManager cacheManager = getCacheManager(context, HazelcastCacheManager.class); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); + assertThat(cacheManager.getHazelcastInstance()).isSameAs(hazelcastInstance); + assertThat(hazelcastInstance.getConfig().getConfigurationFile()) + .isEqualTo(new ClassPathResource(hazelcastConfig).getFile()); + assertThat(cacheManager.getCache("foobar")).isNotNull(); + assertThat(cacheManager.getCacheNames()).containsOnly("foobar"); + }); } @Test @@ -486,14 +501,13 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = HazelcastServerCachingProvider.class.getName(); try { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); + }); } finally { Caching.getCachingProvider(cachingProviderFqn).close(); @@ -506,15 +520,14 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { try { String configLocation = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); - assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + Resource configResource = new ClassPathResource(configLocation); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); + assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); + }); } finally { Caching.getCachingProvider(cachingProviderFqn).close(); @@ -525,69 +538,67 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { void hazelcastAsJCacheWithExistingHazelcastInstance() { String cachingProviderFqn = HazelcastServerCachingProvider.class.getName(); this.contextRunner.withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)) - .withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - javax.cache.CacheManager jCacheManager = cacheManager.getCacheManager(); - assertThat(jCacheManager).isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); - assertThat(context).hasSingleBean(HazelcastInstance.class); - HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); - assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager).getHazelcastInstance()) - .isSameAs(hazelcastInstance); - assertThat(hazelcastInstance.getName()).isEqualTo("default-instance"); - assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); - }); + .withUserConfiguration(DefaultCacheConfiguration.class) + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + javax.cache.CacheManager jCacheManager = cacheManager.getCacheManager(); + assertThat(jCacheManager).isInstanceOf(com.hazelcast.cache.HazelcastCacheManager.class); + assertThat(context).hasSingleBean(HazelcastInstance.class); + HazelcastInstance hazelcastInstance = context.getBean(HazelcastInstance.class); + assertThat(((com.hazelcast.cache.HazelcastCacheManager) jCacheManager).getHazelcastInstance()) + .isSameAs(hazelcastInstance); + assertThat(hazelcastInstance.getName()).isEqualTo("default-instance"); + assertThat(Hazelcast.getAllHazelcastInstances()).hasSize(1); + }); } @Test void infinispanCacheWithConfig() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml") - .run((context) -> { - SpringEmbeddedCacheManager cacheManager = getCacheManager(context, - SpringEmbeddedCacheManager.class); - assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.infinispan.config=infinispan.xml") + .run((context) -> { + SpringEmbeddedCacheManager cacheManager = getCacheManager(context, SpringEmbeddedCacheManager.class); + assertThat(cacheManager.getCacheNames()).contains("foo", "bar"); + }); } @Test void infinispanCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan") - .run(verifyCustomizers("allCacheManagerCustomizer", "infinispanCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=infinispan") + .run(verifyCustomizers("allCacheManagerCustomizer", "infinispanCacheManagerCustomizer")); } @Test void infinispanCacheWithCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) - .containsOnly("foo", "bar")); + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar")); } @Test void infinispanCacheWithCachesAndCustomConfig() { this.contextRunner.withUserConfiguration(InfinispanCustomConfiguration.class) - .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> { - assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) - .containsOnly("foo", "bar"); - then(context.getBean(ConfigurationBuilder.class)).should(times(2)).build(); - }); + .withPropertyValues("spring.cache.type=infinispan", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run((context) -> { + assertThat(getCacheManager(context, SpringEmbeddedCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar"); + then(context.getBean(ConfigurationBuilder.class)).should(times(2)).build(); + }); } @Test void infinispanAsJCacheWithCaches() { String cachingProviderClassName = JCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderClassName, "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()) - .containsOnly("foo", "bar")); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderClassName, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()) + .containsOnly("foo", "bar")); } @Test @@ -595,14 +606,13 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderClassName = JCachingProvider.class.getName(); String configLocation = "infinispan.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderClassName, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - Resource configResource = new ClassPathResource(configLocation); - assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheManager().getURI()) - .isEqualTo(configResource.getURI()); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderClassName, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + Resource configResource = new ClassPathResource(configLocation); + assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheManager().getURI()) + .isEqualTo(configResource.getURI()); + }); } @Test @@ -610,13 +620,12 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { String cachingProviderFqn = HazelcastServerCachingProvider.class.getName(); try { this.contextRunner.withUserConfiguration(JCacheWithCustomizerConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", - "spring.cache.jcache.provider=" + cachingProviderFqn, "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run((context) -> - // see customizer - assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()).containsOnly("foo", - "custom1")); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> + // see customizer + assertThat(getCacheManager(context, JCacheCacheManager.class).getCacheNames()).containsOnly("foo", + "custom1")); } finally { Caching.getCachingProvider(cachingProviderFqn).close(); @@ -626,53 +635,54 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void cache2kCacheWithExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar").run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar") + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); + }); } @Test void cache2kCacheWithCustomizedDefaults() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k") - .withBean(Cache2kBuilderCustomizer.class, - () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) - .run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).isEmpty(); - Cache dynamic = manager.getCache("dynamic"); - assertThat(dynamic.get("1")).satisfies(hasEntry("default")); - assertThat(dynamic.get("2")).satisfies(hasEntry("default")); - }); + .withPropertyValues("spring.cache.type=cache2k") + .withBean(Cache2kBuilderCustomizer.class, + () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).isEmpty(); + Cache dynamic = manager.getCache("dynamic"); + assertThat(dynamic.get("1")).satisfies(hasEntry("default")); + assertThat(dynamic.get("2")).satisfies(hasEntry("default")); + }); } @Test void cache2kCacheWithCustomizedDefaultsAndExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar") - .withBean(Cache2kBuilderCustomizer.class, - () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) - .run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); - assertThat(manager.getCache("foo").get("1")).satisfies(hasEntry("default")); - assertThat(manager.getCache("bar").get("1")).satisfies(hasEntry("default")); - }); + .withPropertyValues("spring.cache.type=cache2k", "spring.cache.cacheNames=foo,bar") + .withBean(Cache2kBuilderCustomizer.class, + () -> (builder) -> builder.valueType(String.class).loader((key) -> "default")) + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("foo", "bar"); + assertThat(manager.getCache("foo").get("1")).satisfies(hasEntry("default")); + assertThat(manager.getCache("bar").get("1")).satisfies(hasEntry("default")); + }); } @Test void cache2kCacheWithCacheManagerCustomizer() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k") - .withBean(CacheManagerCustomizer.class, - () -> cache2kCacheManagerCustomizer((cacheManager) -> cacheManager.addCache("custom", - (builder) -> builder.valueType(String.class).loader((key) -> "custom")))) - .run((context) -> { - SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); - assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("custom"); - assertThat(manager.getCache("custom").get("1")).satisfies(hasEntry("custom")); - }); + .withPropertyValues("spring.cache.type=cache2k") + .withBean(CacheManagerCustomizer.class, + () -> cache2kCacheManagerCustomizer((cacheManager) -> cacheManager.addCache("custom", + (builder) -> builder.valueType(String.class).loader((key) -> "custom")))) + .run((context) -> { + SpringCache2kCacheManager manager = getCacheManager(context, SpringCache2kCacheManager.class); + assertThat(manager.getCacheNames()).containsExactlyInAnyOrder("custom"); + assertThat(manager.getCache("custom").get("1")).satisfies(hasEntry("custom")); + }); } private CacheManagerCustomizer cache2kCacheManagerCustomizer( @@ -683,62 +693,64 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Test void cache2kCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=cache2k") - .run(verifyCustomizers("allCacheManagerCustomizer", "cache2kCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=cache2k") + .run(verifyCustomizers("allCacheManagerCustomizer", "cache2kCacheManagerCustomizer")); } @Test void caffeineCacheWithExplicitCaches() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo").run((context) -> { - CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); - assertThat(manager.getCacheNames()).containsOnly("foo"); - Cache foo = manager.getCache("foo"); - foo.get("1"); - // See next tests: no spec given so stats should be disabled - assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isZero(); - }); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo") + .run((context) -> { + CaffeineCacheManager manager = getCacheManager(context, CaffeineCacheManager.class); + assertThat(manager.getCacheNames()).containsOnly("foo"); + Cache foo = manager.getCache("foo"); + foo.get("1"); + // See next tests: no spec given so stats should be disabled + assertThat(((CaffeineCache) foo).getNativeCache().stats().missCount()).isZero(); + }); } @Test void caffeineCacheWithCustomizers() { this.contextRunner.withUserConfiguration(DefaultCacheAndCustomizersConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine") - .run(verifyCustomizers("allCacheManagerCustomizer", "caffeineCacheManagerCustomizer")); + .withPropertyValues("spring.cache.type=caffeine") + .run(verifyCustomizers("allCacheManagerCustomizer", "caffeineCacheManagerCustomizer")); } @Test void caffeineCacheWithExplicitCacheBuilder() { this.contextRunner.withUserConfiguration(CaffeineCacheBuilderConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") - .run(this::validateCaffeineCacheWithStats); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames=foo,bar") + .run(this::validateCaffeineCacheWithStats); } @Test void caffeineCacheExplicitWithSpec() { this.contextRunner.withUserConfiguration(CaffeineCacheSpecConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", - "spring.cache.cacheNames[1]=bar") - .run(this::validateCaffeineCacheWithStats); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.cacheNames[0]=foo", + "spring.cache.cacheNames[1]=bar") + .run(this::validateCaffeineCacheWithStats); } @Test void caffeineCacheExplicitWithSpecString() { this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run(this::validateCaffeineCacheWithStats); + .withPropertyValues("spring.cache.type=caffeine", "spring.cache.caffeine.spec=recordStats", + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run(this::validateCaffeineCacheWithStats); } @Test void autoConfiguredCacheManagerCanBeSwapped() { this.contextRunner.withUserConfiguration(CacheManagerPostProcessorConfiguration.class) - .withPropertyValues("spring.cache.type=caffeine").run((context) -> { - getCacheManager(context, SimpleCacheManager.class); - CacheManagerPostProcessor postProcessor = context.getBean(CacheManagerPostProcessor.class); - assertThat(postProcessor.cacheManagers).hasSize(1); - assertThat(postProcessor.cacheManagers.get(0)).isInstanceOf(CaffeineCacheManager.class); - }); + .withPropertyValues("spring.cache.type=caffeine") + .run((context) -> { + getCacheManager(context, SimpleCacheManager.class); + CacheManagerPostProcessor postProcessor = context.getBean(CacheManagerPostProcessor.class); + assertThat(postProcessor.cacheManagers).hasSize(1); + assertThat(postProcessor.cacheManagers.get(0)).isInstanceOf(CaffeineCacheManager.class); + }); } private Consumer hasEntry(Object value) { @@ -843,7 +855,8 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Bean org.springframework.data.redis.cache.RedisCacheConfiguration customRedisCacheConfiguration() { return org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(java.time.Duration.ofSeconds(30)).prefixCacheNameWith("bar"); + .entryTtl(java.time.Duration.ofSeconds(30)) + .prefixCacheNameWith("bar"); } } @@ -854,8 +867,8 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests { @Bean RedisCacheManagerBuilderCustomizer ttlRedisCacheManagerBuilderCustomizer() { - return (builder) -> builder.cacheDefaults( - RedisCacheConfiguration.defaultCacheConfig().entryTtl(java.time.Duration.ofSeconds(10))); + return (builder) -> builder + .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(java.time.Duration.ofSeconds(10))); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java index d24ef02ede..3ee060cffe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/EhCache3CacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,12 +40,12 @@ class EhCache3CacheAutoConfigurationTests extends AbstractCacheAutoConfiguration void ehcache3AsJCacheWithCaches() { String cachingProviderFqn = EhcacheCachingProvider.class.getName(); this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.cacheNames[0]=foo", "spring.cache.cacheNames[1]=bar") + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } @Test @@ -53,15 +53,15 @@ class EhCache3CacheAutoConfigurationTests extends AbstractCacheAutoConfiguration String cachingProviderFqn = EhcacheCachingProvider.class.getName(); String configLocation = "ehcache3.xml"; this.contextRunner.withUserConfiguration(DefaultCacheConfiguration.class) - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation) - .run((context) -> { - JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation) + .run((context) -> { + JCacheCacheManager cacheManager = getCacheManager(context, JCacheCacheManager.class); - Resource configResource = new ClassPathResource(configLocation); - assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); - assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); - }); + Resource configResource = new ClassPathResource(configLocation); + assertThat(cacheManager.getCacheManager().getURI()).isEqualTo(configResource.getURI()); + assertThat(cacheManager.getCacheNames()).containsOnly("foo", "bar"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java index 143f4654ff..e120b79788 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,16 +46,18 @@ class CassandraAutoConfigurationIntegrationTests { static final CassandraContainer cassandra = new CassandraContainer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)).withPropertyValues( - "spring.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), - "spring.cassandra.local-datacenter=datacenter1", "spring.cassandra.connection.connect-timeout=60s", - "spring.cassandra.connection.init-query-timeout=60s", "spring.cassandra.request.timeout=60s"); + .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)) + .withPropertyValues( + "spring.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), + "spring.cassandra.local-datacenter=datacenter1", "spring.cassandra.connection.connect-timeout=60s", + "spring.cassandra.connection.init-query-timeout=60s", "spring.cassandra.request.timeout=60s"); @Test void whenTheContextIsClosedThenTheDriverConfigLoaderIsClosed() { this.contextRunner.withUserConfiguration(DriverConfigLoaderSpyConfiguration.class).run((context) -> { assertThat(((BeanDefinitionRegistry) context.getSourceApplicationContext()) - .getBeanDefinition("cassandraDriverConfigLoader").getDestroyMethodName()).isEmpty(); + .getBeanDefinition("cassandraDriverConfigLoader") + .getDestroyMethodName()).isEmpty(); // Initialize lazy bean context.getBean(CqlSession.class); DriverConfigLoader driverConfigLoader = context.getBean(DriverConfigLoader.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java index ada065306f..9007c60e07 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class CassandraAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)); @Test void cqlSessionBuildHasScopePrototype() { @@ -66,118 +66,137 @@ class CassandraAutoConfigurationTests { void driverConfigLoaderWithDefaultConfiguration() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .isDefined(DefaultDriverOption.SESSION_NAME)).isFalse(); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .isDefined(DefaultDriverOption.SESSION_NAME)).isFalse(); }); } @Test void driverConfigLoaderWithContactPoints() { - this.contextRunner.withPropertyValues("spring.cassandra.contact-points=cluster.example.com:9042", - "spring.cassandra.local-datacenter=cassandra-eu1").run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .containsOnly("cluster.example.com:9042"); - assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) - .isEqualTo("cassandra-eu1"); - }); + this.contextRunner + .withPropertyValues("spring.cassandra.contact-points=cluster.example.com:9042", + "spring.cassandra.local-datacenter=cassandra-eu1") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) + .containsOnly("cluster.example.com:9042"); + assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .isEqualTo("cassandra-eu1"); + }); } @Test void driverConfigLoaderWithContactPointAndNoPort() { this.contextRunner - .withPropertyValues("spring.cassandra.contact-points=cluster.example.com,another.example.com:9041", - "spring.cassandra.local-datacenter=cassandra-eu1") - .run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .containsOnly("cluster.example.com:9042", "another.example.com:9041"); - assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) - .isEqualTo("cassandra-eu1"); - }); + .withPropertyValues("spring.cassandra.contact-points=cluster.example.com,another.example.com:9041", + "spring.cassandra.local-datacenter=cassandra-eu1") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) + .containsOnly("cluster.example.com:9042", "another.example.com:9041"); + assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .isEqualTo("cassandra-eu1"); + }); } @Test void driverConfigLoaderWithContactPointAndNoPortAndCustomPort() { this.contextRunner - .withPropertyValues("spring.cassandra.contact-points=cluster.example.com:9041,another.example.com", - "spring.cassandra.port=9043", "spring.cassandra.local-datacenter=cassandra-eu1") - .run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .containsOnly("cluster.example.com:9041", "another.example.com:9043"); - assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) - .isEqualTo("cassandra-eu1"); - }); + .withPropertyValues("spring.cassandra.contact-points=cluster.example.com:9041,another.example.com", + "spring.cassandra.port=9043", "spring.cassandra.local-datacenter=cassandra-eu1") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + DriverExecutionProfile configuration = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(configuration.getStringList(DefaultDriverOption.CONTACT_POINTS)) + .containsOnly("cluster.example.com:9041", "another.example.com:9043"); + assertThat(configuration.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)) + .isEqualTo("cassandra-eu1"); + }); } @Test void driverConfigLoaderWithCustomSessionName() { this.contextRunner.withPropertyValues("spring.cassandra.session-name=testcluster").run((context) -> { assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); }); } @Test void driverConfigLoaderWithCustomSessionNameAndCustomizer() { this.contextRunner.withUserConfiguration(SimpleDriverConfigLoaderBuilderCustomizerConfig.class) - .withPropertyValues("spring.cassandra.session-name=testcluster").run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("overridden-name"); - }); + .withPropertyValues("spring.cassandra.session-name=testcluster") + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("overridden-name"); + }); } @Test void driverConfigLoaderCustomizeConnectionOptions() { - this.contextRunner.withPropertyValues("spring.cassandra.connection.connect-timeout=200ms", - "spring.cassandra.connection.init-query-timeout=10").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getInt(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT)).isEqualTo(200); - assertThat(config.getInt(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT)).isEqualTo(10); - }); + this.contextRunner + .withPropertyValues("spring.cassandra.connection.connect-timeout=200ms", + "spring.cassandra.connection.init-query-timeout=10") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getInt(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT)).isEqualTo(200); + assertThat(config.getInt(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT)).isEqualTo(10); + }); } @Test void driverConfigLoaderCustomizePoolOptions() { - this.contextRunner.withPropertyValues("spring.cassandra.pool.idle-timeout=42", - "spring.cassandra.pool.heartbeat-interval=62").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_TIMEOUT)).isEqualTo(42); - assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(62); - }); + this.contextRunner + .withPropertyValues("spring.cassandra.pool.idle-timeout=42", "spring.cassandra.pool.heartbeat-interval=62") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_TIMEOUT)).isEqualTo(42); + assertThat(config.getInt(DefaultDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(62); + }); } @Test void driverConfigLoaderCustomizeRequestOptions() { this.contextRunner - .withPropertyValues("spring.cassandra.request.timeout=5s", "spring.cassandra.request.consistency=two", - "spring.cassandra.request.serial-consistency=quorum", "spring.cassandra.request.page-size=42") - .run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getInt(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(5000); - assertThat(config.getString(DefaultDriverOption.REQUEST_CONSISTENCY)).isEqualTo("TWO"); - assertThat(config.getString(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY)).isEqualTo("QUORUM"); - assertThat(config.getInt(DefaultDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(42); - }); + .withPropertyValues("spring.cassandra.request.timeout=5s", "spring.cassandra.request.consistency=two", + "spring.cassandra.request.serial-consistency=quorum", "spring.cassandra.request.page-size=42") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getInt(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(5000); + assertThat(config.getString(DefaultDriverOption.REQUEST_CONSISTENCY)).isEqualTo("TWO"); + assertThat(config.getString(DefaultDriverOption.REQUEST_SERIAL_CONSISTENCY)).isEqualTo("QUORUM"); + assertThat(config.getInt(DefaultDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(42); + }); } @Test void driverConfigLoaderCustomizeControlConnectionOptions() { this.contextRunner.withPropertyValues("spring.cassandra.controlconnection.timeout=200ms").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); assertThat(config.getInt(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT)).isEqualTo(200); }); } @@ -185,76 +204,88 @@ class CassandraAutoConfigurationTests { @Test void driverConfigLoaderUsePassThroughLimitingRequestThrottlerByDefault() { this.contextRunner.withPropertyValues().run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo(PassThroughRequestThrottler.class.getSimpleName()); + .isEqualTo(PassThroughRequestThrottler.class.getSimpleName()); }); } @Test void driverConfigLoaderWithRateLimitingRequiresExtraConfiguration() { this.contextRunner.withPropertyValues("spring.cassandra.request.throttler.type=rate-limiting") - .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) - .hasMessageContaining("Error instantiating class RateLimitingRequestThrottler") - .hasMessageContaining("No configuration setting found for key")); + .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) + .hasMessageContaining("Error instantiating class RateLimitingRequestThrottler") + .hasMessageContaining("No configuration setting found for key")); } @Test void driverConfigLoaderCustomizeConcurrencyLimitingRequestThrottler() { - this.contextRunner.withPropertyValues("spring.cassandra.request.throttler.type=concurrency-limiting", - "spring.cassandra.request.throttler.max-concurrent-requests=62", - "spring.cassandra.request.throttler.max-queue-size=72").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo(ConcurrencyLimitingRequestThrottler.class.getSimpleName()); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS)) - .isEqualTo(62); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); - }); + this.contextRunner + .withPropertyValues("spring.cassandra.request.throttler.type=concurrency-limiting", + "spring.cassandra.request.throttler.max-concurrent-requests=62", + "spring.cassandra.request.throttler.max-queue-size=72") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) + .isEqualTo(ConcurrencyLimitingRequestThrottler.class.getSimpleName()); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_CONCURRENT_REQUESTS)).isEqualTo(62); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); + }); } @Test void driverConfigLoaderCustomizeRateLimitingRequestThrottler() { - this.contextRunner.withPropertyValues("spring.cassandra.request.throttler.type=rate-limiting", - "spring.cassandra.request.throttler.max-requests-per-second=62", - "spring.cassandra.request.throttler.max-queue-size=72", - "spring.cassandra.request.throttler.drain-interval=16ms").run((context) -> { - DriverExecutionProfile config = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); - assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo(RateLimitingRequestThrottler.class.getSimpleName()); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND)) - .isEqualTo(62); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); - assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL)).isEqualTo(16); - }); + this.contextRunner + .withPropertyValues("spring.cassandra.request.throttler.type=rate-limiting", + "spring.cassandra.request.throttler.max-requests-per-second=62", + "spring.cassandra.request.throttler.max-queue-size=72", + "spring.cassandra.request.throttler.drain-interval=16ms") + .run((context) -> { + DriverExecutionProfile config = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); + assertThat(config.getString(DefaultDriverOption.REQUEST_THROTTLER_CLASS)) + .isEqualTo(RateLimitingRequestThrottler.class.getSimpleName()); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND)).isEqualTo(62); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(72); + assertThat(config.getInt(DefaultDriverOption.REQUEST_THROTTLER_DRAIN_INTERVAL)).isEqualTo(16); + }); } @Test void driverConfigLoaderWithConfigComplementSettings() { String configLocation = "org/springframework/boot/autoconfigure/cassandra/simple.conf"; - this.contextRunner.withPropertyValues("spring.cassandra.session-name=testcluster", - "spring.cassandra.config=" + configLocation).run((context) -> { - assertThat(context).hasSingleBean(DriverConfigLoader.class); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); - assertThat(context.getBean(DriverConfigLoader.class).getInitialConfig().getDefaultProfile() - .getDuration(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofMillis(500)); - }); + this.contextRunner + .withPropertyValues("spring.cassandra.session-name=testcluster", + "spring.cassandra.config=" + configLocation) + .run((context) -> { + assertThat(context).hasSingleBean(DriverConfigLoader.class); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("testcluster"); + assertThat(context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile() + .getDuration(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofMillis(500)); + }); } @Test // gh-31238 void driverConfigLoaderWithConfigOverridesDefaults() { String configLocation = "org/springframework/boot/autoconfigure/cassandra/override-defaults.conf"; this.contextRunner.withPropertyValues("spring.cassandra.config=" + configLocation).run((context) -> { - DriverExecutionProfile actual = context.getBean(DriverConfigLoader.class).getInitialConfig() - .getDefaultProfile(); + DriverExecutionProfile actual = context.getBean(DriverConfigLoader.class) + .getInitialConfig() + .getDefaultProfile(); assertThat(actual.getString(DefaultDriverOption.SESSION_NAME)).isEqualTo("advanced session"); assertThat(actual.getDuration(DefaultDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofSeconds(2)); assertThat(actual.getStringList(DefaultDriverOption.CONTACT_POINTS)) - .isEqualTo(Collections.singletonList("1.2.3.4:5678")); + .isEqualTo(Collections.singletonList("1.2.3.4:5678")); assertThat(actual.getBoolean(DefaultDriverOption.RESOLVE_CONTACT_POINTS)).isFalse(); assertThat(actual.getInt(DefaultDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(11); assertThat(actual.getString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER)).isEqualTo("datacenter1"); @@ -262,7 +293,7 @@ class CassandraAutoConfigurationTests { assertThat(actual.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_REQUESTS_PER_SECOND)).isEqualTo(33); assertThat(actual.getInt(DefaultDriverOption.REQUEST_THROTTLER_MAX_QUEUE_SIZE)).isEqualTo(44); assertThat(actual.getDuration(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT)) - .isEqualTo(Duration.ofMillis(5555)); + .isEqualTo(Duration.ofMillis(5555)); assertThat(actual.getString(DefaultDriverOption.PROTOCOL_COMPRESSION)).isEqualTo("SNAPPY"); }); } @@ -275,7 +306,7 @@ class CassandraAutoConfigurationTests { DriverConfig driverConfig = context.getBean(DriverConfigLoader.class).getInitialConfig(); assertThat(driverConfig.getProfiles()).containsOnlyKeys("default", "first", "second"); assertThat(driverConfig.getProfile("first").getDuration(DefaultDriverOption.REQUEST_TIMEOUT)) - .isEqualTo(Duration.ofMillis(100)); + .isEqualTo(Duration.ofMillis(100)); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java index ae2202a5c7..cf8cc26868 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,32 +52,33 @@ class CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests { @Container static final CassandraContainer cassandra = new PasswordAuthenticatorCassandraContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)).waitingFor(new CassandraWaitStrategy()); + .withStartupTimeout(Duration.ofMinutes(10)) + .waitingFor(new CassandraWaitStrategy()); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)).withPropertyValues( - "spring.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), - "spring.cassandra.local-datacenter=datacenter1", "spring.cassandra.connection.connect-timeout=60s", - "spring.cassandra.connection.init-query-timeout=60s", "spring.cassandra.request.timeout=60s"); + .withConfiguration(AutoConfigurations.of(CassandraAutoConfiguration.class)) + .withPropertyValues( + "spring.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), + "spring.cassandra.local-datacenter=datacenter1", "spring.cassandra.connection.connect-timeout=60s", + "spring.cassandra.connection.init-query-timeout=60s", "spring.cassandra.request.timeout=60s"); @Test void authenticationWithValidUsernameAndPassword() { this.contextRunner - .withPropertyValues("spring.cassandra.username=cassandra", "spring.cassandra.password=cassandra") - .run((context) -> { - SimpleStatement select = SimpleStatement.newInstance("SELECT release_version FROM system.local") - .setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); - assertThat(context.getBean(CqlSession.class).execute(select).one()).isNotNull(); - }); + .withPropertyValues("spring.cassandra.username=cassandra", "spring.cassandra.password=cassandra") + .run((context) -> { + SimpleStatement select = SimpleStatement.newInstance("SELECT release_version FROM system.local") + .setConsistencyLevel(ConsistencyLevel.LOCAL_ONE); + assertThat(context.getBean(CqlSession.class).execute(select).one()).isNotNull(); + }); } @Test void authenticationWithInvalidCredentials() { this.contextRunner - .withPropertyValues("spring.cassandra.username=not-a-user", - "spring.cassandra.password=invalid-password") - .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) - .hasMessageContaining("Authentication error")); + .withPropertyValues("spring.cassandra.username=not-a-user", "spring.cassandra.password=invalid-password") + .run((context) -> assertThatThrownBy(() -> context.getBean(CqlSession.class)) + .hasMessageContaining("Authentication error")); } static final class PasswordAuthenticatorCassandraContainer extends CassandraContainer { @@ -112,9 +113,10 @@ class CassandraAutoConfigurationWithPasswordAuthenticationIntegrationTests { private CqlSessionBuilder cqlSessionBuilder() { return CqlSession.builder() - .addContactPoint(new InetSocketAddress(this.waitStrategyTarget.getHost(), - this.waitStrategyTarget.getFirstMappedPort())) - .withLocalDatacenter("datacenter1").withAuthCredentials("cassandra", "cassandra"); + .addContactPoint(new InetSocketAddress(this.waitStrategyTarget.getHost(), + this.waitStrategyTarget.getFirstMappedPort())) + .withLocalDatacenter("datacenter1") + .withAuthCredentials("cassandra", "cassandra"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java index 3096ffc49e..a0e92e93df 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cassandra/CassandraPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,14 +44,14 @@ class CassandraPropertiesTests { assertThat(driverDefaults.get(TypedDriverOption.CONNECTION_CONNECT_TIMEOUT)).isEqualTo(Duration.ofSeconds(5)); // spring.cassandra.connection.init-query-timeout assertThat(driverDefaults.get(TypedDriverOption.CONNECTION_INIT_QUERY_TIMEOUT)) - .isEqualTo(Duration.ofSeconds(5)); + .isEqualTo(Duration.ofSeconds(5)); // spring.cassandra.request.timeout assertThat(driverDefaults.get(TypedDriverOption.REQUEST_TIMEOUT)).isEqualTo(Duration.ofSeconds(2)); // spring.cassandra.request.page-size assertThat(driverDefaults.get(TypedDriverOption.REQUEST_PAGE_SIZE)).isEqualTo(5000); // spring.cassandra.request.throttler.type assertThat(driverDefaults.get(TypedDriverOption.REQUEST_THROTTLER_CLASS)) - .isEqualTo("PassThroughRequestThrottler"); // "none" + .isEqualTo("PassThroughRequestThrottler"); // "none" // spring.cassandra.pool.heartbeat-interval assertThat(driverDefaults.get(TypedDriverOption.HEARTBEAT_INTERVAL)).isEqualTo(Duration.ofSeconds(30)); // spring.cassandra.pool.idle-timeout diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java index 830af0c1e4..6a723472bf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class AbstractNestedConditionTests { @Test void validPhase() { this.contextRunner.withUserConfiguration(ValidConfig.class) - .run((context) -> assertThat(context).hasBean("myBean")); + .run((context) -> assertThat(context).hasBean("myBean")); } @Test @@ -45,9 +45,9 @@ class AbstractNestedConditionTests { this.contextRunner.withUserConfiguration(InvalidConfig.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Nested condition " + InvalidNestedCondition.class.getName() - + " uses a configuration phase that is inappropriate for class " - + OnBeanCondition.class.getName()); + .hasMessageContaining("Nested condition " + InvalidNestedCondition.class.getName() + + " uses a configuration phase that is inappropriate for class " + + OnBeanCondition.class.getName()); }); } @@ -56,9 +56,9 @@ class AbstractNestedConditionTests { this.contextRunner.withUserConfiguration(DoubleNestedConfig.class).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure().getCause()).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Nested condition " + DoubleNestedCondition.class.getName() - + " uses a configuration phase that is inappropriate for class " - + ValidNestedCondition.class.getName()); + .hasMessageContaining("Nested condition " + DoubleNestedCondition.class.getName() + + " uses a configuration phase that is inappropriate for class " + + ValidNestedCondition.class.getName()); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java index e090fc0225..0e0ad4eb34 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -53,9 +53,9 @@ class ConditionEvaluationReportAutoConfigurationImportListenerTests { @Test void shouldBeInSpringFactories() { List factories = SpringFactoriesLoader - .loadFactories(AutoConfigurationImportListener.class, null); + .loadFactories(AutoConfigurationImportListener.class, null); assertThat(factories) - .hasAtLeastOneElementOfType(ConditionEvaluationReportAutoConfigurationImportListener.class); + .hasAtLeastOneElementOfType(ConditionEvaluationReportAutoConfigurationImportListener.class); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java index cb7a599d3c..2e130ff8c9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportTests.java @@ -98,7 +98,7 @@ class ConditionEvaluationReportTests { ConditionEvaluationReport.get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory()); assertThat(this.report).isSameAs(ConditionEvaluationReport.get(this.beanFactory)); assertThat(this.report.getParent()).isSameAs(ConditionEvaluationReport - .get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory())); + .get((ConfigurableListableBeanFactory) this.beanFactory.getParentBeanFactory())); } @Test @@ -163,7 +163,7 @@ class ConditionEvaluationReportTests { @SuppressWarnings("resource") void springBootConditionPopulatesReport() { ConditionEvaluationReport report = ConditionEvaluationReport - .get(new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); + .get(new AnnotationConfigApplicationContext(Config.class).getBeanFactory()); assertThat(report.getConditionAndOutcomesBySource().size()).isNotZero(); } @@ -245,7 +245,7 @@ class ConditionEvaluationReportTests { "org.springframework.boot.autoconfigure.condition.config.first.SampleAutoConfiguration", "org.springframework.boot.autoconfigure.condition.config.second.SampleAutoConfiguration"); assertThat(reportMessage) - .doesNotContain("org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"); + .doesNotContain("org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"); context.close(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java index 2f4e7bbb11..2e49bd2d23 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionMessageTests.java @@ -146,15 +146,17 @@ class ConditionMessageTests { @Test void foundWhenMultipleElementsShouldUsePlural() { - ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items("a", "b", - "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .found("bean", "beans") + .items("a", "b", "c"); assertThat(message).hasToString("@Test found beans a, b, c"); } @Test void foundWhenQuoteStyleShouldQuote() { - ConditionMessage message = ConditionMessage.forCondition(Test.class).found("bean", "beans").items(Style.QUOTE, - "a", "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .found("bean", "beans") + .items(Style.QUOTE, "a", "b", "c"); assertThat(message).hasToString("@Test found beans 'a', 'b', 'c'"); } @@ -166,8 +168,9 @@ class ConditionMessageTests { @Test void didNotFindWhenMultipleElementsShouldUsePlural() { - ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("class", "classes").items("a", - "b", "c"); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .didNotFind("class", "classes") + .items("a", "b", "c"); assertThat(message).hasToString("@Test did not find classes a, b, c"); } @@ -199,8 +202,9 @@ class ConditionMessageTests { @Test void quotedItemsTolerateNullInput() { Collection items = null; - ConditionMessage message = ConditionMessage.forCondition(Test.class).didNotFind("item").items(Style.QUOTE, - items); + ConditionMessage message = ConditionMessage.forCondition(Test.class) + .didNotFind("item") + .items(Style.QUOTE, items); assertThat(message).hasToString("@Test did not find item"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java index ba292a857c..f77c3e5f9a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,76 +59,76 @@ class ConditionalOnBeanTests { @Test void testNameOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testNameAndTypeOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void testNameOnBeanConditionReverseOrder() { // Ideally this should be true this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void testClassOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testClassOnBeanClassNameCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanClassNameConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testOnBeanConditionWithXml() { this.contextRunner.withUserConfiguration(XmlConfiguration.class, OnBeanNameConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testOnBeanConditionWithCombinedXml() { // Ideally this should be true this.contextRunner.withUserConfiguration(CombinedXmlConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void testAnnotationOnBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test void testOnMissingBeanType() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanMissingClassConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void withPropertyPlaceholderClassName() { this.contextRunner - .withUserConfiguration(PropertySourcesPlaceholderConfigurer.class, - WithPropertyPlaceholderClassName.class, OnBeanClassConfiguration.class) - .withPropertyValues("mybeanclass=java.lang.String") - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(PropertySourcesPlaceholderConfigurer.class, WithPropertyPlaceholderClassName.class, + OnBeanClassConfiguration.class) + .withPropertyValues("mybeanclass=java.lang.String") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { this.contextRunner - .withUserConfiguration(FactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("bar"); - assertThat(context).hasSingleBean(ExampleBean.class); - }); + .withUserConfiguration(FactoryBeanConfiguration.class, OnAnnotationWithFactoryBeanConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("bar"); + assertThat(context).hasSingleBean(ExampleBean.class); + }); } private void hasBarBean(AssertableApplicationContext context) { @@ -140,8 +140,9 @@ class ConditionalOnBeanTests { void onBeanConditionOutputShouldNotContainConditionalOnMissingBeanClassInMessage() { this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class).run((context) -> { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() - .values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); String message = conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); assertThat(message).doesNotContain("@ConditionalOnMissingBean"); }); @@ -149,81 +150,81 @@ class ConditionalOnBeanTests { @Test void conditionEvaluationConsidersChangeInTypeWhenBeanIsOverridden() { - this.contextRunner.withAllowBeanDefinitionOverriding(true).withUserConfiguration(OriginalDefinition.class, - OverridingDefinition.class, ConsumingConfiguration.class).run((context) -> { - assertThat(context).hasBean("testBean"); - assertThat(context).hasSingleBean(Integer.class); - assertThat(context).doesNotHaveBean(ConsumingConfiguration.class); - }); + this.contextRunner.withAllowBeanDefinitionOverriding(true) + .withUserConfiguration(OriginalDefinition.class, OverridingDefinition.class, ConsumingConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("testBean"); + assertThat(context).hasSingleBean(Integer.class); + assertThat(context).doesNotHaveBean(ConsumingConfiguration.class); + }); } @Test void parameterizedContainerWhenValueIsOfMissingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfMissingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("otherExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("customExampleBean", "conditionalCustomExampleBean"))); } private Consumer exampleBeanRequirement(String... names) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java index 3bd18519c1..ceb4cd2bdb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class ConditionalOnClassTests { @Test void testVanillaOnClassCondition() { this.contextRunner.withUserConfiguration(BasicConfiguration.class, FooConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test @@ -57,7 +57,7 @@ class ConditionalOnClassTests { @Test void testOnClassConditionWithXml() { this.contextRunner.withUserConfiguration(BasicConfiguration.class, XmlConfiguration.class) - .run(this::hasBarBean); + .run(this::hasBarBean); } @Test @@ -69,8 +69,9 @@ class ConditionalOnClassTests { void onClassConditionOutputShouldNotContainConditionalOnMissingClassInMessage() { this.contextRunner.withUserConfiguration(BasicConfiguration.class).run((context) -> { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() - .values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); String message = conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); assertThat(message).doesNotContain("@ConditionalOnMissingClass did not find unwanted class"); }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java index 8cdeafcefd..76c3f3feb7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCloudPlatformTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,19 +35,21 @@ class ConditionalOnCloudPlatformTests { @Test void outcomeWhenCloudfoundryPlatformNotPresentShouldNotMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) - .run((context) -> assertThat(context).doesNotHaveBean("foo")); + .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test void outcomeWhenCloudfoundryPlatformPresentShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformConfig.class) - .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); + .withPropertyValues("VCAP_APPLICATION:---") + .run((context) -> assertThat(context).hasBean("foo")); } @Test void outcomeWhenCloudfoundryPlatformPresentAndMethodTargetShouldMatch() { this.contextRunner.withUserConfiguration(CloudFoundryPlatformOnMethodConfig.class) - .withPropertyValues("VCAP_APPLICATION:---").run((context) -> assertThat(context).hasBean("foo")); + .withPropertyValues("VCAP_APPLICATION:---") + .run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java index 9316faba01..36cb94382c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -44,19 +44,19 @@ class ConditionalOnExpressionTests { @Test void expressionIsTrue() { this.contextRunner.withUserConfiguration(BasicConfiguration.class) - .run((context) -> assertThat(context.getBean("foo")).isEqualTo("foo")); + .run((context) -> assertThat(context.getBean("foo")).isEqualTo("foo")); } @Test void expressionEvaluatesToTrueRegistersBean() { this.contextRunner.withUserConfiguration(MissingConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("foo")); + .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test void expressionEvaluatesToFalseDoesNotRegisterBean() { this.contextRunner.withUserConfiguration(NullConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("foo")); + .run((context) -> assertThat(context).doesNotHaveBean("foo")); } @Test @@ -73,7 +73,7 @@ class ConditionalOnExpressionTests { private AnnotatedTypeMetadata mockMetaData(String value) { AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class); given(metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName())) - .willReturn(Collections.singletonMap("value", value)); + .willReturn(Collections.singletonMap("value", value)); return metadata; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java index 1a42d0b5e3..439c5c15c5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJavaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,20 +49,20 @@ class ConditionalOnJavaTests { @EnabledOnJre(JRE.JAVA_17) void doesNotMatchIfBetterVersionIsRequired() { this.contextRunner.withUserConfiguration(Java18Required.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test @EnabledOnJre(JRE.JAVA_18) void doesNotMatchIfLowerIsRequired() { this.contextRunner.withUserConfiguration(OlderThan18Required.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void matchesIfVersionIsInRange() { this.contextRunner.withUserConfiguration(Java17Required.class) - .run((context) -> assertThat(context).hasSingleBean(String.class)); + .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java index 9b3ab0ada2..d1635feec1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -74,21 +74,21 @@ class ConditionalOnJndiTests { @Test void jndiNotAvailable() { this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void jndiAvailable() { setupJndi(); this.contextRunner.withUserConfiguration(JndiAvailableConfiguration.class, JndiConditionConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(String.class)); + .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test void jndiLocationNotBound() { setupJndi(); this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test @@ -96,7 +96,7 @@ class ConditionalOnJndiTests { setupJndi(); TestableInitialContextFactory.bind("java:/FooManager", new Object()); this.contextRunner.withUserConfiguration(JndiConditionConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(String.class)); + .run((context) -> assertThat(context).hasSingleBean(String.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java index 79ef300d09..06072ca231 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,21 +68,21 @@ class ConditionalOnMissingBeanTests { @Test void testNameOnMissingBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test void testNameOnMissingBeanConditionReverseOrder() { this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class, FooConfiguration.class) - .run((context) -> { - // Ideally this would be doesNotHaveBean, but the ordering is a - // problem - assertThat(context).hasBean("bar"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .run((context) -> { + // Ideally this would be doesNotHaveBean, but the ordering is a + // problem + assertThat(context).hasBean("bar"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test @@ -91,59 +91,60 @@ class ConditionalOnMissingBeanTests { // specified in the different attributes of @ConditionalOnBean are combined with // logical OR (not AND) so if any of them match the condition is true. this.contextRunner.withUserConfiguration(FooConfiguration.class, OnBeanNameAndTypeConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("bar")); + .run((context) -> assertThat(context).doesNotHaveBean("bar")); } @Test void hierarchyConsidered() { this.contextRunner.withUserConfiguration(FooConfiguration.class) - .run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(HierarchyConsidered.class) - .run((context) -> assertThat(context.containsLocalBean("bar")).isFalse())); + .run((parent) -> new ApplicationContextRunner().withParent(parent) + .withUserConfiguration(HierarchyConsidered.class) + .run((context) -> assertThat(context.containsLocalBean("bar")).isFalse())); } @Test void hierarchyNotConsidered() { this.contextRunner.withUserConfiguration(FooConfiguration.class) - .run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(HierarchyNotConsidered.class) - .run((context) -> assertThat(context.containsLocalBean("bar")).isTrue())); + .run((parent) -> new ApplicationContextRunner().withParent(parent) + .withUserConfiguration(HierarchyNotConsidered.class) + .run((context) -> assertThat(context.containsLocalBean("bar")).isTrue())); } @Test void impliedOnBeanMethod() { this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class, ImpliedOnBeanMethod.class) - .run((context) -> assertThat(context).hasSingleBean(ExampleBean.class)); + .run((context) -> assertThat(context).hasSingleBean(ExampleBean.class)); } @Test void testAnnotationOnMissingBeanCondition() { this.contextRunner.withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test void testAnnotationOnMissingBeanConditionWithEagerFactoryBean() { // Rigorous test for SPR-11069 this.contextRunner - .withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class, - FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context).hasBean("example"); - assertThat(context.getBean("foo")).isEqualTo("foo"); - }); + .withUserConfiguration(FooConfiguration.class, OnAnnotationConfiguration.class, + FactoryBeanXmlConfiguration.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context).hasBean("example"); + assertThat(context.getBean("foo")).isEqualTo("foo"); + }); } @Test void testOnMissingBeanConditionOutputShouldNotContainConditionalOnBeanClassInMessage() { this.contextRunner.withUserConfiguration(OnBeanNameConfiguration.class).run((context) -> { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource() - .values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); String message = conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); assertThat(message).doesNotContain("@ConditionalOnBean"); }); @@ -152,192 +153,196 @@ class ConditionalOnMissingBeanTests { @Test void testOnMissingBeanConditionWithFactoryBean() { this.contextRunner - .withUserConfiguration(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(FactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithComponentScannedFactoryBean() { this.contextRunner - .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithComponentScannedFactoryBeanWithBeanMethodArguments() { this.contextRunner - .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(ComponentScannedFactoryBeanBeanMethodWithArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ScanBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithFactoryBeanWithBeanMethodArguments() { this.contextRunner - .withUserConfiguration(FactoryBeanWithBeanMethodArgumentsConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .withPropertyValues("theValue=foo") - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(FactoryBeanWithBeanMethodArgumentsConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .withPropertyValues("theValue=foo") + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithConcreteFactoryBean() { this.contextRunner - .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithUnhelpfulFactoryBean() { // We could not tell that the FactoryBean would ultimately create an ExampleBean this.contextRunner - .withUserConfiguration(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2)); + .withUserConfiguration(UnhelpfulFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2)); } @Test void testOnMissingBeanConditionWithRegisteredFactoryBean() { this.contextRunner - .withUserConfiguration(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(RegisteredFactoryBeanConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithNonspecificFactoryBeanWithClassAttribute() { this.contextRunner - .withUserConfiguration(NonspecificFactoryBeanClassAttributeConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(NonspecificFactoryBeanClassAttributeConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithNonspecificFactoryBeanWithStringAttribute() { this.contextRunner - .withUserConfiguration(NonspecificFactoryBeanStringAttributeConfiguration.class, - ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(NonspecificFactoryBeanStringAttributeConfiguration.class, + ConditionalOnFactoryBean.class, PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithFactoryBeanInXml() { this.contextRunner - .withUserConfiguration(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, - PropertyPlaceholderAutoConfiguration.class) - .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); + .withUserConfiguration(FactoryBeanXmlConfiguration.class, ConditionalOnFactoryBean.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> assertThat(context.getBean(ExampleBean.class).toString()).isEqualTo("fromFactory")); } @Test void testOnMissingBeanConditionWithIgnoredSubclass() { - this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclass.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { - assertThat(context).getBeans(ExampleBean.class).hasSize(2); - assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); - }); + this.contextRunner + .withUserConfiguration(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclass.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> { + assertThat(context).getBeans(ExampleBean.class).hasSize(2); + assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); + }); } @Test void testOnMissingBeanConditionWithIgnoredSubclassByName() { - this.contextRunner.withUserConfiguration(CustomExampleBeanConfiguration.class, - ConditionalOnIgnoredSubclassByName.class, PropertyPlaceholderAutoConfiguration.class).run((context) -> { - assertThat(context).getBeans(ExampleBean.class).hasSize(2); - assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); - }); + this.contextRunner + .withUserConfiguration(CustomExampleBeanConfiguration.class, ConditionalOnIgnoredSubclassByName.class, + PropertyPlaceholderAutoConfiguration.class) + .run((context) -> { + assertThat(context).getBeans(ExampleBean.class).hasSize(2); + assertThat(context).getBeans(CustomExampleBean.class).hasSize(1); + }); } @Test void grandparentIsConsideredWhenUsingAncestorsStrategy() { this.contextRunner.withUserConfiguration(ExampleBeanConfiguration.class) - .run((grandparent) -> new ApplicationContextRunner().withParent(grandparent) - .run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(ExampleBeanConfiguration.class, - OnBeanInAncestorsConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(1)))); + .run((grandparent) -> new ApplicationContextRunner().withParent(grandparent) + .run((parent) -> new ApplicationContextRunner().withParent(parent) + .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(1)))); } @Test void currentContextIsIgnoredWhenUsingAncestorsStrategy() { this.contextRunner.run((parent) -> new ApplicationContextRunner().withParent(parent) - .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) - .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2))); + .withUserConfiguration(ExampleBeanConfiguration.class, OnBeanInAncestorsConfiguration.class) + .run((context) -> assertThat(context).getBeans(ExampleBean.class).hasSize(2))); } @Test void beanProducedByFactoryBeanIsConsideredWhenMatchingOnAnnotation() { - this.contextRunner.withUserConfiguration(ConcreteFactoryBeanConfiguration.class, - OnAnnotationWithFactoryBeanConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean("bar"); - assertThat(context).hasSingleBean(ExampleBean.class); - }); + this.contextRunner + .withUserConfiguration(ConcreteFactoryBeanConfiguration.class, + OnAnnotationWithFactoryBeanConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean("bar"); + assertThat(context).hasSingleBean(ExampleBean.class); + }); } @Test void parameterizedContainerWhenValueIsOfMissingBeanMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfMissingBeanRegistrationMatches() { this.contextRunner - .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context) - .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); + .withUserConfiguration(ParameterizedWithoutCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context) + .satisfies(exampleBeanRequirement("otherExampleBean", "conditionalCustomExampleBean"))); } @Test void parameterizedContainerWhenValueIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithValueConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithValueConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnTypeIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } @Test void parameterizedContainerWhenReturnRegistrationTypeIsOfExistingBeanRegistrationDoesNotMatch() { this.contextRunner - .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, - ParameterizedConditionWithReturnRegistrationTypeConfig.class) - .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); + .withUserConfiguration(ParameterizedWithCustomContainerConfig.class, + ParameterizedConditionWithReturnRegistrationTypeConfig.class) + .run((context) -> assertThat(context).satisfies(exampleBeanRequirement("customExampleBean"))); } private Consumer exampleBeanRequirement(String... names) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java index 8477400909..b71644c56a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingBeanWithFilteredClasspathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ConditionalOnMissingBeanWithFilteredClasspathTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(OnBeanTypeConfiguration.class); + .withUserConfiguration(OnBeanTypeConfiguration.class); @Test void testNameOnMissingBeanTypeWithMissingImport() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java index c428c218ca..2c92ac5ee1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnNotWebApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,20 +42,20 @@ class ConditionalOnNotWebApplicationTests { @Test void testNotWebApplicationWithServletContext() { new WebApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void testNotWebApplicationWithReactiveContext() { new ReactiveWebApplicationContextRunner() - .withUserConfiguration(ReactiveApplicationConfig.class, NotWebApplicationConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(String.class)); + .withUserConfiguration(ReactiveApplicationConfig.class, NotWebApplicationConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(String.class)); } @Test void testNotWebApplication() { new ApplicationContextRunner().withUserConfiguration(NotWebApplicationConfiguration.class) - .run((context) -> assertThat(context).getBeans(String.class).containsExactly(entry("none", "none"))); + .run((context) -> assertThat(context).getBeans(String.class).containsExactly(entry("none", "none"))); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java index b1194cad8f..f663915ce9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -196,15 +196,14 @@ class ConditionalOnPropertyTests { @Test void nameOrValueMustBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property")) - .satisfies(causeMessageContaining( - "The name or value attribute of @ConditionalOnProperty must be specified")); + .satisfies( + causeMessageContaining("The name or value attribute of @ConditionalOnProperty must be specified")); } @Test void nameAndValueMustNotBeSpecified() { assertThatIllegalStateException().isThrownBy(() -> load(NameAndValueAttribute.class, "some.property")) - .satisfies(causeMessageContaining( - "The name and value attributes of @ConditionalOnProperty are exclusive")); + .satisfies(causeMessageContaining("The name and value attributes of @ConditionalOnProperty are exclusive")); } private Consumer causeMessageContaining(String message) { @@ -274,8 +273,9 @@ class ConditionalOnPropertyTests { private void load(Class config, String... environment) { TestPropertyValues.of(environment).applyTo(this.environment); - this.context = new SpringApplicationBuilder(config).environment(this.environment).web(WebApplicationType.NONE) - .run(); + this.context = new SpringApplicationBuilder(config).environment(this.environment) + .web(WebApplicationType.NONE) + .run(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index e45270073a..292c119f11 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -40,89 +40,95 @@ class ConditionalOnSingleCandidateTests { @Test void singleCandidateNoCandidate() { this.contextRunner.withUserConfiguration(OnBeanSingleCandidateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("consumer")); + .run((context) -> assertThat(context).doesNotHaveBean("consumer")); } @Test void singleCandidateOneCandidate() { this.contextRunner.withUserConfiguration(AlphaConfiguration.class, OnBeanSingleCandidateConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("consumer"); - assertThat(context.getBean("consumer")).isEqualTo("alpha"); - }); + .run((context) -> { + assertThat(context).hasBean("consumer"); + assertThat(context.getBean("consumer")).isEqualTo("alpha"); + }); } @Test void singleCandidateOneScopedProxyCandidate() { this.contextRunner - .withUserConfiguration(AlphaScopedProxyConfiguration.class, OnBeanSingleCandidateConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("consumer"); - assertThat(context.getBean("consumer")).hasToString("alpha"); - }); + .withUserConfiguration(AlphaScopedProxyConfiguration.class, OnBeanSingleCandidateConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("consumer"); + assertThat(context.getBean("consumer")).hasToString("alpha"); + }); } @Test void singleCandidateInAncestorsOneCandidateInCurrent() { this.contextRunner.run((parent) -> this.contextRunner - .withUserConfiguration(AlphaConfiguration.class, OnBeanSingleCandidateInAncestorsConfiguration.class) - .withParent(parent).run((child) -> assertThat(child).doesNotHaveBean("consumer"))); + .withUserConfiguration(AlphaConfiguration.class, OnBeanSingleCandidateInAncestorsConfiguration.class) + .withParent(parent) + .run((child) -> assertThat(child).doesNotHaveBean("consumer"))); } @Test void singleCandidateInAncestorsOneCandidateInParent() { this.contextRunner.withUserConfiguration(AlphaConfiguration.class) - .run((parent) -> this.contextRunner - .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class).withParent(parent) - .run((child) -> { - assertThat(child).hasBean("consumer"); - assertThat(child.getBean("consumer")).isEqualTo("alpha"); - })); + .run((parent) -> this.contextRunner + .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class) + .withParent(parent) + .run((child) -> { + assertThat(child).hasBean("consumer"); + assertThat(child.getBean("consumer")).isEqualTo("alpha"); + })); } @Test void singleCandidateInAncestorsOneCandidateInGrandparent() { this.contextRunner.withUserConfiguration(AlphaConfiguration.class) - .run((grandparent) -> this.contextRunner.withParent(grandparent) - .run((parent) -> this.contextRunner - .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class) - .withParent(parent).run((child) -> { - assertThat(child).hasBean("consumer"); - assertThat(child.getBean("consumer")).isEqualTo("alpha"); - }))); + .run((grandparent) -> this.contextRunner.withParent(grandparent) + .run((parent) -> this.contextRunner + .withUserConfiguration(OnBeanSingleCandidateInAncestorsConfiguration.class) + .withParent(parent) + .run((child) -> { + assertThat(child).hasBean("consumer"); + assertThat(child.getBean("consumer")).isEqualTo("alpha"); + }))); } @Test void singleCandidateMultipleCandidates() { this.contextRunner - .withUserConfiguration(AlphaConfiguration.class, BravoConfiguration.class, - OnBeanSingleCandidateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("consumer")); + .withUserConfiguration(AlphaConfiguration.class, BravoConfiguration.class, + OnBeanSingleCandidateConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean("consumer")); } @Test void singleCandidateMultipleCandidatesOnePrimary() { - this.contextRunner.withUserConfiguration(AlphaPrimaryConfiguration.class, BravoConfiguration.class, - OnBeanSingleCandidateConfiguration.class).run((context) -> { - assertThat(context).hasBean("consumer"); - assertThat(context.getBean("consumer")).isEqualTo("alpha"); - }); + this.contextRunner + .withUserConfiguration(AlphaPrimaryConfiguration.class, BravoConfiguration.class, + OnBeanSingleCandidateConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("consumer"); + assertThat(context.getBean("consumer")).isEqualTo("alpha"); + }); } @Test void singleCandidateMultipleCandidatesMultiplePrimary() { this.contextRunner - .withUserConfiguration(AlphaPrimaryConfiguration.class, BravoPrimaryConfiguration.class, - OnBeanSingleCandidateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("consumer")); + .withUserConfiguration(AlphaPrimaryConfiguration.class, BravoPrimaryConfiguration.class, + OnBeanSingleCandidateConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean("consumer")); } @Test void invalidAnnotationTwoTypes() { this.contextRunner.withUserConfiguration(OnBeanSingleCandidateTwoTypesConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); + assertThat(context).getFailure() + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); }); } @@ -130,19 +136,21 @@ class ConditionalOnSingleCandidateTests { void invalidAnnotationNoType() { this.contextRunner.withUserConfiguration(OnBeanSingleCandidateNoTypeConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().hasCauseInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); + assertThat(context).getFailure() + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); }); } @Test void singleCandidateMultipleCandidatesInContextHierarchy() { this.contextRunner.withUserConfiguration(AlphaPrimaryConfiguration.class, BravoConfiguration.class) - .run((parent) -> this.contextRunner.withUserConfiguration(OnBeanSingleCandidateConfiguration.class) - .withParent(parent).run((child) -> { - assertThat(child).hasBean("consumer"); - assertThat(child.getBean("consumer")).isEqualTo("alpha"); - })); + .run((parent) -> this.contextRunner.withUserConfiguration(OnBeanSingleCandidateConfiguration.class) + .withParent(parent) + .run((child) -> { + assertThat(child).hasBean("consumer"); + assertThat(child.getBean("consumer")).isEqualTo("alpha"); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java index 91eaea7734..c3507f9bcf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnWarDeploymentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -38,14 +38,14 @@ class ConditionalOnWarDeploymentTests { void nonWebApplicationShouldNotMatch() { ApplicationContextRunner contextRunner = new ApplicationContextRunner(); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("forWar")); + .run((context) -> assertThat(context).doesNotHaveBean("forWar")); } @Test void reactiveWebApplicationShouldNotMatch() { ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner(); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("forWar")); + .run((context) -> assertThat(context).doesNotHaveBean("forWar")); } @Test @@ -53,7 +53,7 @@ class ConditionalOnWarDeploymentTests { WebApplicationContextRunner contextRunner = new WebApplicationContextRunner( AnnotationConfigServletWebApplicationContext::new); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean("forWar")); + .run((context) -> assertThat(context).doesNotHaveBean("forWar")); } @Test @@ -62,7 +62,7 @@ class ConditionalOnWarDeploymentTests { // SpringBootServletInitializer does for WAR deployments. WebApplicationContextRunner contextRunner = new WebApplicationContextRunner(); contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasBean("forWar")); + .run((context) -> assertThat(context).hasBean("forWar")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java index 608a2160cd..e023523508 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,14 +42,14 @@ class OnBeanConditionTypeDeductionFailureTests { @Test void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> new AnnotationConfigApplicationContext(ImportingConfiguration.class).close()) - .satisfies((ex) -> { - Throwable beanTypeDeductionException = findNestedCause(ex, BeanTypeDeductionException.class); - assertThat(beanTypeDeductionException).hasMessage("Failed to deduce bean type for " - + OnMissingBeanConfiguration.class.getName() + ".objectMapper"); - assertThat(findNestedCause(beanTypeDeductionException, NoClassDefFoundError.class)).isNotNull(); - - }); + .isThrownBy(() -> new AnnotationConfigApplicationContext(ImportingConfiguration.class).close()) + .satisfies((ex) -> { + Throwable beanTypeDeductionException = findNestedCause(ex, BeanTypeDeductionException.class); + assertThat(beanTypeDeductionException).hasMessage("Failed to deduce bean type for " + + OnMissingBeanConfiguration.class.getName() + ".objectMapper"); + assertThat(findNestedCause(beanTypeDeductionException, NoClassDefFoundError.class)).isNotNull(); + + }); } private Throwable findNestedCause(Throwable ex, Class target) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java index d1f359ea60..3fc9951c17 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnClassConditionAutoConfigurationImportFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class OnClassConditionAutoConfigurationImportFilterTests { @Test void shouldBeRegistered() { assertThat(SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, null)) - .hasAtLeastOneElementOfType(OnClassCondition.class); + .hasAtLeastOneElementOfType(OnClassCondition.class); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java index 9185e2137a..507ec4c3ff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnPropertyListConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class OnPropertyListConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfig.class); + .withUserConfiguration(TestConfig.class); @Test void propertyNotDefined() { @@ -43,25 +43,25 @@ class OnPropertyListConditionTests { @Test void propertyDefinedAsCommaSeparated() { this.contextRunner.withPropertyValues("spring.test.my-list=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void propertyDefinedAsList() { this.contextRunner.withPropertyValues("spring.test.my-list[0]=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void propertyDefinedAsCommaSeparatedRelaxed() { this.contextRunner.withPropertyValues("spring.test.myList=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void propertyDefinedAsListRelaxed() { this.contextRunner.withPropertyValues("spring.test.myList[0]=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java index 7be194374f..845f6d0b34 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -38,13 +38,13 @@ class SpringBootConditionTests { @Test void sensibleClassException() { assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnClass.class)) - .withMessageContaining("Error processing condition on " + ErrorOnClass.class.getName()); + .withMessageContaining("Error processing condition on " + ErrorOnClass.class.getName()); } @Test void sensibleMethodException() { assertThatIllegalStateException().isThrownBy(() -> new AnnotationConfigApplicationContext(ErrorOnMethod.class)) - .withMessageContaining("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); + .withMessageContaining("Error processing condition on " + ErrorOnMethod.class.getName() + ".myBean"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java index c252a31fdd..ea6ee78b08 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/LifecycleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class LifecycleAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LifecycleAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LifecycleAutoConfiguration.class)); @Test void lifecycleProcessorIsConfiguredWithDefaultTimeout() { @@ -58,12 +58,13 @@ class LifecycleAutoConfigurationTests { @Test void lifecycleProcessorIsConfiguredWithCustomTimeoutInAChildContext() { new ApplicationContextRunner().run((parent) -> { - this.contextRunner.withParent(parent).withPropertyValues("spring.lifecycle.timeout-per-shutdown-phase=15s") - .run((child) -> { - assertThat(child).hasBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); - Object processor = child.getBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); - assertThat(processor).extracting("timeoutPerShutdownPhase").isEqualTo(15000L); - }); + this.contextRunner.withParent(parent) + .withPropertyValues("spring.lifecycle.timeout-per-shutdown-phase=15s") + .run((child) -> { + assertThat(child).hasBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); + Object processor = child.getBean(AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME); + assertThat(processor).extracting("timeoutPerShutdownPhase").isEqualTo(15000L); + }); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java index eea8ea84c4..313624d877 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,12 +44,12 @@ import static org.assertj.core.api.Assertions.assertThat; class MessageSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MessageSourceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MessageSourceAutoConfiguration.class)); @Test void testDefaultMessageSource() { this.contextRunner.run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("Foo message")); + .isEqualTo("Foo message")); } @Test @@ -71,22 +71,22 @@ class MessageSourceAutoConfigurationTests { @Test void testEncodingWorks() { this.contextRunner.withPropertyValues("spring.messages.basename:test/swedish") - .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("Some text with some swedish öäå!")); + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) + .isEqualTo("Some text with some swedish öäå!")); } @Test void testCacheDurationNoUnit() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=10") - .run(assertCache(10 * 1000)); + .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=10") + .run(assertCache(10 * 1000)); } @Test void testCacheDurationWithUnit() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=1m") - .run(assertCache(60 * 1000)); + .withPropertyValues("spring.messages.basename:test/messages", "spring.messages.cache-duration=1m") + .run(assertCache(60 * 1000)); } private ContextConsumer assertCache(long expected) { @@ -99,86 +99,85 @@ class MessageSourceAutoConfigurationTests { @Test void testMultipleMessageSourceCreated() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages,test/messages2") - .run((context) -> { - assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); - assertThat(context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)).isEqualTo("bar-bar"); - }); + .run((context) -> { + assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"); + assertThat(context.getMessage("foo-foo", null, "Foo-Foo message", Locale.UK)).isEqualTo("bar-bar"); + }); } @Test @Disabled("Expected to fail per gh-1075") void testMessageSourceFromPropertySourceAnnotation() { - this.contextRunner.withUserConfiguration(Config.class).run( - (context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar")); + this.contextRunner.withUserConfiguration(Config.class) + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar")); } @Test void testFallbackDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("fallbackToSystemLocale", true)); + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("fallbackToSystemLocale", true)); } @Test void testFallbackTurnOff() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.fallback-to-system-locale:false") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("fallbackToSystemLocale", false)); + .withPropertyValues("spring.messages.basename:test/messages", + "spring.messages.fallback-to-system-locale:false") + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("fallbackToSystemLocale", false)); } @Test void testFormatMessageDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", false)); + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", false)); } @Test void testFormatMessageOn() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.always-use-message-format:true") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", true)); + .withPropertyValues("spring.messages.basename:test/messages", + "spring.messages.always-use-message-format:true") + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", true)); } @Test void testUseCodeAsDefaultMessageDefault() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", false)); + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", false)); } @Test void testUseCodeAsDefaultMessageOn() { this.contextRunner - .withPropertyValues("spring.messages.basename:test/messages", - "spring.messages.use-code-as-default-message:true") - .run((context) -> assertThat(context.getBean(MessageSource.class)) - .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", true)); + .withPropertyValues("spring.messages.basename:test/messages", + "spring.messages.use-code-as-default-message:true") + .run((context) -> assertThat(context.getBean(MessageSource.class)) + .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", true)); } @Test void existingMessageSourceIsPreferred() { this.contextRunner.withUserConfiguration(CustomMessageSourceConfiguration.class) - .run((context) -> assertThat(context.getMessage("foo", null, null, null)).isEqualTo("foo")); + .run((context) -> assertThat(context.getMessage("foo", null, null, null)).isEqualTo("foo")); } @Test void existingMessageSourceInParentIsIgnored() { this.contextRunner.run((parent) -> this.contextRunner.withParent(parent) - .withPropertyValues("spring.messages.basename:test/messages") - .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)) - .isEqualTo("bar"))); + .withPropertyValues("spring.messages.basename:test/messages") + .run((context) -> assertThat(context.getMessage("foo", null, "Foo message", Locale.UK)).isEqualTo("bar"))); } @Test void messageSourceWithNonStandardBeanNameIsIgnored() { this.contextRunner.withPropertyValues("spring.messages.basename:test/messages") - .withUserConfiguration(CustomBeanNameMessageSourceConfiguration.class) - .run((context) -> assertThat(context.getMessage("foo", null, Locale.US)).isEqualTo("bar")); + .withUserConfiguration(CustomBeanNameMessageSourceConfiguration.class) + .run((context) -> assertThat(context.getMessage("foo", null, Locale.US)).isEqualTo("bar")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java index 139a14fd3e..a8a7122f48 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,51 +43,56 @@ class PropertyPlaceholderAutoConfigurationTests { @Test void whenTheAutoConfigurationIsNotUsedThenBeanDefinitionPlaceholdersAreNotResolved() { - this.contextRunner.withPropertyValues("fruit:banana").withInitializer(this::definePlaceholderBean) - .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("${fruit:apple}")); + this.contextRunner.withPropertyValues("fruit:banana") + .withInitializer(this::definePlaceholderBean) + .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("${fruit:apple}")); } @Test void whenTheAutoConfigurationIsUsedThenBeanDefinitionPlaceholdersAreResolved() { - this.contextRunner.withPropertyValues("fruit:banana").withInitializer(this::definePlaceholderBean) - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("banana")); + this.contextRunner.withPropertyValues("fruit:banana") + .withInitializer(this::definePlaceholderBean) + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("banana")); } @Test void whenTheAutoConfigurationIsNotUsedThenValuePlaceholdersAreResolved() { - this.contextRunner.withPropertyValues("fruit:banana").withUserConfiguration(PlaceholderConfig.class) - .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); + this.contextRunner.withPropertyValues("fruit:banana") + .withUserConfiguration(PlaceholderConfig.class) + .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); } @Test void whenTheAutoConfigurationIsUsedThenValuePlaceholdersAreResolved() { this.contextRunner.withPropertyValues("fruit:banana") - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(PlaceholderConfig.class) - .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(PlaceholderConfig.class) + .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("banana")); } @Test void whenThereIsAUserDefinedPropertySourcesPlaceholderConfigurerThenItIsUsedForBeanDefinitionPlaceholderResolution() { - this.contextRunner.withPropertyValues("fruit:banana").withInitializer(this::definePlaceholderBean) - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(PlaceholdersOverride.class) - .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("orange")); + this.contextRunner.withPropertyValues("fruit:banana") + .withInitializer(this::definePlaceholderBean) + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(PlaceholdersOverride.class) + .run((context) -> assertThat(context.getBean(PlaceholderBean.class).fruit).isEqualTo("orange")); } @Test void whenThereIsAUserDefinedPropertySourcesPlaceholderConfigurerThenItIsUsedForValuePlaceholderResolution() { this.contextRunner.withPropertyValues("fruit:banana") - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(PlaceholderConfig.class, PlaceholdersOverride.class) - .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("orange")); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(PlaceholderConfig.class, PlaceholdersOverride.class) + .run((context) -> assertThat(context.getBean(PlaceholderConfig.class).fruit).isEqualTo("orange")); } private void definePlaceholderBean(ConfigurableApplicationContext context) { ((BeanDefinitionRegistry) context.getBeanFactory()).registerBeanDefinition("placeholderBean", - BeanDefinitionBuilder.rootBeanDefinition(PlaceholderBean.class).addConstructorArgValue("${fruit:apple}") - .getBeanDefinition()); + BeanDefinitionBuilder.rootBeanDefinition(PlaceholderBean.class) + .addConstructorArgValue("${fruit:apple}") + .getBeanDefinition()); } @Configuration(proxyBeanMethods = false) @@ -115,7 +120,7 @@ class PropertyPlaceholderAutoConfigurationTests { static PropertySourcesPlaceholderConfigurer morePlaceholders() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); configurer - .setProperties(StringUtils.splitArrayElementsIntoProperties(new String[] { "fruit=orange" }, "=")); + .setProperties(StringUtils.splitArrayElementsIntoProperties(new String[] { "fruit=orange" }, "=")); configurer.setLocalOverride(true); configurer.setOrder(0); return configurer; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java index 9fc637c2d4..82ef9350db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -51,14 +51,16 @@ class CouchbaseAutoConfigurationIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withCredentials("spring", "password").withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME).withPrimaryIndex(false)); + .withCredentials("spring", "password") + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME).withPrimaryIndex(false)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)) - .withPropertyValues("spring.couchbase.connection-string: " + couchbase.getConnectionString(), - "spring.couchbase.username:spring", "spring.couchbase.password:password", - "spring.couchbase.bucket.name:" + BUCKET_NAME); + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)) + .withPropertyValues("spring.couchbase.connection-string: " + couchbase.getConnectionString(), + "spring.couchbase.username:spring", "spring.couchbase.password:password", + "spring.couchbase.bucket.name:" + BUCKET_NAME); @Test void defaultConfiguration() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java index 5a420e604c..2edf5a8341 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/couchbase/CouchbaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -52,52 +52,57 @@ import static org.mockito.Mockito.mock; class CouchbaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class)); @Test void connectionStringIsRequired() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ClusterEnvironment.class) - .doesNotHaveBean(Cluster.class)); + .doesNotHaveBean(Cluster.class)); } @Test void connectionStringCreateEnvironmentAndCluster() { this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withPropertyValues("spring.couchbase.connection-string=localhost").run((context) -> { - assertThat(context).hasSingleBean(ClusterEnvironment.class).hasSingleBean(Cluster.class); - assertThat(context.getBean(Cluster.class)) - .isSameAs(context.getBean(CouchbaseTestConfiguration.class).couchbaseCluster()); - }); + .withPropertyValues("spring.couchbase.connection-string=localhost") + .run((context) -> { + assertThat(context).hasSingleBean(ClusterEnvironment.class).hasSingleBean(Cluster.class); + assertThat(context.getBean(Cluster.class)) + .isSameAs(context.getBean(CouchbaseTestConfiguration.class).couchbaseCluster()); + }); } @Test void whenObjectMapperBeanIsDefinedThenClusterEnvironmentObjectMapperIsDerivedFromIt() { this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withPropertyValues("spring.couchbase.connection-string=localhost").run((context) -> { - ClusterEnvironment env = context.getBean(ClusterEnvironment.class); - Set expectedModuleIds = new HashSet<>( - context.getBean(ObjectMapper.class).getRegisteredModuleIds()); - expectedModuleIds.add(new JsonValueModule().getTypeId()); - JsonSerializer serializer = env.jsonSerializer(); - assertThat(serializer).extracting("wrapped").isInstanceOf(JacksonJsonSerializer.class) - .extracting("mapper", as(InstanceOfAssertFactories.type(ObjectMapper.class))) - .extracting(ObjectMapper::getRegisteredModuleIds).isEqualTo(expectedModuleIds); - }); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) + .withPropertyValues("spring.couchbase.connection-string=localhost") + .run((context) -> { + ClusterEnvironment env = context.getBean(ClusterEnvironment.class); + Set expectedModuleIds = new HashSet<>( + context.getBean(ObjectMapper.class).getRegisteredModuleIds()); + expectedModuleIds.add(new JsonValueModule().getTypeId()); + JsonSerializer serializer = env.jsonSerializer(); + assertThat(serializer).extracting("wrapped") + .isInstanceOf(JacksonJsonSerializer.class) + .extracting("mapper", as(InstanceOfAssertFactories.type(ObjectMapper.class))) + .extracting(ObjectMapper::getRegisteredModuleIds) + .isEqualTo(expectedModuleIds); + }); } @Test void customizeJsonSerializer() { JsonSerializer customJsonSerializer = mock(JsonSerializer.class); this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withBean(ClusterEnvironmentBuilderCustomizer.class, - () -> (builder) -> builder.jsonSerializer(customJsonSerializer)) - .withPropertyValues("spring.couchbase.connection-string=localhost").run((context) -> { - ClusterEnvironment env = context.getBean(ClusterEnvironment.class); - JsonSerializer serializer = env.jsonSerializer(); - assertThat(serializer).extracting("wrapped").isSameAs(customJsonSerializer); - }); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) + .withBean(ClusterEnvironmentBuilderCustomizer.class, + () -> (builder) -> builder.jsonSerializer(customJsonSerializer)) + .withPropertyValues("spring.couchbase.connection-string=localhost") + .run((context) -> { + ClusterEnvironment env = context.getBean(ClusterEnvironment.class); + JsonSerializer serializer = env.jsonSerializer(); + assertThat(serializer).extracting("wrapped").isSameAs(customJsonSerializer); + }); } @Test @@ -152,23 +157,23 @@ class CouchbaseAutoConfigurationTests { private void testClusterEnvironment(Consumer environmentConsumer, String... environment) { this.contextRunner.withUserConfiguration(CouchbaseTestConfiguration.class) - .withPropertyValues("spring.couchbase.connection-string=localhost").withPropertyValues(environment) - .run((context) -> environmentConsumer.accept(context.getBean(ClusterEnvironment.class))); + .withPropertyValues("spring.couchbase.connection-string=localhost") + .withPropertyValues(environment) + .run((context) -> environmentConsumer.accept(context.getBean(ClusterEnvironment.class))); } @Test void customizeEnvWithCustomCouchbaseConfiguration() { this.contextRunner - .withUserConfiguration(CouchbaseTestConfiguration.class, - ClusterEnvironmentCustomizerConfiguration.class) - .withPropertyValues("spring.couchbase.connection-string=localhost", - "spring.couchbase.env.timeouts.connect=100") - .run((context) -> { - assertThat(context).hasSingleBean(ClusterEnvironment.class); - ClusterEnvironment env = context.getBean(ClusterEnvironment.class); - assertThat(env.timeoutConfig().kvTimeout()).isEqualTo(Duration.ofSeconds(5)); - assertThat(env.timeoutConfig().connectTimeout()).isEqualTo(Duration.ofSeconds(2)); - }); + .withUserConfiguration(CouchbaseTestConfiguration.class, ClusterEnvironmentCustomizerConfiguration.class) + .withPropertyValues("spring.couchbase.connection-string=localhost", + "spring.couchbase.env.timeouts.connect=100") + .run((context) -> { + assertThat(context).hasSingleBean(ClusterEnvironment.class); + ClusterEnvironment env = context.getBean(ClusterEnvironment.class); + assertThat(env.timeoutConfig().kvTimeout()).isEqualTo(Duration.ofSeconds(5)); + assertThat(env.timeoutConfig().connectTimeout()).isEqualTo(Duration.ofSeconds(2)); + }); } @Configuration(proxyBeanMethods = false) @@ -176,8 +181,9 @@ class CouchbaseAutoConfigurationTests { @Bean ClusterEnvironmentBuilderCustomizer clusterEnvironmentBuilderCustomizer() { - return (builder) -> builder.timeoutConfig().kvTimeout(Duration.ofSeconds(5)) - .connectTimeout(Duration.ofSeconds(2)); + return (builder) -> builder.timeoutConfig() + .kvTimeout(Duration.ofSeconds(5)) + .connectTimeout(Duration.ofSeconds(2)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java index 68ce64aa3e..5b0b9663e0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { void exceptionTranslationPostProcessorUsesCglibByDefault() { this.context = new AnnotationConfigApplicationContext(PersistenceExceptionTranslationAutoConfiguration.class); Map beans = this.context - .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); + .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).hasSize(1); assertThat(beans.values().iterator().next().isProxyTargetClass()).isTrue(); } @@ -70,7 +70,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context - .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); + .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).hasSize(1); assertThat(beans.values().iterator().next().isProxyTargetClass()).isFalse(); } @@ -82,7 +82,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { this.context.register(PersistenceExceptionTranslationAutoConfiguration.class); this.context.refresh(); Map beans = this.context - .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); + .getBeansOfType(PersistenceExceptionTranslationPostProcessor.class); assertThat(beans).isEmpty(); } @@ -99,7 +99,7 @@ class PersistenceExceptionTranslationAutoConfigurationTests { HibernateJpaAutoConfiguration.class, TestConfiguration.class, PersistenceExceptionTranslationAutoConfiguration.class); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) - .isThrownBy(() -> this.context.getBean(TestRepository.class).doSomething()); + .isThrownBy(() -> this.context.getBean(TestRepository.class).doSomething()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java index 5f6c4b5c65..3de73b9cd9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/ConditionalOnRepositoryTypeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,76 +35,76 @@ class ConditionalOnRepositoryTypeTests { @Test void imperativeRepositoryMatchesWithNoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test void reactiveRepositoryMatchesWithNoConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test void imperativeRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:auto") - .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:auto") + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test void reactiveRepositoryMatchesWithAutoConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:auto") - .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:auto") + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test void imperativeRepositoryMatchesWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:imperative") - .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:imperative") + .run((context) -> assertThat(context).hasSingleBean(ImperativeRepository.class)); } @Test void reactiveRepositoryMatchesWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:reactive") - .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:reactive") + .run((context) -> assertThat(context).hasSingleBean(ReactiveRepository.class)); } @Test void imperativeRepositoryDoesNotMatchWithReactiveConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:reactive") - .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:reactive") + .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test void reactiveRepositoryDoesNotMatchWithImperativeConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test void imperativeRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ImperativeRepository.class) - .withPropertyValues("spring.data.test.repositories.type:none") - .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:none") + .run((context) -> assertThat(context).doesNotHaveBean(ImperativeRepository.class)); } @Test void reactiveRepositoryDoesNotMatchWithNoneConfiguredType() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); + .withPropertyValues("spring.data.test.repositories.type:none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveRepository.class)); } @Test void failsFastWhenConfiguredTypeIsUnknown() { this.contextRunner.withUserConfiguration(ReactiveRepository.class) - .withPropertyValues("spring.data.test.repositories.type:abcde") - .run((context) -> assertThat(context).hasFailed()); + .withPropertyValues("spring.data.test.repositories.type:abcde") + .run((context) -> assertThat(context).hasFailed()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java index 51ffd85d4b..aacd79fe8d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,27 +49,27 @@ class CassandraDataAutoConfigurationIntegrationTests { static final CassandraContainer cassandra = new CassandraContainer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class)) - .withPropertyValues( - "spring.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), - "spring.cassandra.local-datacenter=datacenter1", "spring.cassandra.connection.connect-timeout=60s", - "spring.cassandra.connection.init-query-timeout=60s", "spring.cassandra.request.timeout=60s") - .withInitializer((context) -> AutoConfigurationPackages.register((BeanDefinitionRegistry) context, - City.class.getPackage().getName())); + .withConfiguration( + AutoConfigurations.of(CassandraAutoConfiguration.class, CassandraDataAutoConfiguration.class)) + .withPropertyValues( + "spring.cassandra.contact-points:" + cassandra.getHost() + ":" + cassandra.getFirstMappedPort(), + "spring.cassandra.local-datacenter=datacenter1", "spring.cassandra.connection.connect-timeout=60s", + "spring.cassandra.connection.init-query-timeout=60s", "spring.cassandra.request.timeout=60s") + .withInitializer((context) -> AutoConfigurationPackages.register((BeanDefinitionRegistry) context, + City.class.getPackage().getName())); @Test void hasDefaultSchemaActionSet() { this.contextRunner.run((context) -> assertThat(context.getBean(SessionFactoryFactoryBean.class)) - .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.NONE)); + .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.NONE)); } @Test void hasRecreateSchemaActionSet() { this.contextRunner.withUserConfiguration(KeyspaceTestConfiguration.class) - .withPropertyValues("spring.cassandra.schemaAction=recreate_drop_unused") - .run((context) -> assertThat(context.getBean(SessionFactoryFactoryBean.class)) - .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.RECREATE_DROP_UNUSED)); + .withPropertyValues("spring.cassandra.schemaAction=recreate_drop_unused") + .run((context) -> assertThat(context.getBean(SessionFactoryFactoryBean.class)) + .hasFieldOrPropertyWithValue("schemaAction", SchemaAction.RECREATE_DROP_UNUSED)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java index b5ab262e38..932ba62caf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -85,7 +85,7 @@ class CassandraDataAutoConfigurationTests { load(); CassandraConverter cassandraConverter = this.context.getBean(CassandraConverter.class); assertThat(cassandraConverter.getCodecRegistry()) - .isSameAs(this.context.getBean(CassandraMockConfiguration.class).codecRegistry); + .isSameAs(this.context.getBean(CassandraMockConfiguration.class).codecRegistry); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java index 159309d6bf..2dbf1495d0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -81,15 +81,15 @@ class CassandraReactiveRepositoriesAutoConfigurationTests { @Test void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.cassandra.repositories.type=imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.cassandra.repositories.type=imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.cassandra.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.cassandra.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } private ManagedTypes getManagedTypes(ApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java index 5190db7e02..7e6294e6df 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,15 +79,15 @@ class CassandraRepositoriesAutoConfigurationTests { @Test void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.cassandra.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); + .withPropertyValues("spring.cassandra.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); } @Test void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.cassandra.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); + .withPropertyValues("spring.cassandra.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(CityCassandraRepository.class)); } private ManagedTypes getManagedTypes(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java index 20deec96d9..73eae165ca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,8 +51,8 @@ import static org.assertj.core.api.Assertions.assertThat; class CouchbaseDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class, - CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class)); @Test void disabledIfCouchbaseIsNotConfigured() { @@ -76,16 +76,16 @@ class CouchbaseDataAutoConfigurationTests { @Test void typeKeyDefault() { this.contextRunner.withUserConfiguration(CouchbaseMockConfiguration.class) - .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) - .isEqualTo(DefaultCouchbaseTypeMapper.DEFAULT_TYPE_KEY)); + .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) + .isEqualTo(DefaultCouchbaseTypeMapper.DEFAULT_TYPE_KEY)); } @Test void typeKeyCanBeCustomized() { this.contextRunner.withUserConfiguration(CouchbaseMockConfiguration.class) - .withPropertyValues("spring.data.couchbase.type-key=_custom") - .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) - .isEqualTo("_custom")); + .withPropertyValues("spring.data.couchbase.type-key=_custom") + .run((context) -> assertThat(context.getBean(MappingCouchbaseConverter.class).getTypeKey()) + .isEqualTo("_custom")); } @Test @@ -94,7 +94,7 @@ class CouchbaseDataAutoConfigurationTests { CouchbaseTemplate template = context.getBean(CouchbaseTemplate.class); assertThat( template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) - .isTrue(); + .isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java index da133f28b3..23fa8b4c2e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,9 +47,9 @@ class CouchbaseReactiveAndImperativeRepositoriesAutoConfigurationTests { @Test void shouldCreateInstancesForReactiveAndImperativeRepositories() { new ApplicationContextRunner() - .withUserConfiguration(ImperativeAndReactiveConfiguration.class, BaseConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityRepository.class) - .hasSingleBean(ReactiveCityRepository.class)); + .withUserConfiguration(ImperativeAndReactiveConfiguration.class, BaseConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class) + .hasSingleBean(ReactiveCityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java index 22a9d0fc7c..29ed72063d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,9 +49,9 @@ import static org.assertj.core.api.Assertions.assertThat; */ class CouchbaseReactiveDataAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class, CouchbaseAutoConfiguration.class, + CouchbaseDataAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class)); @Test void disabledIfCouchbaseIsNotConfigured() { @@ -78,7 +78,7 @@ class CouchbaseReactiveDataAutoConfigurationTests { ReactiveCouchbaseTemplate template = context.getBean(ReactiveCouchbaseTemplate.class); assertThat( template.getConverter().getConversionService().canConvert(CouchbaseProperties.class, Boolean.class)) - .isTrue(); + .isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java index a3c287054f..b5a13de1bb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,10 +41,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ class CouchbaseReactiveRepositoriesAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, - CouchbaseRepositoriesAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class, - CouchbaseReactiveRepositoriesAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, + CouchbaseRepositoriesAutoConfiguration.class, CouchbaseReactiveDataAutoConfiguration.class, + CouchbaseReactiveRepositoriesAutoConfiguration.class)); @Test void couchbaseNotAvailable() { @@ -54,33 +54,33 @@ class CouchbaseReactiveRepositoriesAutoConfigurationTests { @Test void defaultRepository() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); } @Test void imperativeRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void disabledRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void noRepositoryAvailable() { this.contextRunner.withUserConfiguration(NoRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityCouchbaseRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityCouchbaseRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java index 3ebe6a94e1..a5ec5c152d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/couchbase/CouchbaseRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; class CouchbaseRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class, - CouchbaseDataAutoConfiguration.class, CouchbaseRepositoriesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CouchbaseAutoConfiguration.class, CouchbaseDataAutoConfiguration.class, + CouchbaseRepositoriesAutoConfiguration.class)); @Test void couchbaseNotAvailable() { @@ -50,27 +50,27 @@ class CouchbaseRepositoriesAutoConfigurationTests { @Test void defaultRepository() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); } @Test void reactiveRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void disabledRepositories() { this.contextRunner.withUserConfiguration(DefaultConfiguration.class) - .withPropertyValues("spring.data.couchbase.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.couchbase.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void noRepositoryAvailable() { this.contextRunner.withUserConfiguration(NoRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java index 8636229c7e..6b1aeb91a7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,15 +55,17 @@ import static org.mockito.Mockito.mock; class ElasticsearchDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, - ElasticsearchClientAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, - ReactiveElasticsearchClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, + ElasticsearchClientAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, + ReactiveElasticsearchClientAutoConfiguration.class)); @Test void defaultRestBeansRegistered() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ElasticsearchTemplate.class) - .hasSingleBean(ReactiveElasticsearchTemplate.class).hasSingleBean(ElasticsearchConverter.class) - .hasSingleBean(ElasticsearchConverter.class).hasSingleBean(ElasticsearchCustomConversions.class)); + .hasSingleBean(ReactiveElasticsearchTemplate.class) + .hasSingleBean(ElasticsearchConverter.class) + .hasSingleBean(ElasticsearchConverter.class) + .hasSingleBean(ElasticsearchCustomConversions.class)); } @Test @@ -71,8 +73,8 @@ class ElasticsearchDataAutoConfigurationTests { this.contextRunner.run((context) -> { SimpleElasticsearchMappingContext mappingContext = context.getBean(SimpleElasticsearchMappingContext.class); assertThat(mappingContext) - .extracting("simpleTypeHolder", InstanceOfAssertFactories.type(SimpleTypeHolder.class)).satisfies( - (simpleTypeHolder) -> assertThat(simpleTypeHolder.isSimpleType(BigDecimal.class)).isTrue()); + .extracting("simpleTypeHolder", InstanceOfAssertFactories.type(SimpleTypeHolder.class)) + .satisfies((simpleTypeHolder) -> assertThat(simpleTypeHolder.isSimpleType(BigDecimal.class)).isTrue()); }); } @@ -80,22 +82,26 @@ class ElasticsearchDataAutoConfigurationTests { void customConversionsShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomElasticsearchCustomConversions.class).run((context) -> { assertThat(context).hasSingleBean(ElasticsearchCustomConversions.class).hasBean("testCustomConversions"); - assertThat(context.getBean(ElasticsearchConverter.class).getConversionService() - .canConvert(ElasticsearchTemplate.class, Boolean.class)).isTrue(); + assertThat(context.getBean(ElasticsearchConverter.class) + .getConversionService() + .canConvert(ElasticsearchTemplate.class, Boolean.class)).isTrue(); }); } @Test void customRestTemplateShouldBeUsed() { - this.contextRunner.withUserConfiguration(CustomRestTemplate.class).run((context) -> assertThat(context) - .getBeanNames(ElasticsearchTemplate.class).hasSize(1).contains("elasticsearchTemplate")); + this.contextRunner.withUserConfiguration(CustomRestTemplate.class) + .run((context) -> assertThat(context).getBeanNames(ElasticsearchTemplate.class) + .hasSize(1) + .contains("elasticsearchTemplate")); } @Test void customReactiveRestTemplateShouldBeUsed() { this.contextRunner.withUserConfiguration(CustomReactiveElasticsearchTemplate.class) - .run((context) -> assertThat(context).getBeanNames(ReactiveElasticsearchTemplate.class).hasSize(1) - .contains("reactiveElasticsearchTemplate")); + .run((context) -> assertThat(context).getBeanNames(ReactiveElasticsearchTemplate.class) + .hasSize(1) + .contains("reactiveElasticsearchTemplate")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java index 8b5f407388..d26f3f9b30 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,30 +51,32 @@ class ElasticsearchRepositoriesAutoConfigurationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, - ElasticsearchClientAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class, - ElasticsearchDataAutoConfiguration.class)) - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress()); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class, + ElasticsearchClientAutoConfiguration.class, ElasticsearchRepositoriesAutoConfiguration.class, + ElasticsearchDataAutoConfiguration.class)) + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress()); @Test void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(CityRepository.class).hasSingleBean(ElasticsearchTemplate.class)); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class) + .hasSingleBean(ElasticsearchTemplate.class)); } @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ElasticsearchTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ElasticsearchTemplate.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityElasticsearchDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityElasticsearchDbRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java index 0aaa0c562f..c31cf4a7cb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/elasticsearch/ReactiveElasticsearchRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,34 +54,36 @@ class ReactiveElasticsearchRepositoriesAutoConfigurationTests { @Container static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchClientAutoConfiguration.class, - ElasticsearchRestClientAutoConfiguration.class, - ReactiveElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, - ReactiveElasticsearchClientAutoConfiguration.class)) - .withPropertyValues( - "spring.elasticsearch.uris=" + elasticsearch.getHost() + ":" + elasticsearch.getFirstMappedPort(), - "spring.elasticsearch.socket-timeout=30s") - .withInitializer(ConditionEvaluationReportLoggingListener.forLogLevel(LogLevel.INFO)); + .withConfiguration(AutoConfigurations.of(ElasticsearchClientAutoConfiguration.class, + ElasticsearchRestClientAutoConfiguration.class, + ReactiveElasticsearchRepositoriesAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class, + ReactiveElasticsearchClientAutoConfiguration.class)) + .withPropertyValues( + "spring.elasticsearch.uris=" + elasticsearch.getHost() + ":" + elasticsearch.getFirstMappedPort(), + "spring.elasticsearch.socket-timeout=30s") + .withInitializer(ConditionEvaluationReportLoggingListener.forLogLevel(LogLevel.INFO)); @Test void testDefaultRepositoryConfiguration() { - this.contextRunner.withUserConfiguration(TestConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ReactiveCityRepository.class).hasSingleBean(ReactiveElasticsearchTemplate.class)); + this.contextRunner.withUserConfiguration(TestConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class) + .hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchTemplate.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityReactiveElasticsearchDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityReactiveElasticsearchDbRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java index 45ea35ea7b..0ed97c82ab 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jdbc/JdbcRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,12 +62,12 @@ import static org.mockito.Mockito.mock; class JdbcRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JdbcRepositoriesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JdbcRepositoriesAutoConfiguration.class)); @Test void backsOffWithNoDataSource() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class)); } @Test @@ -81,60 +81,64 @@ class JdbcRepositoriesAutoConfigurationTests { @Test void backsOffWithNoTransactionManager() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); - assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); + assertThat(context).doesNotHaveBean(AbstractJdbcConfiguration.class); + }); } @Test void basicAutoConfiguration() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); - assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); + assertThat(context).hasSingleBean(CityRepository.class); + assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); + }); } @Test void entityScanShouldSetManagedTypes() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - JdbcMappingContext mappingContext = context.getBean(JdbcMappingContext.class); - ManagedTypes managedTypes = (ManagedTypes) ReflectionTestUtils.getField(mappingContext, - "managedTypes"); - assertThat(managedTypes.toList()).containsOnly(City.class); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + JdbcMappingContext mappingContext = context.getBean(JdbcMappingContext.class); + ManagedTypes managedTypes = (ManagedTypes) ReflectionTestUtils.getField(mappingContext, "managedTypes"); + assertThat(managedTypes.toList()).containsOnly(City.class); + }); } @Test void autoConfigurationWithNoRepositories() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(EmptyConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); - assertThat(context).doesNotHaveBean(Repository.class); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(EmptyConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); + assertThat(context).doesNotHaveBean(Repository.class); + }); } @Test void honoursUsersEnableJdbcRepositoriesConfiguration() { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(EnableRepositoriesConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); - assertThat(context).hasSingleBean(CityRepository.class); - assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(EnableRepositoriesConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(AbstractJdbcConfiguration.class); + assertThat(context).hasSingleBean(CityRepository.class); + assertThat(context.getBean(CityRepository.class).findById(2000L)).isPresent(); + }); } @Test @@ -179,21 +183,21 @@ class JdbcRepositoriesAutoConfigurationTests { private void allowsUserToDefineCustomBean(Class configuration, Class beanType, String beanName) { this.contextRunner.with(database()) - .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(configuration, EmptyConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(beanType); - assertThat(context).hasBean(beanName); - }); + .withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(configuration, EmptyConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(beanType); + assertThat(context).hasBean(beanName); + }); } private Function database() { return (runner) -> runner - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - SqlInitializationAutoConfiguration.class)) - .withPropertyValues("spring.sql.init.schema-locations=classpath:data-city-schema.sql", - "spring.sql.init.data-locations=classpath:city.sql", - "spring.datasource.generate-unique-name:true"); + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, SqlInitializationAutoConfiguration.class)) + .withPropertyValues("spring.sql.init.schema-locations=classpath:data-city-schema.sql", + "spring.sql.init.data-locations=classpath:city.sql", "spring.datasource.generate-unique-name:true"); } @TestAutoConfigurationPackage(City.class) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java index 204e003ea6..a9336e3942 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/AbstractJpaRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,9 +57,9 @@ import static org.assertj.core.api.Assertions.assertThat; abstract class AbstractJpaRepositoriesAutoConfigurationTests { final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class); + .withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class, + JpaRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)) + .withUserConfiguration(EmbeddedDataSourceConfiguration.class); @Test void testDefaultRepositoryConfiguration() { @@ -83,56 +83,59 @@ abstract class AbstractJpaRepositoriesAutoConfigurationTests { @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void whenBootstrapModeIsLazyWithMultipleAsyncExecutorBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) - .isEqualTo(context.getBean("applicationTaskExecutor"))); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("applicationTaskExecutor"))); } @Test void whenBootstrapModeIsLazyWithSingleAsyncExecutorBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(SingleAsyncTaskExecutorConfiguration.class) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) - .isEqualTo(context.getBean("testAsyncTaskExecutor"))); + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=lazy") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("testAsyncTaskExecutor"))); } @Test void whenBootstrapModeIsDeferredBootstrapExecutorIsConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=deferred") - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) - .isEqualTo(context.getBean("applicationTaskExecutor"))); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=deferred") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isEqualTo(context.getBean("applicationTaskExecutor"))); } @Test void whenBootstrapModeIsDefaultBootstrapExecutorIsNotConfigured() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=default").run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()).isNull()); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .withPropertyValues("spring.data.jpa.repositories.bootstrap-mode=default") + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isNull()); } @Test void bootstrapModeIsDefaultByDefault() { this.contextRunner.withUserConfiguration(MultipleAsyncTaskExecutorConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class, - TaskSchedulingAutoConfiguration.class)) - .run((context) -> assertThat( - context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()).isNull()); + .withConfiguration( + AutoConfigurations.of(TaskExecutionAutoConfiguration.class, TaskSchedulingAutoConfiguration.class)) + .run((context) -> assertThat( + context.getBean(LocalContainerEntityManagerFactoryBean.class).getBootstrapExecutor()) + .isNull()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java index 9e965bcac0..e49594c6a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/EnversRevisionRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -33,7 +33,7 @@ class EnversRevisionRepositoriesAutoConfigurationTests extends AbstractJpaReposi @Test void autoConfigurationShouldSucceedWithRevisionRepository() { this.contextRunner.withUserConfiguration(RevisionRepositoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CountryRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CountryRepository.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java index 4efde42ec5..b84ea525a0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class JpaRepositoriesAutoConfigurationTests extends AbstractJpaRepositoriesAutoC @Test void autoConfigurationShouldFailWithRevisionRepository() { this.contextRunner.withUserConfiguration(RevisionRepositoryConfiguration.class) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java index 8aa4b6e8a6..cc5acd7c24 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/jpa/JpaWebAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -45,10 +45,9 @@ import static org.assertj.core.api.Assertions.assertThat; class JpaWebAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - JpaRepositoriesAutoConfiguration.class, SpringDataWebAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, + JpaRepositoriesAutoConfiguration.class, SpringDataWebAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void springDataWebIsConfiguredWithJpaRepositories() { @@ -57,7 +56,7 @@ class JpaWebAutoConfigurationTests { assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class); assertThat(context).hasSingleBean(SortHandlerMethodArgumentResolver.class); assertThat(context.getBean(FormattingConversionService.class).canConvert(String.class, Distance.class)) - .isTrue(); + .isTrue(); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java index fcb96868ee..4f0b12e0b1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,8 +62,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + MongoAutoConfiguration.class, MongoDataAutoConfiguration.class)); @Test void templateExists() { @@ -94,7 +94,7 @@ class MongoDataAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomConversionsConfig.class).run((context) -> { MongoTemplate template = context.getBean(MongoTemplate.class); assertThat(template.getConverter().getConversionService().canConvert(MongoClient.class, Boolean.class)) - .isTrue(); + .isTrue(); }); } @@ -125,15 +125,15 @@ class MongoDataAutoConfigurationTests { @Test void customFieldNamingStrategy() { - this.contextRunner.withPropertyValues( - "spring.data.mongodb.field-naming-strategy:" + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) - .run((context) -> { - MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); - FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils - .getField(mappingContext, "fieldNamingStrategy"); - assertThat(fieldNamingStrategy.getClass()) - .isEqualTo(CamelCaseAbbreviatingFieldNamingStrategy.class); - }); + this.contextRunner + .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + + CamelCaseAbbreviatingFieldNamingStrategy.class.getName()) + .run((context) -> { + MongoMappingContext mappingContext = context.getBean(MongoMappingContext.class); + FieldNamingStrategy fieldNamingStrategy = (FieldNamingStrategy) ReflectionTestUtils + .getField(mappingContext, "fieldNamingStrategy"); + assertThat(fieldNamingStrategy.getClass()).isEqualTo(CamelCaseAbbreviatingFieldNamingStrategy.class); + }); } @Test @@ -155,8 +155,8 @@ class MongoDataAutoConfigurationTests { @Test void interfaceFieldNamingStrategy() { this.contextRunner - .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + FieldNamingStrategy.class.getName()) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .withPropertyValues("spring.data.mongodb.field-naming-strategy:" + FieldNamingStrategy.class.getName()) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test @@ -183,7 +183,7 @@ class MongoDataAutoConfigurationTests { @Test void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoDataAutoConfiguration.class)); runner.run((context) -> assertThat(context).doesNotHaveBean(MongoTemplate.class)); } @@ -206,7 +206,7 @@ class MongoDataAutoConfigurationTests { @Test void autoConfiguresIfUserProvidesMongoDatabaseFactoryButNoClient() { this.contextRunner.withUserConfiguration(MongoDatabaseFactoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoTemplate.class)); } private static void assertDomainTypesDiscovered(MongoMappingContext mappingContext, Class... types) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java index 3f7e29890e..993aa22ac0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoReactiveDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); @Test void templateExists() { @@ -55,7 +55,7 @@ class MongoReactiveDataAutoConfigurationTests { @Test void whenGridFsDatabaseIsConfiguredThenGridFsTemplateUsesIt() { this.contextRunner.withPropertyValues("spring.data.mongodb.gridfs.database:grid") - .run((context) -> assertThat(grisFsTemplateDatabaseName(context)).isEqualTo("grid")); + .run((context) -> assertThat(grisFsTemplateDatabaseName(context)).isEqualTo("grid")); } @Test @@ -70,7 +70,7 @@ class MongoReactiveDataAutoConfigurationTests { @Test void backsOffIfMongoClientBeanIsNotPresent() { ApplicationContextRunner runner = new ApplicationContextRunner().withConfiguration(AutoConfigurations - .of(PropertyPlaceholderAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); + .of(PropertyPlaceholderAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class)); runner.run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveDataAutoConfiguration.class)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java index f4dbc80ef5..b22d30dd29 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,9 +48,9 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, - MongoReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, + MongoReactiveRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test void testDefaultRepositoryConfiguration() { @@ -66,33 +66,33 @@ class MongoReactiveRepositoriesAutoConfigurationTests { @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityMongoDbRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityMongoDbRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void enablingImperativeRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=imperative") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=imperative") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Test void enablingNoRepositoriesDisablesReactiveRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveCityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java index 33fd80382c..76e51aaed3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/mongo/MongoRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,8 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - MongoRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + MongoRepositoriesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class)); @Test void testDefaultRepositoryConfiguration() { @@ -62,33 +62,33 @@ class MongoRepositoriesAutoConfigurationTests { @Test void testNoRepositoryConfiguration() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test void doesNotTriggerDefaultRepositoryDetectionIfCustomized() { this.contextRunner.withUserConfiguration(CustomizedConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityMongoDbRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityMongoDbRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void enablingReactiveRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Test void enablingNoRepositoriesDisablesImperativeRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.mongodb.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); + .withPropertyValues("spring.data.mongodb.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java index 5e8fbbc845..2b3aeb38d4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,8 @@ import static org.mockito.Mockito.mock; class Neo4jDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class)); @Test void shouldProvideConversions() { @@ -70,7 +70,7 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); assertThat(context.getBean(DatabaseSelectionProvider.class)) - .isSameAs(DatabaseSelectionProvider.getDefaultSelectionProvider()); + .isSameAs(DatabaseSelectionProvider.getDefaultSelectionProvider()); }); } @@ -79,18 +79,19 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.data.neo4j.database=test").run((context) -> { assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); assertThat(context.getBean(DatabaseSelectionProvider.class).getDatabaseSelection()) - .isEqualTo(DatabaseSelection.byName("test")); + .isEqualTo(DatabaseSelection.byName("test")); }); } @Test void shouldReuseExistingDatabaseNameProvider() { this.contextRunner.withPropertyValues("spring.data.neo4j.database=ignored") - .withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); - assertThat(context.getBean(DatabaseSelectionProvider.class).getDatabaseSelection()) - .isEqualTo(DatabaseSelection.byName("custom")); - }); + .withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(DatabaseSelectionProvider.class); + assertThat(context.getBean(DatabaseSelectionProvider.class).getDatabaseSelection()) + .isEqualTo(DatabaseSelection.byName("custom")); + }); } @Test @@ -103,26 +104,26 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Neo4jClient.class); assertThat(context.getBean(Neo4jClient.class)).extracting("databaseSelectionProvider") - .isSameAs(context.getBean(DatabaseSelectionProvider.class)); + .isSameAs(context.getBean(DatabaseSelectionProvider.class)); }); } @Test void shouldReuseExistingNeo4jClient() { this.contextRunner.withUserConfiguration(Neo4jClientConfig.class) - .run((context) -> assertThat(context).hasSingleBean(Neo4jClient.class).hasBean("myCustomClient")); + .run((context) -> assertThat(context).hasSingleBean(Neo4jClient.class).hasBean("myCustomClient")); } @Test void shouldProvideNeo4jTemplate() { this.contextRunner.withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Neo4jTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(Neo4jTemplate.class)); } @Test void shouldReuseExistingNeo4jTemplate() { - this.contextRunner.withBean("myCustomOperations", Neo4jOperations.class, () -> mock(Neo4jOperations.class)).run( - (context) -> assertThat(context).hasSingleBean(Neo4jOperations.class).hasBean("myCustomOperations")); + this.contextRunner.withBean("myCustomOperations", Neo4jOperations.class, () -> mock(Neo4jOperations.class)) + .run((context) -> assertThat(context).hasSingleBean(Neo4jOperations.class).hasBean("myCustomOperations")); } @Test @@ -130,24 +131,24 @@ class Neo4jDataAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomDatabaseSelectionProviderConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Neo4jTransactionManager.class); assertThat(context.getBean(Neo4jTransactionManager.class)).extracting("databaseSelectionProvider") - .isSameAs(context.getBean(DatabaseSelectionProvider.class)); + .isSameAs(context.getBean(DatabaseSelectionProvider.class)); }); } @Test void shouldBackoffIfReactiveTransactionManagerIsSet() { this.contextRunner.withBean(ReactiveTransactionManager.class, () -> mock(ReactiveTransactionManager.class)) - .run((context) -> assertThat(context).doesNotHaveBean(Neo4jTransactionManager.class) - .hasSingleBean(TransactionManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(Neo4jTransactionManager.class) + .hasSingleBean(TransactionManager.class)); } @Test void shouldReuseExistingTransactionManager() { this.contextRunner - .withBean("myCustomTransactionManager", PlatformTransactionManager.class, - () -> mock(PlatformTransactionManager.class)) - .run((context) -> assertThat(context).hasSingleBean(PlatformTransactionManager.class) - .hasBean("myCustomTransactionManager")); + .withBean("myCustomTransactionManager", PlatformTransactionManager.class, + () -> mock(PlatformTransactionManager.class)) + .run((context) -> assertThat(context).hasSingleBean(PlatformTransactionManager.class) + .hasBean("myCustomTransactionManager")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java index c0d9891ff4..60c316c31c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -52,16 +52,16 @@ import static org.mockito.Mockito.mock; class Neo4jReactiveDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class, - Neo4jReactiveDataAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jDataAutoConfiguration.class, + Neo4jReactiveDataAutoConfiguration.class)); @Test void shouldProvideDefaultDatabaseNameProvider() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); assertThat(context.getBean(ReactiveDatabaseSelectionProvider.class)) - .isSameAs(ReactiveDatabaseSelectionProvider.getDefaultSelectionProvider()); + .isSameAs(ReactiveDatabaseSelectionProvider.getDefaultSelectionProvider()); }); } @@ -70,21 +70,22 @@ class Neo4jReactiveDataAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.data.neo4j.database=test").run((context) -> { assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); StepVerifier.create(context.getBean(ReactiveDatabaseSelectionProvider.class).getDatabaseSelection()) - .consumeNextWith((databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("test")) - .expectComplete(); + .consumeNextWith((databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("test")) + .expectComplete(); }); } @Test void shouldReuseExistingDatabaseNameProvider() { this.contextRunner.withPropertyValues("spring.data.neo4j.database=ignored") - .withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); - StepVerifier.create(context.getBean(ReactiveDatabaseSelectionProvider.class).getDatabaseSelection()) - .consumeNextWith( - (databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("custom")) - .expectComplete(); - }); + .withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveDatabaseSelectionProvider.class); + StepVerifier.create(context.getBean(ReactiveDatabaseSelectionProvider.class).getDatabaseSelection()) + .consumeNextWith( + (databaseSelection) -> assertThat(databaseSelection.getValue()).isEqualTo("custom")) + .expectComplete(); + }); } @Test @@ -95,41 +96,42 @@ class Neo4jReactiveDataAutoConfigurationTests { @Test void shouldProvideReactiveNeo4jClientWithCustomDatabaseSelectionProvider() { this.contextRunner.withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveNeo4jClient.class); - assertThat(context.getBean(ReactiveNeo4jClient.class)).extracting("databaseSelectionProvider") - .isSameAs(context.getBean(ReactiveDatabaseSelectionProvider.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveNeo4jClient.class); + assertThat(context.getBean(ReactiveNeo4jClient.class)).extracting("databaseSelectionProvider") + .isSameAs(context.getBean(ReactiveDatabaseSelectionProvider.class)); + }); } @Test void shouldReuseExistingReactiveNeo4jClient() { - this.contextRunner.withUserConfiguration(ReactiveNeo4jClientConfig.class).run((context) -> assertThat(context) - .hasSingleBean(ReactiveNeo4jClient.class).hasBean("myCustomReactiveClient")); + this.contextRunner.withUserConfiguration(ReactiveNeo4jClientConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jClient.class) + .hasBean("myCustomReactiveClient")); } @Test void shouldProvideReactiveNeo4jTemplate() { this.contextRunner.withUserConfiguration(CustomReactiveDatabaseSelectionProviderConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class)); } @Test void shouldReuseExistingReactiveNeo4jTemplate() { this.contextRunner - .withBean("myCustomReactiveOperations", ReactiveNeo4jOperations.class, - () -> mock(ReactiveNeo4jOperations.class)) - .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jOperations.class) - .hasBean("myCustomReactiveOperations")); + .withBean("myCustomReactiveOperations", ReactiveNeo4jOperations.class, + () -> mock(ReactiveNeo4jOperations.class)) + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jOperations.class) + .hasBean("myCustomReactiveOperations")); } @Test void shouldUseExistingReactiveTransactionManager() { this.contextRunner - .withBean("myCustomReactiveTransactionManager", ReactiveTransactionManager.class, - () -> mock(ReactiveTransactionManager.class)) - .run((context) -> assertThat(context).hasSingleBean(ReactiveTransactionManager.class) - .hasSingleBean(TransactionManager.class)); + .withBean("myCustomReactiveTransactionManager", ReactiveTransactionManager.class, + () -> mock(ReactiveTransactionManager.class)) + .run((context) -> assertThat(context).hasSingleBean(ReactiveTransactionManager.class) + .hasSingleBean(TransactionManager.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java index c78b4a1426..3946180313 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jReactiveRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,45 +43,47 @@ import static org.assertj.core.api.Assertions.assertThat; class Neo4jReactiveRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class) - .withConfiguration(AutoConfigurations.of(Neo4jDataAutoConfiguration.class, - Neo4jReactiveDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class, - Neo4jReactiveRepositoriesAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, Neo4jReactiveDataAutoConfiguration.class, + Neo4jRepositoriesAutoConfiguration.class, Neo4jReactiveRepositoriesAutoConfiguration.class)); @Test void configurationWithDefaultRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveCityRepository.class)); } @Test void configurationWithNoRepositories() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(ReactiveNeo4jTemplate.class).doesNotHaveBean(ReactiveNeo4jRepository.class)); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class) + .doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void configurationWithDisabledRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.neo4j.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveNeo4jRepository.class)); + .withPropertyValues("spring.data.neo4j.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class) - .doesNotHaveBean(ReactiveNeo4jRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveNeo4jTemplate.class) + .doesNotHaveBean(ReactiveNeo4jRepository.class)); } @Test void shouldRespectAtEnableReactiveNeo4jRepositories() { this.contextRunner - .withUserConfiguration(SortOfInvalidCustomConfiguration.class, WithCustomReactiveRepositoryScan.class) - .withPropertyValues("spring.data.neo4j.repositories.type=reactive") - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) - .doesNotHaveBean(ReactiveCityRepository.class).doesNotHaveBean(CountryRepository.class) - .hasSingleBean(ReactiveCountryRepository.class)); + .withUserConfiguration(SortOfInvalidCustomConfiguration.class, WithCustomReactiveRepositoryScan.class) + .withPropertyValues("spring.data.neo4j.repositories.type=reactive") + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) + .doesNotHaveBean(ReactiveCityRepository.class) + .doesNotHaveBean(CountryRepository.class) + .hasSingleBean(ReactiveCountryRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java index 75fd6d9260..d9a007bbf4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationIntegrationTests.java @@ -47,7 +47,8 @@ class Neo4jRepositoriesAutoConfigurationIntegrationTests { @Container private static final Neo4jContainer neo4jServer = new Neo4jContainer<>(DockerImageNames.neo4j()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java index a057635750..7b187ff14e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/neo4j/Neo4jRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,41 +50,44 @@ import static org.mockito.Mockito.mock; class Neo4jRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(MockedDriverConfiguration.class).withConfiguration( - AutoConfigurations.of(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class)); + .withUserConfiguration(MockedDriverConfiguration.class) + .withConfiguration( + AutoConfigurations.of(Neo4jDataAutoConfiguration.class, Neo4jRepositoriesAutoConfiguration.class)); @Test void configurationWithDefaultRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(CityRepository.class)); } @Test void configurationWithNoRepositories() { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(Neo4jTransactionManager.class).doesNotHaveBean(Neo4jRepository.class)); + this.contextRunner.withUserConfiguration(EmptyConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(Neo4jTransactionManager.class) + .doesNotHaveBean(Neo4jRepository.class)); } @Test void configurationWithDisabledRepositories() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.data.neo4j.repositories.type=none") - .run((context) -> assertThat(context).doesNotHaveBean(Neo4jRepository.class)); + .withPropertyValues("spring.data.neo4j.repositories.type=none") + .run((context) -> assertThat(context).doesNotHaveBean(Neo4jRepository.class)); } @Test void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(Neo4jTransactionManager.class) - .doesNotHaveBean(Neo4jRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(Neo4jTransactionManager.class) + .doesNotHaveBean(Neo4jRepository.class)); } @Test void shouldRespectAtEnableNeo4jRepositories() { this.contextRunner.withUserConfiguration(SortOfInvalidCustomConfiguration.class, WithCustomRepositoryScan.class) - .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) - .doesNotHaveBean(ReactiveCityRepository.class).hasSingleBean(CountryRepository.class) - .doesNotHaveBean(ReactiveCountryRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CityRepository.class) + .doesNotHaveBean(ReactiveCityRepository.class) + .hasSingleBean(CountryRepository.class) + .doesNotHaveBean(ReactiveCountryRepository.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java index 4e0e8d61ea..aec99ba3c9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcDataAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcDataAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)); @Test void r2dbcEntityTemplateIsConfigured() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java index 99e372dc80..05e25361de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/r2dbc/R2dbcRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -49,55 +49,62 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcRepositoriesAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcRepositoriesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcRepositoriesAutoConfiguration.class)); @Test void backsOffWithNoConnectionFactory() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class)); + .run((context) -> assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class)); } @Test void backsOffWithNoDatabaseClientOperations() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader("org.springframework.r2dbc")) - .withUserConfiguration(TestConfiguration.class).run((context) -> { - assertThat(context).doesNotHaveBean(DatabaseClient.class); - assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class); - }); + .withClassLoader(new FilteredClassLoader("org.springframework.r2dbc")) + .withUserConfiguration(TestConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(DatabaseClient.class); + assertThat(context).doesNotHaveBean(R2dbcRepositoryConfigurationExtension.class); + }); } @Test void basicAutoConfiguration() { this.contextRunner - .withConfiguration( - AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) - .withUserConfiguration(DatabaseInitializationConfiguration.class, TestConfiguration.class) - .withPropertyValues("spring.r2dbc.generate-unique-name:true").run((context) -> { - assertThat(context).hasSingleBean(CityRepository.class); - context.getBean(CityRepository.class).findById(2000L).as(StepVerifier::create).expectNextCount(1) - .verifyComplete(); - }); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) + .withUserConfiguration(DatabaseInitializationConfiguration.class, TestConfiguration.class) + .withPropertyValues("spring.r2dbc.generate-unique-name:true") + .run((context) -> { + assertThat(context).hasSingleBean(CityRepository.class); + context.getBean(CityRepository.class) + .findById(2000L) + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); + }); } @Test void autoConfigurationWithNoRepositories() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(EmptyConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(Repository.class)); + .withUserConfiguration(EmptyConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(Repository.class)); } @Test void honorsUsersEnableR2dbcRepositoriesConfiguration() { this.contextRunner - .withConfiguration( - AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) - .withUserConfiguration(DatabaseInitializationConfiguration.class, EnableRepositoriesConfiguration.class) - .withPropertyValues("spring.r2dbc.generate-unique-name:true").run((context) -> { - assertThat(context).hasSingleBean(CityRepository.class); - context.getBean(CityRepository.class).findById(2000L).as(StepVerifier::create).expectNextCount(1) - .verifyComplete(); - }); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class, R2dbcDataAutoConfiguration.class)) + .withUserConfiguration(DatabaseInitializationConfiguration.class, EnableRepositoriesConfiguration.class) + .withPropertyValues("spring.r2dbc.generate-unique-name:true") + .run((context) -> { + assertThat(context).hasSingleBean(CityRepository.class); + context.getBean(CityRepository.class) + .findById(2000L) + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java index f6a35df38d..2ac757cbe6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java @@ -44,31 +44,31 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisAutoConfigurationJedisTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test void connectionFactoryDefaultsToJedis() { this.contextRunner.run((context) -> assertThat(context.getBean("redisConnectionFactory")) - .isInstanceOf(JedisConnectionFactory.class)); + .isInstanceOf(JedisConnectionFactory.class)); } @Test void connectionFactoryIsNotCreatedWhenLettuceIsSelected() { this.contextRunner.withPropertyValues("spring.data.redis.client-type=lettuce") - .run((context) -> assertThat(context).doesNotHaveBean(RedisConnectionFactory.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RedisConnectionFactory.class)); } @Test void testOverrideRedisConfiguration() { this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.database:1") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getDatabase()).isOne(); - assertThat(getUserName(cf)).isNull(); - assertThat(cf.getPassword()).isNull(); - assertThat(cf.isUseSsl()).isFalse(); - }); + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getDatabase()).isOne(); + assertThat(getUserName(cf)).isNull(); + assertThat(cf.getPassword()).isNull(); + assertThat(cf.isUseSsl()).isFalse(); + }); } @Test @@ -81,29 +81,32 @@ class RedisAutoConfigurationJedisTests { @Test void testRedisUrlConfiguration() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", - "spring.data.redis.url:redis://user:password@example:33").run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isFalse(); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.url:redis://user:password@example:33") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isFalse(); + }); } @Test void testOverrideUrlRedisConfiguration() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.password:xyz", - "spring.data.redis.port:1000", "spring.data.redis.ssl:false", - "spring.data.redis.url:rediss://user:password@example:33").run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isTrue(); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.password:xyz", + "spring.data.redis.port:1000", "spring.data.redis.ssl:false", + "spring.data.redis.url:rediss://user:password@example:33") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test @@ -120,51 +123,55 @@ class RedisAutoConfigurationJedisTests { @Test void testPasswordInUrlStartsWithColon() { this.contextRunner.withPropertyValues("spring.data.redis.url:redis://user::pass:word@example:33") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo(":pass:word"); - }); + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo(":pass:word"); + }); } @Test void testRedisConfigurationWithPool() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.jedis.pool.min-idle:1", - "spring.data.redis.jedis.pool.max-idle:4", "spring.data.redis.jedis.pool.max-active:16", - "spring.data.redis.jedis.pool.max-wait:2000", - "spring.data.redis.jedis.pool.time-between-eviction-runs:30000").run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getPoolConfig().getMinIdle()).isOne(); - assertThat(cf.getPoolConfig().getMaxIdle()).isEqualTo(4); - assertThat(cf.getPoolConfig().getMaxTotal()).isEqualTo(16); - assertThat(cf.getPoolConfig().getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); - assertThat(cf.getPoolConfig().getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.jedis.pool.min-idle:1", + "spring.data.redis.jedis.pool.max-idle:4", "spring.data.redis.jedis.pool.max-active:16", + "spring.data.redis.jedis.pool.max-wait:2000", + "spring.data.redis.jedis.pool.time-between-eviction-runs:30000") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getPoolConfig().getMinIdle()).isOne(); + assertThat(cf.getPoolConfig().getMaxIdle()).isEqualTo(4); + assertThat(cf.getPoolConfig().getMaxTotal()).isEqualTo(16); + assertThat(cf.getPoolConfig().getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); + assertThat(cf.getPoolConfig().getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); + }); } @Test void testRedisConfigurationDisabledPool() { this.contextRunner - .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.jedis.pool.enabled:false") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientConfiguration().isUsePooling()).isFalse(); - }); + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.jedis.pool.enabled:false") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientConfiguration().isUsePooling()).isFalse(); + }); } @Test void testRedisConfigurationWithTimeoutAndConnectTimeout() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.timeout:250", - "spring.data.redis.connect-timeout:1000").run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getTimeout()).isEqualTo(250); - assertThat(cf.getClientConfiguration().getConnectTimeout().toMillis()).isEqualTo(1000); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.timeout:250", + "spring.data.redis.connect-timeout:1000") + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getTimeout()).isEqualTo(250); + assertThat(cf.getClientConfiguration().getConnectTimeout().toMillis()).isEqualTo(1000); + }); } @Test @@ -180,42 +187,43 @@ class RedisAutoConfigurationJedisTests { @Test void testRedisConfigurationWithClientName() { this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.client-name:spring-boot") - .run((context) -> { - JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientName()).isEqualTo("spring-boot"); - }); + .run((context) -> { + JedisConnectionFactory cf = context.getBean(JedisConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientName()).isEqualTo("spring-boot"); + }); } @Test void testRedisConfigurationWithSentinel() { this.contextRunner - .withPropertyValues("spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") - .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) - .run((context) -> assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()) - .isTrue()); + .withPropertyValues("spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") + .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) + .run((context) -> assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()) + .isTrue()); } @Test void testRedisConfigurationWithSentinelAndAuthentication() { this.contextRunner - .withPropertyValues("spring.data.redis.username=user", "spring.data.redis.password=password", - "spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") - .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class).run((context) -> { - assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); - assertThat(getUserName(JedisConnectionFactoryCaptor.connectionFactory)).isEqualTo("user"); - assertThat(JedisConnectionFactoryCaptor.connectionFactory.getPassword()).isEqualTo("password"); - }); + .withPropertyValues("spring.data.redis.username=user", "spring.data.redis.password=password", + "spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:127.0.0.1:26379,127.0.0.1:26380") + .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) + .run((context) -> { + assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisSentinelAware()).isTrue(); + assertThat(getUserName(JedisConnectionFactoryCaptor.connectionFactory)).isEqualTo("user"); + assertThat(JedisConnectionFactoryCaptor.connectionFactory.getPassword()).isEqualTo("password"); + }); } @Test void testRedisConfigurationWithCluster() { this.contextRunner.withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380") - .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) - .run((context) -> assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisClusterAware()) - .isTrue()); + .withUserConfiguration(JedisConnectionFactoryCaptorConfiguration.class) + .run((context) -> assertThat(JedisConnectionFactoryCaptor.connectionFactory.isRedisClusterAware()) + .isTrue()); } private String getUserName(JedisConnectionFactory factory) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java index 8ab420980b..1114cf7c9a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationLettuceWithoutCommonsPool2Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class RedisAutoConfigurationLettuceWithoutCommonsPool2Tests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test void poolWithoutCommonsPool2IsDisabledByDefault() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java index 6d4f5811ad..e1ffb9baaa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationTests.java @@ -75,7 +75,7 @@ import static org.mockito.Mockito.mock; class RedisAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)); @Test void testDefaultRedisConfiguration() { @@ -89,26 +89,28 @@ class RedisAutoConfigurationTests { @Test void testOverrideRedisConfiguration() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.database:1", - "spring.data.redis.lettuce.shutdown-timeout:500").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getDatabase()).isOne(); - assertThat(getUserName(cf)).isNull(); - assertThat(cf.getPassword()).isNull(); - assertThat(cf.isUseSsl()).isFalse(); - assertThat(cf.getShutdownTimeout()).isEqualTo(500); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.database:1", + "spring.data.redis.lettuce.shutdown-timeout:500") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getDatabase()).isOne(); + assertThat(getUserName(cf)).isNull(); + assertThat(cf.getPassword()).isNull(); + assertThat(cf.isUseSsl()).isFalse(); + assertThat(cf.getShutdownTimeout()).isEqualTo(500); + }); } @Test void testCustomizeClientResources() { Tracing tracing = mock(Tracing.class); this.contextRunner.withBean(ClientResourcesBuilderCustomizer.class, () -> (builder) -> builder.tracing(tracing)) - .run((context) -> { - DefaultClientResources clientResources = context.getBean(DefaultClientResources.class); - assertThat(clientResources.tracing()).isEqualTo(tracing); - }); + .run((context) -> { + DefaultClientResources clientResources = context.getBean(DefaultClientResources.class); + assertThat(clientResources.tracing()).isEqualTo(tracing); + }); } @Test @@ -121,29 +123,32 @@ class RedisAutoConfigurationTests { @Test void testRedisUrlConfiguration() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", - "spring.data.redis.url:redis://user:password@example:33").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isFalse(); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.url:redis://user:password@example:33") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isFalse(); + }); } @Test void testOverrideUrlRedisConfiguration() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.password:xyz", - "spring.data.redis.port:1000", "spring.data.redis.ssl:false", - "spring.data.redis.url:rediss://user:password@example:33").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo("password"); - assertThat(cf.isUseSsl()).isTrue(); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.password:xyz", + "spring.data.redis.port:1000", "spring.data.redis.ssl:false", + "spring.data.redis.url:rediss://user:password@example:33") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo("password"); + assertThat(cf.isUseSsl()).isTrue(); + }); } @Test @@ -160,13 +165,13 @@ class RedisAutoConfigurationTests { @Test void testPasswordInUrlStartsWithColon() { this.contextRunner.withPropertyValues("spring.data.redis.url:redis://user::pass:word@example:33") - .run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("example"); - assertThat(cf.getPort()).isEqualTo(33); - assertThat(getUserName(cf)).isEqualTo("user"); - assertThat(cf.getPassword()).isEqualTo(":pass:word"); - }); + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("example"); + assertThat(cf.getPort()).isEqualTo(33); + assertThat(getUserName(cf)).isEqualTo("user"); + assertThat(cf.getPassword()).isEqualTo(":pass:word"); + }); } @Test @@ -185,44 +190,52 @@ class RedisAutoConfigurationTests { @Test void testRedisConfigurationWithCustomPoolSettings() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.lettuce.pool.min-idle:1", - "spring.data.redis.lettuce.pool.max-idle:4", "spring.data.redis.lettuce.pool.max-active:16", - "spring.data.redis.lettuce.pool.max-wait:2000", - "spring.data.redis.lettuce.pool.time-between-eviction-runs:30000", - "spring.data.redis.lettuce.shutdown-timeout:1000").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - GenericObjectPoolConfig poolConfig = getPoolingClientConfiguration(cf).getPoolConfig(); - assertThat(poolConfig.getMinIdle()).isOne(); - assertThat(poolConfig.getMaxIdle()).isEqualTo(4); - assertThat(poolConfig.getMaxTotal()).isEqualTo(16); - assertThat(poolConfig.getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); - assertThat(poolConfig.getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); - assertThat(cf.getShutdownTimeout()).isEqualTo(1000); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.lettuce.pool.min-idle:1", + "spring.data.redis.lettuce.pool.max-idle:4", "spring.data.redis.lettuce.pool.max-active:16", + "spring.data.redis.lettuce.pool.max-wait:2000", + "spring.data.redis.lettuce.pool.time-between-eviction-runs:30000", + "spring.data.redis.lettuce.shutdown-timeout:1000") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + GenericObjectPoolConfig poolConfig = getPoolingClientConfiguration(cf).getPoolConfig(); + assertThat(poolConfig.getMinIdle()).isOne(); + assertThat(poolConfig.getMaxIdle()).isEqualTo(4); + assertThat(poolConfig.getMaxTotal()).isEqualTo(16); + assertThat(poolConfig.getMaxWaitDuration()).isEqualTo(Duration.ofSeconds(2)); + assertThat(poolConfig.getDurationBetweenEvictionRuns()).isEqualTo(Duration.ofSeconds(30)); + assertThat(cf.getShutdownTimeout()).isEqualTo(1000); + }); } @Test void testRedisConfigurationDisabledPool() { this.contextRunner - .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.lettuce.pool.enabled:false") - .run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientConfiguration()).isNotInstanceOf(LettucePoolingClientConfiguration.class); - }); + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.lettuce.pool.enabled:false") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientConfiguration()).isNotInstanceOf(LettucePoolingClientConfiguration.class); + }); } @Test void testRedisConfigurationWithTimeoutAndConnectTimeout() { - this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.timeout:250", - "spring.data.redis.connect-timeout:1000").run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getTimeout()).isEqualTo(250); - assertThat(cf.getClientConfiguration().getClientOptions().get().getSocketOptions() - .getConnectTimeout().toMillis()).isEqualTo(1000); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.timeout:250", + "spring.data.redis.connect-timeout:1000") + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getTimeout()).isEqualTo(250); + assertThat(cf.getClientConfiguration() + .getClientOptions() + .get() + .getSocketOptions() + .getConnectTimeout() + .toMillis()).isEqualTo(1000); + }); } @Test @@ -231,8 +244,12 @@ class RedisAutoConfigurationTests { LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); assertThat(cf.getHostName()).isEqualTo("foo"); assertThat(cf.getTimeout()).isEqualTo(60000); - assertThat(cf.getClientConfiguration().getClientOptions().get().getSocketOptions().getConnectTimeout() - .toMillis()).isEqualTo(10000); + assertThat(cf.getClientConfiguration() + .getClientOptions() + .get() + .getSocketOptions() + .getConnectTimeout() + .toMillis()).isEqualTo(10000); }); } @@ -247,11 +264,11 @@ class RedisAutoConfigurationTests { @Test void testRedisConfigurationWithClientName() { this.contextRunner.withPropertyValues("spring.data.redis.host:foo", "spring.data.redis.client-name:spring-boot") - .run((context) -> { - LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); - assertThat(cf.getHostName()).isEqualTo("foo"); - assertThat(cf.getClientName()).isEqualTo("spring-boot"); - }); + .run((context) -> { + LettuceConnectionFactory cf = context.getBean(LettuceConnectionFactory.class); + assertThat(cf.getHostName()).isEqualTo("foo"); + assertThat(cf.getClientName()).isEqualTo("spring-boot"); + }); } @Test @@ -274,77 +291,77 @@ class RedisAutoConfigurationTests { void testRedisConfigurationWithSentinel() { List sentinels = Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380"); this.contextRunner - .withPropertyValues("spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) - .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) - .isTrue()); + .withPropertyValues("spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) + .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) + .isTrue()); } @Test void testRedisConfigurationWithIpv6Sentinel() { List sentinels = Arrays.asList("[0:0:0:0:0:0:0:1]:26379", "[0:0:0:0:0:0:0:1]:26380"); this.contextRunner - .withPropertyValues("spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) - .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) - .isTrue()); + .withPropertyValues("spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels)) + .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware()) + .isTrue()); } @Test void testRedisConfigurationWithSentinelAndDatabase() { this.contextRunner - .withPropertyValues("spring.data.redis.database:1", "spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run((context) -> { - LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); - assertThat(connectionFactory.getDatabase()).isOne(); - assertThat(connectionFactory.isRedisSentinelAware()).isTrue(); - }); + .withPropertyValues("spring.data.redis.database:1", "spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run((context) -> { + LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); + assertThat(connectionFactory.getDatabase()).isOne(); + assertThat(connectionFactory.isRedisSentinelAware()).isTrue(); + }); } @Test void testRedisConfigurationWithSentinelAndAuthentication() { this.contextRunner - .withPropertyValues("spring.data.redis.username=user", "spring.data.redis.password=password", - "spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run(assertSentinelConfiguration("user", "password", (sentinelConfiguration) -> { - assertThat(sentinelConfiguration.getSentinelPassword().isPresent()).isFalse(); - Set sentinels = sentinelConfiguration.getSentinels(); - assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) - .contains("127.0.0.1:26379", "127.0.0.1:26380"); - })); + .withPropertyValues("spring.data.redis.username=user", "spring.data.redis.password=password", + "spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run(assertSentinelConfiguration("user", "password", (sentinelConfiguration) -> { + assertThat(sentinelConfiguration.getSentinelPassword().isPresent()).isFalse(); + Set sentinels = sentinelConfiguration.getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); + })); } @Test void testRedisConfigurationWithSentinelPasswordAndDataNodePassword() { this.contextRunner - .withPropertyValues("spring.data.redis.password=password", "spring.data.redis.sentinel.password=secret", - "spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run(assertSentinelConfiguration(null, "password", (sentinelConfiguration) -> { - assertThat(sentinelConfiguration.getSentinelUsername()).isNull(); - assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); - Set sentinels = sentinelConfiguration.getSentinels(); - assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) - .contains("127.0.0.1:26379", "127.0.0.1:26380"); - })); + .withPropertyValues("spring.data.redis.password=password", "spring.data.redis.sentinel.password=secret", + "spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run(assertSentinelConfiguration(null, "password", (sentinelConfiguration) -> { + assertThat(sentinelConfiguration.getSentinelUsername()).isNull(); + assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); + Set sentinels = sentinelConfiguration.getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); + })); } @Test void testRedisConfigurationWithSentinelAuthenticationAndDataNodeAuthentication() { this.contextRunner - .withPropertyValues("spring.data.redis.username=username", "spring.data.redis.password=password", - "spring.data.redis.sentinel.username=sentinel", "spring.data.redis.sentinel.password=secret", - "spring.data.redis.sentinel.master:mymaster", - "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") - .run(assertSentinelConfiguration("username", "password", (sentinelConfiguration) -> { - assertThat(sentinelConfiguration.getSentinelUsername()).isEqualTo("sentinel"); - assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); - Set sentinels = sentinelConfiguration.getSentinels(); - assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) - .contains("127.0.0.1:26379", "127.0.0.1:26380"); - })); + .withPropertyValues("spring.data.redis.username=username", "spring.data.redis.password=password", + "spring.data.redis.sentinel.username=sentinel", "spring.data.redis.sentinel.password=secret", + "spring.data.redis.sentinel.master:mymaster", + "spring.data.redis.sentinel.nodes:127.0.0.1:26379, 127.0.0.1:26380") + .run(assertSentinelConfiguration("username", "password", (sentinelConfiguration) -> { + assertThat(sentinelConfiguration.getSentinelUsername()).isEqualTo("sentinel"); + assertThat(new String(sentinelConfiguration.getSentinelPassword().get())).isEqualTo("secret"); + Set sentinels = sentinelConfiguration.getSentinels(); + assertThat(sentinels.stream().map(Object::toString).collect(Collectors.toSet())) + .contains("127.0.0.1:26379", "127.0.0.1:26380"); + })); } private ContextConsumer assertSentinelConfiguration(String userName, String password, @@ -359,41 +376,48 @@ class RedisAutoConfigurationTests { @Test void testRedisSentinelUrlConfiguration() { - this.contextRunner.withPropertyValues( - "spring.data.redis.url=redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster") - .run((context) -> assertThatIllegalStateException() - .isThrownBy(() -> context.getBean(LettuceConnectionFactory.class)) - .withRootCauseInstanceOf(RedisUrlSyntaxException.class).havingRootCause().withMessageContaining( - "Invalid Redis URL 'redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster'")); + this.contextRunner + .withPropertyValues( + "spring.data.redis.url=redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster") + .run((context) -> assertThatIllegalStateException() + .isThrownBy(() -> context.getBean(LettuceConnectionFactory.class)) + .withRootCauseInstanceOf(RedisUrlSyntaxException.class) + .havingRootCause() + .withMessageContaining( + "Invalid Redis URL 'redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster'")); } @Test void testRedisConfigurationWithCluster() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); - this.contextRunner.withPropertyValues("spring.data.redis.cluster.nodes[0]:" + clusterNodes.get(0), - "spring.data.redis.cluster.nodes[1]:" + clusterNodes.get(1)).run((context) -> { - RedisClusterConfiguration clusterConfiguration = context.getBean(LettuceConnectionFactory.class) - .getClusterConfiguration(); - assertThat(clusterConfiguration.getClusterNodes()).hasSize(2); - assertThat(clusterConfiguration.getClusterNodes()) - .extracting((node) -> node.getHost() + ":" + node.getPort()) - .containsExactlyInAnyOrder("127.0.0.1:27379", "127.0.0.1:27380"); - }); + this.contextRunner + .withPropertyValues("spring.data.redis.cluster.nodes[0]:" + clusterNodes.get(0), + "spring.data.redis.cluster.nodes[1]:" + clusterNodes.get(1)) + .run((context) -> { + RedisClusterConfiguration clusterConfiguration = context.getBean(LettuceConnectionFactory.class) + .getClusterConfiguration(); + assertThat(clusterConfiguration.getClusterNodes()).hasSize(2); + assertThat(clusterConfiguration.getClusterNodes()) + .extracting((node) -> node.getHost() + ":" + node.getPort()) + .containsExactlyInAnyOrder("127.0.0.1:27379", "127.0.0.1:27380"); + }); } @Test void testRedisConfigurationWithClusterAndAuthentication() { List clusterNodes = Arrays.asList("127.0.0.1:27379", "127.0.0.1:27380"); - this.contextRunner.withPropertyValues("spring.data.redis.username=user", "spring.data.redis.password=password", - "spring.data.redis.cluster.nodes[0]:" + clusterNodes.get(0), - "spring.data.redis.cluster.nodes[1]:" + clusterNodes.get(1)).run((context) -> { - LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); - assertThat(getUserName(connectionFactory)).isEqualTo("user"); - assertThat(connectionFactory.getPassword()).isEqualTo("password"); - } + this.contextRunner + .withPropertyValues("spring.data.redis.username=user", "spring.data.redis.password=password", + "spring.data.redis.cluster.nodes[0]:" + clusterNodes.get(0), + "spring.data.redis.cluster.nodes[1]:" + clusterNodes.get(1)) + .run((context) -> { + LettuceConnectionFactory connectionFactory = context.getBean(LettuceConnectionFactory.class); + assertThat(getUserName(connectionFactory)).isEqualTo("user"); + assertThat(connectionFactory.getPassword()).isEqualTo("password"); + } - ); + ); } @Test @@ -407,73 +431,70 @@ class RedisAutoConfigurationTests { @Test void testRedisConfigurationWithClusterCreateClusterClientOptions() { this.contextRunner.withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380") - .run(assertClientOptions(ClusterClientOptions.class, (options) -> { - assertThat(options.getTimeoutOptions().isApplyConnectionTimeout()).isTrue(); - assertThat(options.getTimeoutOptions().isTimeoutCommands()).isTrue(); - })); + .run(assertClientOptions(ClusterClientOptions.class, (options) -> { + assertThat(options.getTimeoutOptions().isApplyConnectionTimeout()).isTrue(); + assertThat(options.getTimeoutOptions().isTimeoutCommands()).isTrue(); + })); } @Test void testRedisConfigurationWithClusterRefreshPeriod() { this.contextRunner - .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.data.redis.lettuce.cluster.refresh.period=30s") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().getRefreshPeriod()) - .hasSeconds(30))); + .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.data.redis.lettuce.cluster.refresh.period=30s") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().getRefreshPeriod()).hasSeconds(30))); } @Test void testRedisConfigurationWithClusterAdaptiveRefresh() { this.contextRunner - .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.data.redis.lettuce.cluster.refresh.adaptive=true") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().getAdaptiveRefreshTriggers()) - .isEqualTo(EnumSet.allOf(RefreshTrigger.class)))); + .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.data.redis.lettuce.cluster.refresh.adaptive=true") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().getAdaptiveRefreshTriggers()) + .isEqualTo(EnumSet.allOf(RefreshTrigger.class)))); } @Test void testRedisConfigurationWithClusterRefreshPeriodHasNoEffectWithNonClusteredConfiguration() { - this.contextRunner.withPropertyValues("spring.data.redis.cluster.refresh.period=30s").run(assertClientOptions( - ClientOptions.class, (options) -> assertThat(options.getClass()).isEqualTo(ClientOptions.class))); + this.contextRunner.withPropertyValues("spring.data.redis.cluster.refresh.period=30s") + .run(assertClientOptions(ClientOptions.class, + (options) -> assertThat(options.getClass()).isEqualTo(ClientOptions.class))); } @Test void testRedisConfigurationWithClusterDynamicRefreshSourcesEnabled() { this.contextRunner - .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.data.redis.lettuce.cluster.refresh.dynamic-refresh-sources=true") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()) - .isTrue())); + .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.data.redis.lettuce.cluster.refresh.dynamic-refresh-sources=true") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()).isTrue())); } @Test void testRedisConfigurationWithClusterDynamicRefreshSourcesDisabled() { this.contextRunner - .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.data.redis.lettuce.cluster.refresh.dynamic-refresh-sources=false") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()) - .isFalse())); + .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.data.redis.lettuce.cluster.refresh.dynamic-refresh-sources=false") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()).isFalse())); } @Test void testRedisConfigurationWithClusterDynamicSourcesUnspecifiedUsesDefault() { this.contextRunner - .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", - "spring.data.redis.lettuce.cluster.refresh.dynamic-sources=") - .run(assertClientOptions(ClusterClientOptions.class, - (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()) - .isTrue())); + .withPropertyValues("spring.data.redis.cluster.nodes=127.0.0.1:27379,127.0.0.1:27380", + "spring.data.redis.lettuce.cluster.refresh.dynamic-sources=") + .run(assertClientOptions(ClusterClientOptions.class, + (options) -> assertThat(options.getTopologyRefreshOptions().useDynamicRefreshSources()).isTrue())); } private ContextConsumer assertClientOptions( Class expectedType, Consumer options) { return (context) -> { LettuceClientConfiguration clientConfiguration = context.getBean(LettuceConnectionFactory.class) - .getClientConfiguration(); + .getClientConfiguration(); assertThat(clientConfiguration.getClientOptions()).isPresent(); ClientOptions clientOptions = clientConfiguration.getClientOptions().get(); assertThat(clientOptions.getClass()).isEqualTo(expectedType); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java index 0a42e51a73..5d2544bc44 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,9 +34,9 @@ class RedisPropertiesTests { void lettuceDefaultsAreConsistent() { Lettuce lettuce = new RedisProperties().getLettuce(); ClusterTopologyRefreshOptions defaultClusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder() - .build(); + .build(); assertThat(lettuce.getCluster().getRefresh().isDynamicRefreshSources()) - .isEqualTo(defaultClusterTopologyRefreshOptions.useDynamicRefreshSources()); + .isEqualTo(defaultClusterTopologyRefreshOptions.useDynamicRefreshSources()); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java index fb0a6abd14..545ace7385 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisReactiveAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -33,8 +33,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ class RedisReactiveAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); @Test void testDefaultRedisConfiguration() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java index 57ad1559f3..f7e719c865 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisRepositoriesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,15 +48,15 @@ class RedisRepositoriesAutoConfigurationTests { @Container public static RedisContainer redis = new RedisContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)); + .withStartupTimeout(Duration.ofMinutes(10)); private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @BeforeEach void setUp() { TestPropertyValues - .of("spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) - .applyTo(this.context.getEnvironment()); + .of("spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) + .applyTo(this.context.getEnvironment()); } @AfterEach diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java index f849a6b734..a875cd5e6d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisUrlSyntaxFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class RedisUrlSyntaxFailureAnalyzerTests { RedisUrlSyntaxException exception = new RedisUrlSyntaxException("http://127.0.0.1:26379/mymaster"); FailureAnalysis analysis = new RedisUrlSyntaxFailureAnalyzer().analyze(exception); assertThat(analysis.getDescription()).contains("The URL 'http://127.0.0.1:26379/mymaster' is not valid") - .contains("The scheme 'http' is not supported"); + .contains("The scheme 'http' is not supported"); assertThat(analysis.getAction()).contains("Use the scheme 'redis://' for insecure or 'rediss://' for secure"); } @@ -53,7 +53,7 @@ class RedisUrlSyntaxFailureAnalyzerTests { FailureAnalysis analysis = new RedisUrlSyntaxFailureAnalyzer().analyze(exception); assertThat(analysis.getDescription()).contains( "The URL 'redis-sentinel://username:password@127.0.0.1:26379,127.0.0.1:26380/mymaster' is not valid") - .contains("The scheme 'redis-sentinel' is not supported"); + .contains("The scheme 'redis-sentinel' is not supported"); assertThat(analysis.getAction()).contains("Use spring.data.redis.sentinel properties"); } @@ -62,7 +62,7 @@ class RedisUrlSyntaxFailureAnalyzerTests { RedisUrlSyntaxException exception = new RedisUrlSyntaxException("redis-socket:///redis/redis.sock"); FailureAnalysis analysis = new RedisUrlSyntaxFailureAnalyzer().analyze(exception); assertThat(analysis.getDescription()).contains("The URL 'redis-socket:///redis/redis.sock' is not valid") - .contains("The scheme 'redis-socket' is not supported"); + .contains("The scheme 'redis-socket' is not supported"); assertThat(analysis.getAction()).contains("Configure the appropriate Spring Data Redis connection beans"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java index 2118e427ac..67cf7109ca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/web/SpringDataWebAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,18 +37,18 @@ import static org.assertj.core.api.Assertions.assertThat; class SpringDataWebAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)); @Test void webSupportIsAutoConfiguredInWebApplicationContexts() { this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class)); + .run((context) -> assertThat(context).hasSingleBean(PageableHandlerMethodArgumentResolver.class)); } @Test void autoConfigurationBacksOffInNonWebApplicationContexts() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(SpringDataWebAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(PageableHandlerMethodArgumentResolver.class)); + .run((context) -> assertThat(context).doesNotHaveBean(PageableHandlerMethodArgumentResolver.class)); } @Test @@ -57,17 +57,17 @@ class SpringDataWebAutoConfigurationTests { "spring.data.web.pageable.size-parameter=s", "spring.data.web.pageable.default-page-size=10", "spring.data.web.pageable.prefix=abc", "spring.data.web.pageable.qualifier-delimiter=__", "spring.data.web.pageable.max-page-size=100", "spring.data.web.pageable.one-indexed-parameters=true") - .run((context) -> { - PageableHandlerMethodArgumentResolver argumentResolver = context - .getBean(PageableHandlerMethodArgumentResolver.class); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", "p"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", "s"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("oneIndexedParameters", true); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", "abc"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("qualifierDelimiter", "__"); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("fallbackPageable", PageRequest.of(0, 10)); - assertThat(argumentResolver).hasFieldOrPropertyWithValue("maxPageSize", 100); - }); + .run((context) -> { + PageableHandlerMethodArgumentResolver argumentResolver = context + .getBean(PageableHandlerMethodArgumentResolver.class); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", "p"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", "s"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("oneIndexedParameters", true); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("prefix", "abc"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("qualifierDelimiter", "__"); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("fallbackPageable", PageRequest.of(0, 10)); + assertThat(argumentResolver).hasFieldOrPropertyWithValue("maxPageSize", 100); + }); } @Test @@ -75,7 +75,7 @@ class SpringDataWebAutoConfigurationTests { this.contextRunner.run((context) -> { SpringDataWebProperties.Pageable properties = new SpringDataWebProperties().getPageable(); PageableHandlerMethodArgumentResolver argumentResolver = context - .getBean(PageableHandlerMethodArgumentResolver.class); + .getBean(PageableHandlerMethodArgumentResolver.class); assertThat(argumentResolver).hasFieldOrPropertyWithValue("pageParameterName", properties.getPageParameter()); assertThat(argumentResolver).hasFieldOrPropertyWithValue("sizeParameterName", @@ -95,7 +95,7 @@ class SpringDataWebAutoConfigurationTests { void customizeSort() { this.contextRunner.withPropertyValues("spring.data.web.sort.sort-parameter=s").run((context) -> { SortHandlerMethodArgumentResolver argumentResolver = context - .getBean(SortHandlerMethodArgumentResolver.class); + .getBean(SortHandlerMethodArgumentResolver.class); assertThat(argumentResolver).hasFieldOrPropertyWithValue("sortParameter", "s"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java index 8c241c7178..a8383f44b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,7 +66,7 @@ class NoSuchBeanDefinitionFailureAnalyzerTests { FailureAnalysis analysis = analyzeFailure(createFailure(StringHandler.class)); assertDescriptionConstructorMissingType(analysis, StringHandler.class, 0, String.class); assertThat(analysis.getDescription()) - .doesNotContain("No matching auto-configuration has been found for this type."); + .doesNotContain("No matching auto-configuration has been found for this type."); assertThat(analysis.getAction()).startsWith( String.format("Consider defining a bean of type '%s' in your configuration.", String.class.getName())); } @@ -126,18 +126,18 @@ class NoSuchBeanDefinitionFailureAnalyzerTests { void failureAnalysisForNoMatchName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringNameHandler.class)); assertThat(analysis.getDescription()) - .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); assertThat(analysis.getAction()) - .startsWith(String.format("Consider defining a bean named '%s' in your configuration.", "test-string")); + .startsWith(String.format("Consider defining a bean named '%s' in your configuration.", "test-string")); } @Test void failureAnalysisForMissingBeanName() { FailureAnalysis analysis = analyzeFailure(createFailure(StringMissingBeanNameConfiguration.class)); assertThat(analysis.getDescription()) - .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", - StringNameHandler.class.getName(), "test-string")); + .startsWith(String.format("Constructor in %s required a bean named '%s' that could not be found", + StringNameHandler.class.getName(), "test-string")); assertBeanMethodDisabled(analysis, "@ConditionalOnBean (types: java.lang.Integer; SearchStrategy: all) did not find any beans", TestMissingBeanAutoConfiguration.class, "string"); @@ -156,7 +156,7 @@ class NoSuchBeanDefinitionFailureAnalyzerTests { void failureAnalysisForUnmatchedQualifier() { FailureAnalysis analysis = analyzeFailure(createFailure(QualifiedBeanConfiguration.class)); assertThat(analysis.getDescription()) - .containsPattern("@org.springframework.beans.factory.annotation.Qualifier\\(\"*alpha\"*\\)"); + .containsPattern("@org.springframework.beans.factory.annotation.Qualifier\\(\"*alpha\"*\\)"); } private void assertDescriptionConstructorMissingType(FailureAnalysis analysis, Class component, int index, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java index 9f30c1c7e4..0289be2ee9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,7 @@ class EntityScanPackagesTests { @Test void registerFromArrayWhenRegistryIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> EntityScanPackages.register(null)) - .withMessageContaining("Registry must not be null"); + .withMessageContaining("Registry must not be null"); } @@ -77,23 +77,23 @@ class EntityScanPackagesTests { void registerFromArrayWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(this.context, (String[]) null)) - .withMessageContaining("PackageNames must not be null"); + .isThrownBy(() -> EntityScanPackages.register(this.context, (String[]) null)) + .withMessageContaining("PackageNames must not be null"); } @Test void registerFromCollectionWhenRegistryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(null, Collections.emptyList())) - .withMessageContaining("Registry must not be null"); + .isThrownBy(() -> EntityScanPackages.register(null, Collections.emptyList())) + .withMessageContaining("Registry must not be null"); } @Test void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); assertThatIllegalArgumentException() - .isThrownBy(() -> EntityScanPackages.register(this.context, (Collection) null)) - .withMessageContaining("PackageNames must not be null"); + .isThrownBy(() -> EntityScanPackages.register(this.context, (Collection) null)) + .withMessageContaining("PackageNames must not be null"); } @Test @@ -123,8 +123,8 @@ class EntityScanPackagesTests { @Test void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() { assertThatExceptionOfType(AnnotationConfigurationException.class) - .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext( - EntityScanValueAndBasePackagesConfig.class)); + .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext( + EntityScanValueAndBasePackagesConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java index 98bc36f0e1..d8ffd41d7b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class EntityScannerTests { @Test void createWhenContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new EntityScanner(null)) - .withMessageContaining("Context must not be null"); + .withMessageContaining("Context must not be null"); } @Test @@ -69,7 +69,7 @@ class EntityScannerTests { void scanShouldScanFromResolvedPlaceholderPackage() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); TestPropertyValues.of("com.example.entity-package=org.springframework.boot.autoconfigure.domain.scan") - .applyTo(context); + .applyTo(context); context.register(ScanPlaceholderConfig.class); context.refresh(); EntityScanner scanner = new EntityScanner(context); @@ -105,14 +105,14 @@ class EntityScannerTests { ClassPathScanningCandidateComponentProvider candidateComponentProvider = mock( ClassPathScanningCandidateComponentProvider.class); given(candidateComponentProvider.findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan")) - .willReturn(Collections.emptySet()); + .willReturn(Collections.emptySet()); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScanConfig.class); TestEntityScanner scanner = new TestEntityScanner(context, candidateComponentProvider); scanner.scan(Entity.class); ArgumentCaptor annotationTypeFilter = ArgumentCaptor.forClass(AnnotationTypeFilter.class); then(candidateComponentProvider).should().addIncludeFilter(annotationTypeFilter.capture()); then(candidateComponentProvider).should() - .findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan"); + .findCandidateComponents("org.springframework.boot.autoconfigure.domain.scan"); then(candidateComponentProvider).shouldHaveNoMoreInteractions(); assertThat(annotationTypeFilter.getValue().getAnnotationType()).isEqualTo(Entity.class); } @@ -120,9 +120,9 @@ class EntityScannerTests { @Test void scanShouldScanCommaSeparatedPackagesInPlaceholderPackage() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of( - "com.example.entity-package=org.springframework.boot.autoconfigure.domain.scan.a,org.springframework.boot.autoconfigure.domain.scan.b") - .applyTo(context); + TestPropertyValues + .of("com.example.entity-package=org.springframework.boot.autoconfigure.domain.scan.a,org.springframework.boot.autoconfigure.domain.scan.b") + .applyTo(context); context.register(ScanPlaceholderConfig.class); context.refresh(); EntityScanner scanner = new EntityScanner(context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationIntegrationTests.java index 2684f3cf05..3abda84420 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,24 +43,25 @@ class ElasticsearchClientAutoConfigurationIntegrationTests { @Container static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, - ElasticsearchRestClientAutoConfiguration.class, ElasticsearchClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, + ElasticsearchRestClientAutoConfiguration.class, ElasticsearchClientAutoConfiguration.class)); @Test void reactiveClientCanQueryElasticsearchNode() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), - "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") - .run((context) -> { - ElasticsearchClient client = context.getBean(ElasticsearchClient.class); - client.index((b) -> b.index("foo").id("1").document(Map.of("a", "alpha", "b", "bravo"))); - GetResponse response = client.get((b) -> b.index("foo").id("1"), Object.class); - assertThat(response).isNotNull(); - assertThat(response.found()).isTrue(); - }); + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), + "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") + .run((context) -> { + ElasticsearchClient client = context.getBean(ElasticsearchClient.class); + client.index((b) -> b.index("foo").id("1").document(Map.of("a", "alpha", "b", "bravo"))); + GetResponse response = client.get((b) -> b.index("foo").id("1"), Object.class); + assertThat(response).isNotNull(); + assertThat(response.found()).isTrue(); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationTests.java index fee56198b4..c290db791f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchClientAutoConfigurationTests.java @@ -45,78 +45,86 @@ import static org.mockito.Mockito.mock; class ElasticsearchClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchClientAutoConfiguration.class)); @Test void withoutRestClientThenAutoConfigurationShouldBackOff() { this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(ElasticsearchTransport.class) - .doesNotHaveBean(JsonpMapper.class).doesNotHaveBean(ElasticsearchClient.class)); + .doesNotHaveBean(JsonpMapper.class) + .doesNotHaveBean(ElasticsearchClient.class)); } @Test void withRestClientAutoConfigurationShouldDefineClientAndSupportingBeans() { this.contextRunner.withUserConfiguration(RestClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(JsonpMapper.class) - .hasSingleBean(RestClientTransport.class).hasSingleBean(ElasticsearchClient.class)); + .run((context) -> assertThat(context).hasSingleBean(JsonpMapper.class) + .hasSingleBean(RestClientTransport.class) + .hasSingleBean(ElasticsearchClient.class)); } @Test void withoutJsonbOrJacksonShouldDefineSimpleMapper() { - this.contextRunner.withUserConfiguration(RestClientConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JsonpMapper.class).hasSingleBean(SimpleJsonpMapper.class)); + this.contextRunner.withUserConfiguration(RestClientConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JsonpMapper.class) + .hasSingleBean(SimpleJsonpMapper.class)); } @Test void withJsonbShouldDefineJsonbMapper() { this.contextRunner.withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) - .withUserConfiguration(RestClientConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JsonpMapper.class).hasSingleBean(JsonbJsonpMapper.class)); + .withUserConfiguration(RestClientConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JsonpMapper.class) + .hasSingleBean(JsonbJsonpMapper.class)); } @Test void withJacksonShouldDefineJacksonMapper() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withUserConfiguration(RestClientConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JsonpMapper.class).hasSingleBean(JacksonJsonpMapper.class)); + .withUserConfiguration(RestClientConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JsonpMapper.class) + .hasSingleBean(JacksonJsonpMapper.class)); } @Test void withJacksonAndJsonbShouldDefineJacksonMapper() { this.contextRunner - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class, JacksonAutoConfiguration.class)) - .withUserConfiguration(RestClientConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(JsonpMapper.class).hasSingleBean(JacksonJsonpMapper.class)); + .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class, JacksonAutoConfiguration.class)) + .withUserConfiguration(RestClientConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(JsonpMapper.class) + .hasSingleBean(JacksonJsonpMapper.class)); } @Test void withCustomMapperTransportShouldUseIt() { this.contextRunner.withUserConfiguration(JsonpMapperConfiguration.class) - .withUserConfiguration(RestClientConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(JsonpMapper.class).hasBean("customJsonpMapper"); - JsonpMapper mapper = context.getBean(JsonpMapper.class); - assertThat(context.getBean(ElasticsearchTransport.class).jsonpMapper()).isSameAs(mapper); - }); + .withUserConfiguration(RestClientConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(JsonpMapper.class).hasBean("customJsonpMapper"); + JsonpMapper mapper = context.getBean(JsonpMapper.class); + assertThat(context.getBean(ElasticsearchTransport.class).jsonpMapper()).isSameAs(mapper); + }); } @Test void withCustomTransportClientShouldUseIt() { this.contextRunner.withUserConfiguration(TransportConfiguration.class) - .withUserConfiguration(RestClientConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ElasticsearchTransport.class) - .hasBean("customElasticsearchTransport"); - ElasticsearchTransport transport = context.getBean(ElasticsearchTransport.class); - assertThat(context.getBean(ElasticsearchClient.class)._transport()).isSameAs(transport); - }); + .withUserConfiguration(RestClientConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ElasticsearchTransport.class).hasBean("customElasticsearchTransport"); + ElasticsearchTransport transport = context.getBean(ElasticsearchTransport.class); + assertThat(context.getBean(ElasticsearchClient.class)._transport()).isSameAs(transport); + }); } @Test void jacksonJsonpMapperDoesNotUseGlobalObjectMapper() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withUserConfiguration(RestClientConfiguration.class).run((context) -> { - ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - JacksonJsonpMapper jacksonJsonpMapper = context.getBean(JacksonJsonpMapper.class); - assertThat(jacksonJsonpMapper.objectMapper()).isNotSameAs(objectMapper); - }); + .withUserConfiguration(RestClientConfiguration.class) + .run((context) -> { + ObjectMapper objectMapper = context.getBean(ObjectMapper.class); + JacksonJsonpMapper jacksonJsonpMapper = context.getBean(JacksonJsonpMapper.class); + assertThat(jacksonJsonpMapper.objectMapper()).isNotSameAs(objectMapper); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java index 31e5fc62b6..821b982a51 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,28 +48,29 @@ class ElasticsearchRestClientAutoConfigurationIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); @Test void restClientCanQueryElasticsearchNode() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), - "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") - .run((context) -> { - RestClient client = context.getBean(RestClient.class); - Request index = new Request("PUT", "/test/_doc/2"); - index.setJsonEntity("{" + " \"a\": \"alpha\"," + " \"b\": \"bravo\"" + "}"); - client.performRequest(index); - Request getRequest = new Request("GET", "/test/_doc/2"); - Response response = client.performRequest(getRequest); - try (InputStream input = response.getEntity().getContent()) { - JsonNode result = new ObjectMapper().readTree(input); - assertThat(result.path("found").asBoolean()).isTrue(); - } - }); + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), + "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") + .run((context) -> { + RestClient client = context.getBean(RestClient.class); + Request index = new Request("PUT", "/test/_doc/2"); + index.setJsonEntity("{" + " \"a\": \"alpha\"," + " \"b\": \"bravo\"" + "}"); + client.performRequest(index); + Request getRequest = new Request("GET", "/test/_doc/2"); + Response response = client.performRequest(getRequest); + try (InputStream input = response.getEntity().getContent()) { + JsonNode result = new ObjectMapper().readTree(input); + assertThat(result.path("found").asBoolean()).isTrue(); + } + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java index 38b11a60c5..79b9c59e90 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ElasticsearchRestClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,19 +53,20 @@ import static org.mockito.Mockito.mock; class ElasticsearchRestClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class)); @Test void configureShouldCreateRestClientBuilderAndRestClient() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(RestClient.class) - .hasSingleBean(RestClientBuilder.class)); + .hasSingleBean(RestClientBuilder.class)); } @Test void configureWhenCustomRestClientShouldBackOff() { this.contextRunner.withUserConfiguration(CustomRestClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(RestClientBuilder.class) - .hasSingleBean(RestClient.class).hasBean("customRestClient")); + .run((context) -> assertThat(context).hasSingleBean(RestClientBuilder.class) + .hasSingleBean(RestClient.class) + .hasBean("customRestClient")); } @Test @@ -91,19 +92,20 @@ class ElasticsearchRestClientAutoConfigurationTests { @Test void configureWithCustomTimeouts() { - this.contextRunner.withPropertyValues("spring.elasticsearch.connection-timeout=15s", - "spring.elasticsearch.socket-timeout=1m").run((context) -> { - assertThat(context).hasSingleBean(RestClient.class); - RestClient restClient = context.getBean(RestClient.class); - assertTimeouts(restClient, Duration.ofSeconds(15), Duration.ofMinutes(1)); - }); + this.contextRunner + .withPropertyValues("spring.elasticsearch.connection-timeout=15s", "spring.elasticsearch.socket-timeout=1m") + .run((context) -> { + assertThat(context).hasSingleBean(RestClient.class); + RestClient restClient = context.getBean(RestClient.class); + assertTimeouts(restClient, Duration.ofSeconds(15), Duration.ofMinutes(1)); + }); } private static void assertTimeouts(RestClient restClient, Duration connectTimeout, Duration readTimeout) { assertThat(restClient).extracting("client.defaultConfig.socketTimeout") - .isEqualTo(Math.toIntExact(readTimeout.toMillis())); + .isEqualTo(Math.toIntExact(readTimeout.toMillis())); assertThat(restClient).extracting("client.defaultConfig.connectTimeout") - .isEqualTo(Math.toIntExact(connectTimeout.toMillis())); + .isEqualTo(Math.toIntExact(connectTimeout.toMillis())); } @Test @@ -111,7 +113,7 @@ class ElasticsearchRestClientAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.elasticsearch.uris=localhost:9876").run((context) -> { RestClient client = context.getBean(RestClient.class); assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9876"); + .containsExactly("http://localhost:9876"); }); } @@ -120,59 +122,56 @@ class ElasticsearchRestClientAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.elasticsearch.uris=http://user@localhost:9200").run((context) -> { RestClient client = context.getBean(RestClient.class); assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9200"); + .containsExactly("http://localhost:9200"); assertThat(client) - .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) - .satisfies((credentialsProvider) -> { - Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); - assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); - assertThat(credentials.getPassword()).isNull(); - }); + .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) + .satisfies((credentialsProvider) -> { + Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); + assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); + assertThat(credentials.getPassword()).isNull(); + }); }); } @Test void configureUriWithUsernameAndEmptyPassword() { this.contextRunner.withPropertyValues("spring.elasticsearch.uris=http://user:@localhost:9200") - .run((context) -> { - RestClient client = context.getBean(RestClient.class); - assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9200"); - assertThat(client) - .extracting("client.credentialsProvider", - InstanceOfAssertFactories.type(CredentialsProvider.class)) - .satisfies((credentialsProvider) -> { - Credentials credentials = credentialsProvider - .getCredentials(new AuthScope("localhost", 9200)); - assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); - assertThat(credentials.getPassword()).isEmpty(); - }); - }); + .run((context) -> { + RestClient client = context.getBean(RestClient.class); + assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) + .containsExactly("http://localhost:9200"); + assertThat(client) + .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) + .satisfies((credentialsProvider) -> { + Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 9200)); + assertThat(credentials.getUserPrincipal().getName()).isEqualTo("user"); + assertThat(credentials.getPassword()).isEmpty(); + }); + }); } @Test void configureUriWithUsernameAndPasswordWhenUsernameAndPasswordPropertiesSet() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=http://user:password@localhost:9200,localhost:9201", - "spring.elasticsearch.username=admin", "spring.elasticsearch.password=admin") - .run((context) -> { - RestClient client = context.getBean(RestClient.class); - assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) - .containsExactly("http://localhost:9200", "http://localhost:9201"); - assertThat(client) - .extracting("client.credentialsProvider", - InstanceOfAssertFactories.type(CredentialsProvider.class)) - .satisfies((credentialsProvider) -> { - Credentials uriCredentials = credentialsProvider - .getCredentials(new AuthScope("localhost", 9200)); - assertThat(uriCredentials.getUserPrincipal().getName()).isEqualTo("user"); - assertThat(uriCredentials.getPassword()).isEqualTo("password"); - Credentials defaultCredentials = credentialsProvider - .getCredentials(new AuthScope("localhost", 9201)); - assertThat(defaultCredentials.getUserPrincipal().getName()).isEqualTo("admin"); - assertThat(defaultCredentials.getPassword()).isEqualTo("admin"); - }); - }); + .withPropertyValues("spring.elasticsearch.uris=http://user:password@localhost:9200,localhost:9201", + "spring.elasticsearch.username=admin", "spring.elasticsearch.password=admin") + .run((context) -> { + RestClient client = context.getBean(RestClient.class); + assertThat(client.getNodes().stream().map(Node::getHost).map(HttpHost::toString)) + .containsExactly("http://localhost:9200", "http://localhost:9201"); + assertThat(client) + .extracting("client.credentialsProvider", InstanceOfAssertFactories.type(CredentialsProvider.class)) + .satisfies((credentialsProvider) -> { + Credentials uriCredentials = credentialsProvider + .getCredentials(new AuthScope("localhost", 9200)); + assertThat(uriCredentials.getUserPrincipal().getName()).isEqualTo("user"); + assertThat(uriCredentials.getPassword()).isEqualTo("password"); + Credentials defaultCredentials = credentialsProvider + .getCredentials(new AuthScope("localhost", 9201)); + assertThat(defaultCredentials.getUserPrincipal().getName()).isEqualTo("admin"); + assertThat(defaultCredentials.getPassword()).isEqualTo("admin"); + }); + }); } @Test @@ -195,14 +194,14 @@ class ElasticsearchRestClientAutoConfigurationTests { assertThat(context).hasSingleBean(RestClient.class); RestClient client = context.getBean(RestClient.class); assertThat(client.getHttpClient()).extracting("connmgr.ioReactor.config.soKeepAlive") - .isEqualTo(Boolean.TRUE); + .isEqualTo(Boolean.TRUE); }); } @Test void configureWithoutSnifferLibraryShouldNotCreateSniffer() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.elasticsearch.client.sniff")) - .run((context) -> assertThat(context).hasSingleBean(RestClient.class).doesNotHaveBean(Sniffer.class)); + .run((context) -> assertThat(context).hasSingleBean(RestClient.class).doesNotHaveBean(Sniffer.class)); } @Test @@ -214,21 +213,23 @@ class ElasticsearchRestClientAutoConfigurationTests { // Validate shutdown order as the sniffer must be shutdown before the // client assertThat(context.getBeanFactory().getDependentBeans("elasticsearchRestClient")) - .contains("elasticsearchSniffer"); + .contains("elasticsearchSniffer"); }); } @Test void configureWithCustomSnifferSettings() { - this.contextRunner.withPropertyValues("spring.elasticsearch.restclient.sniffer.interval=180s", - "spring.elasticsearch.restclient.sniffer.delay-after-failure=30s").run((context) -> { - assertThat(context).hasSingleBean(Sniffer.class); - Sniffer sniffer = context.getBean(Sniffer.class); - assertThat(sniffer).hasFieldOrPropertyWithValue("sniffIntervalMillis", - Duration.ofMinutes(3).toMillis()); - assertThat(sniffer).hasFieldOrPropertyWithValue("sniffAfterFailureDelayMillis", - Duration.ofSeconds(30).toMillis()); - }); + this.contextRunner + .withPropertyValues("spring.elasticsearch.restclient.sniffer.interval=180s", + "spring.elasticsearch.restclient.sniffer.delay-after-failure=30s") + .run((context) -> { + assertThat(context).hasSingleBean(Sniffer.class); + Sniffer sniffer = context.getBean(Sniffer.class); + assertThat(sniffer).hasFieldOrPropertyWithValue("sniffIntervalMillis", + Duration.ofMinutes(3).toMillis()); + assertThat(sniffer).hasFieldOrPropertyWithValue("sniffAfterFailureDelayMillis", + Duration.ofSeconds(30).toMillis()); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationIntegrationTests.java index 26a64cba64..ca2da2e735 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,27 +46,28 @@ class ReactiveElasticsearchClientAutoConfigurationIntegrationTests { @Container static ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, ElasticsearchRestClientAutoConfiguration.class, - ReactiveElasticsearchClientAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, + ElasticsearchRestClientAutoConfiguration.class, ReactiveElasticsearchClientAutoConfiguration.class)); @Test void reactiveClientCanQueryElasticsearchNode() { this.contextRunner - .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), - "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") - .run((context) -> { - ReactiveElasticsearchClient client = context.getBean(ReactiveElasticsearchClient.class); - Mono index = client - .index((b) -> b.index("foo").id("1").document(Map.of("a", "alpha", "b", "bravo"))); - index.block(); - Mono> get = client.get((b) -> b.index("foo").id("1"), Object.class); - GetResponse response = get.block(); - assertThat(response).isNotNull(); - assertThat(response.found()).isTrue(); - }); + .withPropertyValues("spring.elasticsearch.uris=" + elasticsearch.getHttpHostAddress(), + "spring.elasticsearch.connection-timeout=120s", "spring.elasticsearch.socket-timeout=120s") + .run((context) -> { + ReactiveElasticsearchClient client = context.getBean(ReactiveElasticsearchClient.class); + Mono index = client + .index((b) -> b.index("foo").id("1").document(Map.of("a", "alpha", "b", "bravo"))); + index.block(); + Mono> get = client.get((b) -> b.index("foo").id("1"), Object.class); + GetResponse response = get.block(); + assertThat(response).isNotNull(); + assertThat(response.found()).isTrue(); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationTests.java index cb5f89d8e3..0f1c5590b6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/elasticsearch/ReactiveElasticsearchClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock; class ReactiveElasticsearchClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveElasticsearchClientAutoConfiguration.class)); @Test void configureWithoutRestClientShouldBackOff() { @@ -47,14 +47,14 @@ class ReactiveElasticsearchClientAutoConfigurationTests { @Test void configureWithRestClientShouldCreateTransportAndClient() { this.contextRunner.withUserConfiguration(RestClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class)); } @Test void configureWhenCustomClientShouldBackOff() { this.contextRunner.withUserConfiguration(RestClientConfiguration.class, CustomClientConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) - .hasBean("customClient")); + .run((context) -> assertThat(context).hasSingleBean(ReactiveElasticsearchClient.class) + .hasBean("customClient")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java index de464d960f..6ac6211f37 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfigurationTests.java @@ -103,8 +103,8 @@ import static org.mockito.Mockito.mock; class FlywayAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void backsOffWithNoDataSourceBeanAndNoFlywayUrl() { @@ -114,88 +114,90 @@ class FlywayAutoConfigurationTests { @Test void createsDataSourceWithNoDataSourceBeanAndFlywayUrl() { this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); + }); } @Test void backsOffWithFlywayUrlAndNoSpringJdbc() { this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) - .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) - .run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) + .run((context) -> assertThat(context).doesNotHaveBean(Flyway.class)); } @Test void createDataSourceWithUrl() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); - }); + .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); + }); } @Test void createDataSourceWithUser() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID(), - "spring.flyway.user:sa") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); - }); + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:" + UUID.randomUUID(), "spring.flyway.user:sa") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()).isNotNull(); + }); } @Test void createDataSourceDoesNotFallbackToEmbeddedProperties() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); - assertThat(dataSource).isNotNull(); - assertThat(dataSource).hasFieldOrPropertyWithValue("username", null); - assertThat(dataSource).hasFieldOrPropertyWithValue("password", ""); - }); + .withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); + assertThat(dataSource).isNotNull(); + assertThat(dataSource).hasFieldOrPropertyWithValue("username", null); + assertThat(dataSource).hasFieldOrPropertyWithValue("password", ""); + }); } @Test void createDataSourceWithUserAndFallbackToEmbeddedProperties() { this.contextRunner.withUserConfiguration(PropertiesBackedH2DataSourceConfiguration.class) - .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); - assertThat(dataSource).isNotNull(); - assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:"); - assertThat(dataSource).extracting("username").asString().isEqualTo("test"); - }); + .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); + assertThat(dataSource).isNotNull(); + assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:"); + assertThat(dataSource).extracting("username").asString().isEqualTo("test"); + }); } @Test void createDataSourceWithUserAndCustomEmbeddedProperties() { this.contextRunner.withUserConfiguration(CustomBackedH2DataSourceConfiguration.class) - .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - String expectedName = context.getBean(CustomBackedH2DataSourceConfiguration.class).name; - String propertiesName = context.getBean(DataSourceProperties.class).determineDatabaseName(); - assertThat(expectedName).isNotEqualTo(propertiesName); - DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); - assertThat(dataSource).isNotNull(); - assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:") - .contains(expectedName); - assertThat(dataSource).extracting("username").asString().isEqualTo("test"); - }); + .withPropertyValues("spring.flyway.user:test", "spring.flyway.password:secret") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + String expectedName = context.getBean(CustomBackedH2DataSourceConfiguration.class).name; + String propertiesName = context.getBean(DataSourceProperties.class).determineDatabaseName(); + assertThat(expectedName).isNotEqualTo(propertiesName); + DataSource dataSource = context.getBean(Flyway.class).getConfiguration().getDataSource(); + assertThat(dataSource).isNotNull(); + assertThat(dataSource).extracting("url").asString().startsWith("jdbc:h2:mem:").contains(expectedName); + assertThat(dataSource).extracting("username").asString().isEqualTo("test"); + }); } @Test void flywayDataSource() { this.contextRunner - .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) - .isEqualTo(context.getBean("flywayDataSource")); - }); + .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) + .isEqualTo(context.getBean("flywayDataSource")); + }); } @Test @@ -203,7 +205,7 @@ class FlywayAutoConfigurationTests { this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) - .isEqualTo(context.getBean("flywayDataSource")); + .isEqualTo(context.getBean("flywayDataSource")); }); } @@ -212,23 +214,23 @@ class FlywayAutoConfigurationTests { this.contextRunner.withUserConfiguration(FlywayMultipleDataSourcesConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(Flyway.class); assertThat(context.getBean(Flyway.class).getConfiguration().getDataSource()) - .isEqualTo(context.getBean("flywayDataSource")); + .isEqualTo(context.getBean("flywayDataSource")); }); } @Test void schemaManagementProviderDetectsDataSource() { this.contextRunner - .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - FlywaySchemaManagementProvider schemaManagementProvider = context - .getBean(FlywaySchemaManagementProvider.class); - assertThat(schemaManagementProvider.getSchemaManagement(context.getBean(DataSource.class))) - .isEqualTo(SchemaManagement.UNMANAGED); - assertThat(schemaManagementProvider - .getSchemaManagement(context.getBean("flywayDataSource", DataSource.class))) - .isEqualTo(SchemaManagement.MANAGED); - }); + .withUserConfiguration(FlywayDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + FlywaySchemaManagementProvider schemaManagementProvider = context + .getBean(FlywaySchemaManagementProvider.class); + assertThat(schemaManagementProvider.getSchemaManagement(context.getBean(DataSource.class))) + .isEqualTo(SchemaManagement.UNMANAGED); + assertThat(schemaManagementProvider + .getSchemaManagement(context.getBean("flywayDataSource", DataSource.class))) + .isEqualTo(SchemaManagement.MANAGED); + }); } @Test @@ -237,433 +239,443 @@ class FlywayAutoConfigurationTests { assertThat(context).hasSingleBean(Flyway.class); Flyway flyway = context.getBean(Flyway.class); assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/migration")); + .containsExactly(new Location("classpath:db/migration")); }); } @Test void overrideLocations() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()).containsExactly( - new Location("classpath:db/changelog"), new Location("classpath:db/migration")); - }); + .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()) + .containsExactly(new Location("classpath:db/changelog"), new Location("classpath:db/migration")); + }); } @Test void overrideLocationsList() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations[0]:classpath:db/changelog", - "spring.flyway.locations[1]:classpath:db/migration") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()).containsExactly( - new Location("classpath:db/changelog"), new Location("classpath:db/migration")); - }); + .withPropertyValues("spring.flyway.locations[0]:classpath:db/changelog", + "spring.flyway.locations[1]:classpath:db/migration") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()) + .containsExactly(new Location("classpath:db/changelog"), new Location("classpath:db/migration")); + }); } @Test void overrideSchemas() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.schemas:public").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(Arrays.asList(flyway.getConfiguration().getSchemas())).hasToString("[public]"); - }); + .withPropertyValues("spring.flyway.schemas:public") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(Arrays.asList(flyway.getConfiguration().getSchemas())).hasToString("[public]"); + }); } @Test void overrideDataSourceAndDriverClassName() { String jdbcUrl = "jdbc:hsqldb:mem:flyway" + UUID.randomUUID(); String driverClassName = "org.hsqldb.jdbcDriver"; - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class).withPropertyValues( - "spring.flyway.url:" + jdbcUrl, "spring.flyway.driver-class-name:" + driverClassName).run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) flyway.getConfiguration() - .getDataSource(); - assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); - assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); - }); + this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .withPropertyValues("spring.flyway.url:" + jdbcUrl, "spring.flyway.driver-class-name:" + driverClassName) + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) flyway.getConfiguration().getDataSource(); + assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); + assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); + }); } @Test void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true", - "spring.flyway.locations:filesystem:no-such-dir") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); - }); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true", + "spring.flyway.locations:filesystem:no-such-dir") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + }); } @Test void failOnMissingLocationsAllMissing() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:classpath:db/missing1,classpath:db/migration2") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); - assertThat(context).getFailure().hasMessageContaining("Unable to resolve location"); - }); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:classpath:db/missing1,classpath:db/migration2") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + assertThat(context).getFailure().hasMessageContaining("Unable to resolve location"); + }); } @Test void failOnMissingLocationsAllExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void failOnMissingLocationsAllExistWithImplicitClasspathPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:db/changelog,db/migration") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:db/changelog,db/migration") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void failOnMissingLocationsAllExistWithFilesystemPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.fail-on-missing-locations=true") - .withPropertyValues("spring.flyway.locations:filesystem:src/test/resources/db/migration") - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.flyway.fail-on-missing-locations=true") + .withPropertyValues("spring.flyway.locations:filesystem:src/test/resources/db/migration") + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayMigrationStrategy() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MockFlywayMigrationStrategy.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - context.getBean(MockFlywayMigrationStrategy.class).assertCalled(); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, MockFlywayMigrationStrategy.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + context.getBean(MockFlywayMigrationStrategy.class).assertCalled(); + }); } @Test void flywayJavaMigrations() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, FlywayJavaMigrationsConfiguration.class) - .run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getJavaMigrations()).hasSize(2); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, FlywayJavaMigrationsConfiguration.class) + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getJavaMigrations()).hasSize(2); + }); } @Test void customFlywayMigrationInitializer() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayMigrationInitializer.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - FlywayMigrationInitializer initializer = context.getBean(FlywayMigrationInitializer.class); - assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayMigrationInitializer.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + FlywayMigrationInitializer initializer = context.getBean(FlywayMigrationInitializer.class); + assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE); + }); } @Test void customFlywayWithJpa() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJpaConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJpaConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayWithJdbc() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJdbcConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, CustomFlywayWithJdbcConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayMigrationInitializerWithJpa() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - CustomFlywayMigrationInitializerWithJpaConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, + CustomFlywayMigrationInitializerWithJpaConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void customFlywayMigrationInitializerWithJdbc() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, - CustomFlywayMigrationInitializerWithJdbcConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, + CustomFlywayMigrationInitializerWithJdbcConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void overrideBaselineVersionString() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.baseline-version=0").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("0")); - }); + .withPropertyValues("spring.flyway.baseline-version=0") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("0")); + }); } @Test void overrideBaselineVersionNumber() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.baseline-version=1").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("1")); - }); + .withPropertyValues("spring.flyway.baseline-version=1") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("1")); + }); } @Test void useVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog") - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()).containsExactlyInAnyOrder( - new Location("classpath:db/vendors/h2"), new Location("classpath:db/changelog")); - }); + .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()).containsExactlyInAnyOrder( + new Location("classpath:db/vendors/h2"), new Location("classpath:db/changelog")); + }); } @Test void useOneLocationWithVendorDirectory() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor}").run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getLocations()) - .containsExactly(new Location("classpath:db/vendors/h2")); - }); + .withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor}") + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getLocations()) + .containsExactly(new Location("classpath:db/vendors/h2")); + }); } @Test void callbacksAreConfiguredAndOrderedByName() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, CallbackConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - Callback callbackOne = context.getBean("callbackOne", Callback.class); - Callback callbackTwo = context.getBean("callbackTwo", Callback.class); - assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); - InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); - orderedCallbacks.verify(callbackTwo).handle(any(Event.class), any(Context.class)); - orderedCallbacks.verify(callbackOne).handle(any(Event.class), any(Context.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + Callback callbackOne = context.getBean("callbackOne", Callback.class); + Callback callbackTwo = context.getBean("callbackTwo", Callback.class); + assertThat(flyway.getConfiguration().getCallbacks()).hasSize(2); + InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo); + orderedCallbacks.verify(callbackTwo).handle(any(Event.class), any(Context.class)); + orderedCallbacks.verify(callbackOne).handle(any(Event.class), any(Context.class)); + }); } @Test void configurationCustomizersAreConfiguredAndOrdered() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, - ConfigurationCustomizerConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getConnectRetries()).isEqualTo(5); - assertThat(flyway.getConfiguration().getBaselineDescription()).isEqualTo("<< Custom baseline >>"); - assertThat(flyway.getConfiguration().getBaselineVersion()) - .isEqualTo(MigrationVersion.fromVersion("1")); - }); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ConfigurationCustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getConnectRetries()).isEqualTo(5); + assertThat(flyway.getConfiguration().getBaselineDescription()).isEqualTo("<< Custom baseline >>"); + assertThat(flyway.getConfiguration().getBaselineVersion()).isEqualTo(MigrationVersion.fromVersion("1")); + }); } @Test void callbackAndMigrationBeansAreAppliedToConfigurationBeforeCustomizersAreCalled() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, FlywayJavaMigrationsConfiguration.class, - CallbackConfiguration.class) - .withBean(FlywayConfigurationCustomizer.class, () -> (configuration) -> { - assertThat(configuration.getCallbacks()).isNotEmpty(); - assertThat(configuration.getJavaMigrations()).isNotEmpty(); - }).run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, FlywayJavaMigrationsConfiguration.class, + CallbackConfiguration.class) + .withBean(FlywayConfigurationCustomizer.class, () -> (configuration) -> { + assertThat(configuration.getCallbacks()).isNotEmpty(); + assertThat(configuration.getJavaMigrations()).isNotEmpty(); + }) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void batchIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.batch=true").run(validateFlywayTeamsPropertyOnly("batch")); + .withPropertyValues("spring.flyway.batch=true") + .run(validateFlywayTeamsPropertyOnly("batch")); } @Test void dryRunOutputIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.dryRunOutput=dryrun.sql") - .run(validateFlywayTeamsPropertyOnly("dryRunOutput")); + .withPropertyValues("spring.flyway.dryRunOutput=dryrun.sql") + .run(validateFlywayTeamsPropertyOnly("dryRunOutput")); } @Test void errorOverridesIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.errorOverrides=D12345") - .run(validateFlywayTeamsPropertyOnly("errorOverrides")); + .withPropertyValues("spring.flyway.errorOverrides=D12345") + .run(validateFlywayTeamsPropertyOnly("errorOverrides")); } @Test void licenseKeyIsCorrectlyMapped(CapturedOutput output) { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.license-key=<>") - .run((context) -> assertThat(output).contains("License key detected - in order to use Teams or " - + "Enterprise features, download Flyway Teams Edition & Flyway Enterprise Edition")); + .withPropertyValues("spring.flyway.license-key=<>") + .run((context) -> assertThat(output).contains("License key detected - in order to use Teams or " + + "Enterprise features, download Flyway Teams Edition & Flyway Enterprise Edition")); } @Test void oracleSqlplusIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-sqlplus=true") - .run(validateFlywayTeamsPropertyOnly("oracle.sqlplus")); + .withPropertyValues("spring.flyway.oracle-sqlplus=true") + .run(validateFlywayTeamsPropertyOnly("oracle.sqlplus")); } @Test void oracleSqlplusWarnIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-sqlplus-warn=true") - .run(validateFlywayTeamsPropertyOnly("oracle.sqlplusWarn")); + .withPropertyValues("spring.flyway.oracle-sqlplus-warn=true") + .run(validateFlywayTeamsPropertyOnly("oracle.sqlplusWarn")); } @Test void streamIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.stream=true").run(validateFlywayTeamsPropertyOnly("stream")); + .withPropertyValues("spring.flyway.stream=true") + .run(validateFlywayTeamsPropertyOnly("stream")); } @Test void undoSqlMigrationPrefix() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.undo-sql-migration-prefix=undo") - .run(validateFlywayTeamsPropertyOnly("undoSqlMigrationPrefix")); + .withPropertyValues("spring.flyway.undo-sql-migration-prefix=undo") + .run(validateFlywayTeamsPropertyOnly("undoSqlMigrationPrefix")); } @Test void customFlywayClassLoader() { this.contextRunner - .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ResourceLoaderConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Flyway.class); - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getClassLoader()).isInstanceOf(CustomClassLoader.class); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, ResourceLoaderConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(Flyway.class); + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getClassLoader()).isInstanceOf(CustomClassLoader.class); + }); } @Test void initSqlsWithDataSource() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.init-sqls=SELECT 1").run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); - }); + .withPropertyValues("spring.flyway.init-sqls=SELECT 1") + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); + }); } @Test void initSqlsWithFlywayUrl() { - this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:h2:mem:" + UUID.randomUUID(), - "spring.flyway.init-sqls=SELECT 1").run((context) -> { - Flyway flyway = context.getBean(Flyway.class); - assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); - }); + this.contextRunner + .withPropertyValues("spring.flyway.url:jdbc:h2:mem:" + UUID.randomUUID(), + "spring.flyway.init-sqls=SELECT 1") + .run((context) -> { + Flyway flyway = context.getBean(Flyway.class); + assertThat(flyway.getConfiguration().getInitSql()).isEqualTo("SELECT 1"); + }); } @Test void cherryPickIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.cherry-pick=1.1").run(validateFlywayTeamsPropertyOnly("cherryPick")); + .withPropertyValues("spring.flyway.cherry-pick=1.1") + .run(validateFlywayTeamsPropertyOnly("cherryPick")); } @Test void jdbcPropertiesAreCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.jdbc-properties.prop=value") - .run(validateFlywayTeamsPropertyOnly("jdbcProperties")); + .withPropertyValues("spring.flyway.jdbc-properties.prop=value") + .run(validateFlywayTeamsPropertyOnly("jdbcProperties")); } @Test void kerberosConfigFileIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.kerberos-config-file=/tmp/config") - .run(validateFlywayTeamsPropertyOnly("kerberosConfigFile")); + .withPropertyValues("spring.flyway.kerberos-config-file=/tmp/config") + .run(validateFlywayTeamsPropertyOnly("kerberosConfigFile")); } @Test void oracleKerberosCacheFileIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-kerberos-cache-file=/tmp/cache") - .run(validateFlywayTeamsPropertyOnly("oracle.kerberosCacheFile")); + .withPropertyValues("spring.flyway.oracle-kerberos-cache-file=/tmp/cache") + .run(validateFlywayTeamsPropertyOnly("oracle.kerberosCacheFile")); } @Test void outputQueryResultsIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.output-query-results=false") - .run(validateFlywayTeamsPropertyOnly("outputQueryResults")); + .withPropertyValues("spring.flyway.output-query-results=false") + .run(validateFlywayTeamsPropertyOnly("outputQueryResults")); } @Test void sqlServerKerberosLoginFileIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.sql-server-kerberos-login-file=/tmp/config") - .run(validateFlywayTeamsPropertyOnly("sqlserver.kerberos.login.file")); + .withPropertyValues("spring.flyway.sql-server-kerberos-login-file=/tmp/config") + .run(validateFlywayTeamsPropertyOnly("sqlserver.kerberos.login.file")); } @Test void skipExecutingMigrationsIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.skip-executing-migrations=true") - .run(validateFlywayTeamsPropertyOnly("skipExecutingMigrations")); + .withPropertyValues("spring.flyway.skip-executing-migrations=true") + .run(validateFlywayTeamsPropertyOnly("skipExecutingMigrations")); } @Test void whenFlywayIsAutoConfiguredThenJooqDslContextDependsOnFlywayBeans() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayInitializer", "flyway"); - }); + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayInitializer", "flyway"); + }); } @Test void whenCustomMigrationInitializerIsDefinedThenJooqDslContextDependsOnIt() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, - CustomFlywayMigrationInitializer.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayMigrationInitializer", - "flyway"); - }); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, + CustomFlywayMigrationInitializer.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("flywayMigrationInitializer", + "flyway"); + }); } @Test void whenCustomFlywayIsDefinedThenJooqDslContextDependsOnIt() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, - CustomFlyway.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("customFlyway"); - }); + this.contextRunner + .withUserConfiguration(EmbeddedDataSourceConfiguration.class, JooqConfiguration.class, CustomFlyway.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("customFlyway"); + }); } @Test void scriptPlaceholderPrefixIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.script-placeholder-prefix=SPP") - .run((context) -> assertThat( - context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderPrefix()) - .isEqualTo("SPP")); + .withPropertyValues("spring.flyway.script-placeholder-prefix=SPP") + .run((context) -> assertThat(context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderPrefix()) + .isEqualTo("SPP")); } @Test void scriptPlaceholderSuffixIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.script-placeholder-suffix=SPS") - .run((context) -> assertThat( - context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderSuffix()) - .isEqualTo("SPS")); + .withPropertyValues("spring.flyway.script-placeholder-suffix=SPS") + .run((context) -> assertThat(context.getBean(Flyway.class).getConfiguration().getScriptPlaceholderSuffix()) + .isEqualTo("SPS")); } @Test void containsResourceProviderCustomizer() { this.contextRunner.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) - .run((context) -> assertThat(context).hasSingleBean(ResourceProviderCustomizer.class)); + .run((context) -> assertThat(context).hasSingleBean(ResourceProviderCustomizer.class)); } @Test @@ -783,7 +795,8 @@ class FlywayAutoConfigurationTests { properties.put("configured", "manually"); properties.put("hibernate.transaction.jta.platform", NoJtaPlatform.INSTANCE); return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), properties, null) - .dataSource(dataSource).build(); + .dataSource(dataSource) + .build(); } } @@ -808,7 +821,8 @@ class FlywayAutoConfigurationTests { properties.put("configured", "manually"); properties.put("hibernate.transaction.jta.platform", NoJtaPlatform.INSTANCE); return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), properties, null) - .dataSource(this.dataSource).build(); + .dataSource(this.dataSource) + .build(); } } @@ -937,7 +951,8 @@ class FlywayAutoConfigurationTests { @Bean(destroyMethod = "shutdown") EmbeddedDatabase dataSource(DataSourceProperties properties) throws SQLException { EmbeddedDatabase database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) - .setName(getDatabaseName(properties)).build(); + .setName(getDatabaseName(properties)) + .build(); insertUser(database); return database; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java index 8c2dbc40be..3dafd06742 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/FlywayPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,11 +51,12 @@ class FlywayPropertiesTests { Configuration configuration = new FluentConfiguration(); assertThat(properties.isFailOnMissingLocations()).isEqualTo(configuration.isFailOnMissingLocations()); assertThat(properties.getLocations().stream().map(Location::new).toArray(Location[]::new)) - .isEqualTo(configuration.getLocations()); + .isEqualTo(configuration.getLocations()); assertThat(properties.getEncoding()).isEqualTo(configuration.getEncoding()); assertThat(properties.getConnectRetries()).isEqualTo(configuration.getConnectRetries()); - assertThat(properties.getConnectRetriesInterval()).extracting(Duration::getSeconds).extracting(Long::intValue) - .isEqualTo(configuration.getConnectRetriesInterval()); + assertThat(properties.getConnectRetriesInterval()).extracting(Duration::getSeconds) + .extracting(Long::intValue) + .isEqualTo(configuration.getConnectRetriesInterval()); assertThat(properties.getLockRetryCount()).isEqualTo(configuration.getLockRetryCount()); assertThat(properties.getDefaultSchema()).isEqualTo(configuration.getDefaultSchema()); assertThat(properties.getSchemas()).isEqualTo(Arrays.asList(configuration.getSchemas())); @@ -63,7 +64,7 @@ class FlywayPropertiesTests { assertThat(properties.getTable()).isEqualTo(configuration.getTable()); assertThat(properties.getBaselineDescription()).isEqualTo(configuration.getBaselineDescription()); assertThat(MigrationVersion.fromVersion(properties.getBaselineVersion())) - .isEqualTo(configuration.getBaselineVersion()); + .isEqualTo(configuration.getBaselineVersion()); assertThat(properties.getInstalledBy()).isEqualTo(configuration.getInstalledBy()); assertThat(properties.getPlaceholders()).isEqualTo(configuration.getPlaceholders()); assertThat(properties.getPlaceholderPrefix()).isEqualToIgnoringWhitespace(configuration.getPlaceholderPrefix()); @@ -73,7 +74,7 @@ class FlywayPropertiesTests { assertThat(properties.getSqlMigrationSuffixes()).containsExactly(configuration.getSqlMigrationSuffixes()); assertThat(properties.getSqlMigrationSeparator()).isEqualTo(configuration.getSqlMigrationSeparator()); assertThat(properties.getRepeatableSqlMigrationPrefix()) - .isEqualTo(configuration.getRepeatableSqlMigrationPrefix()); + .isEqualTo(configuration.getRepeatableSqlMigrationPrefix()); assertThat(properties.getTarget()).isEqualTo(configuration.getTarget()); assertThat(configuration.getInitSql()).isNull(); assertThat(properties.getInitSqls()).isEmpty(); @@ -132,7 +133,7 @@ class FlywayPropertiesTests { private void ignoreProperties(Map index, String... propertyNames) { for (String propertyName : propertyNames) { assertThat(index.remove(propertyName)).describedAs("Property to ignore should be present " + propertyName) - .isNotNull(); + .isNotNull(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessorTests.java index 669599ebdf..61f1a0aa11 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/flyway/ResourceProviderCustomizerBeanRegistrationAotProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class ResourceProviderCustomizerBeanRegistrationAotProcessorTests { @Test void beanRegistrationAotProcessorIsRegistered() { assertThat(AotServices.factories().load(BeanRegistrationAotProcessor.class)) - .anyMatch(ResourceProviderCustomizerBeanRegistrationAotProcessor.class::isInstance); + .anyMatch(ResourceProviderCustomizerBeanRegistrationAotProcessor.class::isInstance); } @Test @@ -62,7 +62,7 @@ class ResourceProviderCustomizerBeanRegistrationAotProcessorTests { RootBeanDefinition beanDefinition = new RootBeanDefinition(String.class); this.beanFactory.registerBeanDefinition("test", beanDefinition); BeanRegistrationAotContribution contribution = this.processor - .processAheadOfTime(RegisteredBean.of(this.beanFactory, "test")); + .processAheadOfTime(RegisteredBean.of(this.beanFactory, "test")); assertThat(contribution).isNull(); } @@ -90,7 +90,7 @@ class ResourceProviderCustomizerBeanRegistrationAotProcessorTests { TestCompiler.forSystem().with(generationContext).compile((compiled) -> { GenericApplicationContext freshApplicationContext = new GenericApplicationContext(); ApplicationContextInitializer initializer = compiled - .getInstance(ApplicationContextInitializer.class, className.toString()); + .getInstance(ApplicationContextInitializer.class, className.toString()); initializer.initialize(freshApplicationContext); freshContext.accept(freshApplicationContext); }); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java index 108ad43859..3a47775541 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; class FreeMarkerAutoConfigurationReactiveIntegrationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); @Test void defaultConfiguration() { @@ -87,20 +87,20 @@ class FreeMarkerAutoConfigurationReactiveIntegrationTests { @Test void customTemplateLoaderPath() { this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/custom-templates/") - .run((context) -> { - MockServerWebExchange exchange = render(context, "custom"); - String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); - assertThat(result).contains("custom"); - }); + .run((context) -> { + MockServerWebExchange exchange = render(context, "custom"); + String result = exchange.getResponse().getBodyAsString().block(Duration.ofSeconds(30)); + assertThat(result).contains("custom"); + }); } @SuppressWarnings("deprecation") @Test void customFreeMarkerSettings() { this.contextRunner.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope") - .run((context) -> assertThat( - context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) - .isEqualTo("yup,nope")); + .run((context) -> assertThat( + context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) + .isEqualTo("yup,nope")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java index 351b6cc98c..975478d8ae 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationServletIntegrationTests.java @@ -134,7 +134,7 @@ class FreeMarkerAutoConfigurationServletIntegrationTests { void customFreeMarkerSettings() { load("spring.freemarker.settings.boolean_format:yup,nope"); assertThat(this.context.getBean(FreeMarkerConfigurer.class).getConfiguration().getSetting("boolean_format")) - .isEqualTo("yup,nope"); + .isEqualTo("yup,nope"); } @Test @@ -168,8 +168,11 @@ class FreeMarkerAutoConfigurationServletIntegrationTests { load(FilterRegistrationOtherConfiguration.class, "spring.web.resources.chain.enabled:true"); Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(2); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); } @@ -181,8 +184,11 @@ class FreeMarkerAutoConfigurationServletIntegrationTests { load(FilterRegistrationResourceConfiguration.class, "spring.web.resources.chain.enabled:true"); Map beans = this.context.getBeansOfType(FilterRegistrationBean.class); assertThat(beans).hasSize(1); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", EnumSet.of(DispatcherType.INCLUDE)); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java index 6b60297a2b..77658ef5fb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class FreeMarkerAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(FreeMarkerAutoConfiguration.class)); @Test void renderNonWebAppTemplate() { @@ -57,9 +57,9 @@ class FreeMarkerAutoConfigurationTests { @Test void nonExistentTemplateLocation(CapturedOutput output) { this.contextRunner - .withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/does-not-exist/,classpath:/also-does-not-exist") - .run((context) -> assertThat(output).contains("Cannot find template location")); + .withPropertyValues("spring.freemarker.templateLoaderPath:" + + "classpath:/does-not-exist/,classpath:/also-does-not-exist") + .run((context) -> assertThat(output).contains("Cannot find template location")); } @Test @@ -67,17 +67,17 @@ class FreeMarkerAutoConfigurationTests { File emptyDirectory = new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory"); emptyDirectory.mkdirs(); this.contextRunner - .withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .withPropertyValues("spring.freemarker.templateLoaderPath:classpath:/empty-templates/empty-directory/") + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test void nonExistentLocationAndEmptyLocation(CapturedOutput output) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner - .withPropertyValues("spring.freemarker.templateLoaderPath:" - + "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .withPropertyValues("spring.freemarker.templateLoaderPath:" + + "classpath:/does-not-exist/,classpath:/empty-templates/empty-directory/") + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } public static class DataModel { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java index 5a6796888b..897c888f62 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -41,41 +41,47 @@ class FreeMarkerTemplateAvailabilityProviderTests { @Test void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isFalse(); + this.resourceLoader)) + .isFalse(); } @Test void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.freemarker.template-loader-path", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { this.environment.setProperty("spring.freemarker.template-loader-path[0]", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.freemarker.prefix", "prefix/"); assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.freemarker.suffix", ".freemarker"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java index cd8391f723..7e54b9a1e9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/DefaultGraphQlSchemaConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,30 +42,32 @@ class DefaultGraphQlSchemaConditionTests { this.contextRunner.withUserConfiguration(TestingConfiguration.class).run((context) -> { didMatch(context); assertThat(conditionReportMessage(context)).contains("@ConditionalOnGraphQlSchema found schemas") - .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); + .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); }); } @Test void matchesWhenCustomizerIsDetected() { this.contextRunner.withUserConfiguration(CustomCustomizerConfiguration.class, TestingConfiguration.class) - .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing").run((context) -> { - didMatch(context); - assertThat(conditionReportMessage(context)).contains( - "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") - .contains("@ConditionalOnGraphQlSchema found customizer myBuilderCuystomizer"); - }); + .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing") + .run((context) -> { + didMatch(context); + assertThat(conditionReportMessage(context)).contains( + "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") + .contains("@ConditionalOnGraphQlSchema found customizer myBuilderCuystomizer"); + }); } @Test void doesNotMatchWhenBothAreMissing() { this.contextRunner.withUserConfiguration(TestingConfiguration.class) - .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing").run((context) -> { - assertThat(context).doesNotHaveBean("success"); - assertThat(conditionReportMessage(context)).contains( - "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") - .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); - }); + .withPropertyValues("spring.graphql.schema.locations=classpath:graphql/missing") + .run((context) -> { + assertThat(context).doesNotHaveBean("success"); + assertThat(conditionReportMessage(context)).contains( + "@ConditionalOnGraphQlSchema did not find schema files in locations 'classpath:graphql/missing/'") + .contains("@ConditionalOnGraphQlSchema did not find GraphQlSourceBuilderCustomizer"); + }); } private void didMatch(AssertableApplicationContext context) { @@ -75,7 +77,9 @@ class DefaultGraphQlSchemaConditionTests { private String conditionReportMessage(AssertableApplicationContext context) { Collection conditionAndOutcomes = ConditionEvaluationReport - .get(context.getSourceApplicationContext().getBeanFactory()).getConditionAndOutcomesBySource().values(); + .get(context.getSourceApplicationContext().getBeanFactory()) + .getConditionAndOutcomesBySource() + .values(); return conditionAndOutcomes.iterator().next().iterator().next().getOutcome().getMessage(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java index 06425f5d09..908147d0bf 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/GraphQlAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ import static org.mockito.Mockito.mock; class GraphQlAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class)); @Test void shouldContributeDefaultBeans() { @@ -79,7 +79,7 @@ class GraphQlAutoConfigurationTests { @Test void shouldBackoffWhenSchemaFileIsMissing() { this.contextRunner.withPropertyValues("spring.graphql.schema.locations:classpath:missing/") - .run((context) -> assertThat(context).hasNotFailed().doesNotHaveBean(GraphQlSource.class)); + .run((context) -> assertThat(context).hasNotFailed().doesNotHaveBean(GraphQlSource.class)); } @Test @@ -93,13 +93,13 @@ class GraphQlAutoConfigurationTests { @Test void shouldScanLocationsWithCustomExtension() { this.contextRunner.withPropertyValues("spring.graphql.schema.file-extensions:.graphqls,.custom") - .run((context) -> { - assertThat(context).hasSingleBean(GraphQlSource.class); - GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); - GraphQLSchema schema = graphQlSource.schema(); - assertThat(schema.getObjectType("Book")).isNotNull(); - assertThat(schema.getObjectType("Person")).isNotNull(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(GraphQlSource.class); + GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); + GraphQLSchema schema = graphQlSource.schema(); + assertThat(schema.getObjectType("Book")).isNotNull(); + assertThat(schema.getObjectType("Person")).isNotNull(); + }); } @Test @@ -116,8 +116,8 @@ class GraphQlAutoConfigurationTests { GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); GraphQL graphQL = graphQlSource.graphQl(); assertThat(graphQL.getQueryStrategy()).extracting("dataFetcherExceptionHandler") - .satisfies((exceptionHandler) -> assertThat(exceptionHandler.getClass().getName()) - .endsWith("ExceptionResolversExceptionHandler")); + .satisfies((exceptionHandler) -> assertThat(exceptionHandler.getClass().getName()) + .endsWith("ExceptionResolversExceptionHandler")); }); } @@ -127,9 +127,10 @@ class GraphQlAutoConfigurationTests { GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); Instrumentation customInstrumentation = context.getBean("customInstrumentation", Instrumentation.class); GraphQL graphQL = graphQlSource.graphQl(); - assertThat(graphQL).extracting("instrumentation").isInstanceOf(ChainedInstrumentation.class) - .extracting("instrumentations", InstanceOfAssertFactories.iterable(Instrumentation.class)) - .contains(customInstrumentation); + assertThat(graphQL).extracting("instrumentation") + .isInstanceOf(ChainedInstrumentation.class) + .extracting("instrumentations", InstanceOfAssertFactories.iterable(Instrumentation.class)) + .contains(customInstrumentation); }); } @@ -137,7 +138,7 @@ class GraphQlAutoConfigurationTests { void shouldApplyRuntimeWiringConfigurers() { this.contextRunner.withUserConfiguration(RuntimeWiringConfigurerConfiguration.class).run((context) -> { RuntimeWiringConfigurerConfiguration.CustomRuntimeWiringConfigurer configurer = context - .getBean(RuntimeWiringConfigurerConfiguration.CustomRuntimeWiringConfigurer.class); + .getBean(RuntimeWiringConfigurerConfiguration.CustomRuntimeWiringConfigurer.class); assertThat(configurer.applied).isTrue(); }); } @@ -146,7 +147,7 @@ class GraphQlAutoConfigurationTests { void shouldApplyGraphQlSourceBuilderCustomizer() { this.contextRunner.withUserConfiguration(GraphQlSourceBuilderCustomizerConfiguration.class).run((context) -> { GraphQlSourceBuilderCustomizerConfiguration.CustomGraphQlSourceBuilderCustomizer customizer = context - .getBean(GraphQlSourceBuilderCustomizerConfiguration.CustomGraphQlSourceBuilderCustomizer.class); + .getBean(GraphQlSourceBuilderCustomizerConfiguration.CustomGraphQlSourceBuilderCustomizer.class); assertThat(customizer.applied).isTrue(); }); } @@ -166,23 +167,22 @@ class GraphQlAutoConfigurationTests { GraphQlSource graphQlSource = context.getBean(GraphQlSource.class); GraphQLSchema schema = graphQlSource.schema(); assertThat(schema.getCodeRegistry().getFieldVisibility()) - .isInstanceOf(NoIntrospectionGraphqlFieldVisibility.class); + .isInstanceOf(NoIntrospectionGraphqlFieldVisibility.class); }); } @Test void shouldConfigureCustomBatchLoaderRegistry() { this.contextRunner - .withBean("customBatchLoaderRegistry", BatchLoaderRegistry.class, () -> mock(BatchLoaderRegistry.class)) - .run((context) -> { - assertThat(context).hasSingleBean(BatchLoaderRegistry.class); - assertThat(context.getBean("customBatchLoaderRegistry")) - .isSameAs(context.getBean(BatchLoaderRegistry.class)); - assertThat(context.getBean(ExecutionGraphQlService.class)) - .extracting("dataLoaderRegistrars", - InstanceOfAssertFactories.list(DataLoaderRegistrar.class)) - .containsOnly(context.getBean(BatchLoaderRegistry.class)); - }); + .withBean("customBatchLoaderRegistry", BatchLoaderRegistry.class, () -> mock(BatchLoaderRegistry.class)) + .run((context) -> { + assertThat(context).hasSingleBean(BatchLoaderRegistry.class); + assertThat(context.getBean("customBatchLoaderRegistry")) + .isSameAs(context.getBean(BatchLoaderRegistry.class)); + assertThat(context.getBean(ExecutionGraphQlService.class)) + .extracting("dataLoaderRegistrars", InstanceOfAssertFactories.list(DataLoaderRegistrar.class)) + .containsOnly(context.getBean(BatchLoaderRegistry.class)); + }); } @Test @@ -198,9 +198,9 @@ class GraphQlAutoConfigurationTests { @Bean GraphQlSource.SchemaResourceBuilder customGraphQlSourceBuilder() { - return GraphQlSource.schemaResourceBuilder().schemaResources( - new ClassPathResource("graphql/schema.graphqls"), - new ClassPathResource("graphql/types/book.graphqls")); + return GraphQlSource.schemaResourceBuilder() + .schemaResources(new ClassPathResource("graphql/schema.graphqls"), + new ClassPathResource("graphql/types/book.graphqls")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java index a8c4c1d6f8..0998bfe10a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQueryByExampleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,18 +46,21 @@ class GraphQlQueryByExampleAutoConfigurationTests { private static final Book book = new Book("42", "Test title", 42, "Test Author"); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQueryByExampleAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration( + AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQueryByExampleAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryByExampleRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); ExecutionGraphQlServiceTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java index 27e4b5cb0a..3bbb3df8a0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlQuerydslAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,18 +47,21 @@ class GraphQlQuerydslAutoConfigurationTests { private static final Book book = new Book("42", "Test title", 42, "Test Author"); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQuerydslAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration( + AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlQuerydslAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryDslRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); GraphQlTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java index 48c9be1cab..8f4a94a410 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQueryByExampleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,18 +46,21 @@ class GraphQlReactiveQueryByExampleAutoConfigurationTests { private static final Mono bookPublisher = Mono.just(new Book("42", "Test title", 42, "Test Author")); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class, - GraphQlReactiveQueryByExampleAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class, + GraphQlReactiveQueryByExampleAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryByExampleRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); GraphQlTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java index d2a33df2fc..9901d096cb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/data/GraphQlReactiveQuerydslAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,18 +46,21 @@ class GraphQlReactiveQuerydslAutoConfigurationTests { private static final Mono bookPublisher = Mono.just(new Book("42", "Test title", 42, "Test Author")); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GraphQlAutoConfiguration.class, - GraphQlReactiveQuerydslAutoConfiguration.class)) - .withUserConfiguration(MockRepositoryConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration( + AutoConfigurations.of(GraphQlAutoConfiguration.class, GraphQlReactiveQuerydslAutoConfiguration.class)) + .withUserConfiguration(MockRepositoryConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void shouldRegisterDataFetcherForQueryDslRepositories() { this.contextRunner.run((context) -> { ExecutionGraphQlService graphQlService = context.getBean(ExecutionGraphQlService.class); GraphQlTester graphQlTester = ExecutionGraphQlServiceTester.create(graphQlService); - graphQlTester.document("{ bookById(id: 1) {name}}").execute().path("bookById.name").entity(String.class) - .isEqualTo("Test title"); + graphQlTester.document("{ bookById(id: 1) {name}}") + .execute() + .path("bookById.name") + .entity(String.class) + .isEqualTo("Test title"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java index 47e325bc85..f695221ab0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,28 +60,36 @@ class GraphQlWebFluxAutoConfigurationTests { private static final String BASE_URL = "https://spring.example.org/"; private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, - GraphQlWebFluxAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) - .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.graphiql.enabled=true", - "spring.graphql.schema.printer.enabled=true", - "spring.graphql.cors.allowed-origins=https://example.com", - "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, + GraphQlWebFluxAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) + .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.graphiql.enabled=true", + "spring.graphql.schema.printer.enabled=true", "spring.graphql.cors.allowed-origins=https://example.com", + "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); @Test void shouldContributeDefaultBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(GraphQlHttpHandler.class) - .hasSingleBean(WebGraphQlHandler.class).doesNotHaveBean(GraphQlWebSocketHandler.class)); + .hasSingleBean(WebGraphQlHandler.class) + .doesNotHaveBean(GraphQlWebSocketHandler.class)); } @Test void simpleQueryShouldWork() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; - client.post().uri("/graphql").bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk() - .expectHeader().contentType(MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE).expectBody() - .jsonPath("data.bookById.name").isEqualTo("GraphQL for beginners"); + client.post() + .uri("/graphql") + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE) + .expectBody() + .jsonPath("data.bookById.name") + .isEqualTo("GraphQL for beginners"); }); } @@ -89,8 +97,13 @@ class GraphQlWebFluxAutoConfigurationTests { void httpGetQueryShouldBeSupported() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; - client.get().uri("/graphql?query={query}", "{ \"query\": \"" + query + "\"}").exchange().expectStatus() - .isEqualTo(HttpStatus.METHOD_NOT_ALLOWED).expectHeader().valueEquals("Allow", "POST"); + client.get() + .uri("/graphql?query={query}", "{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.METHOD_NOT_ALLOWED) + .expectHeader() + .valueEquals("Allow", "POST"); }); } @@ -111,25 +124,49 @@ class GraphQlWebFluxAutoConfigurationTests { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; - client.post().uri("/graphql").bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk() - .expectHeader().valueEquals("X-Custom-Header", "42"); + client.post() + .uri("/graphql") + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals("X-Custom-Header", "42"); }); } @Test void shouldExposeSchemaEndpoint() { - testWithWebClient((client) -> client.get().uri("/graphql/schema").accept(MediaType.ALL).exchange() - .expectStatus().isOk().expectHeader().contentType(MediaType.TEXT_PLAIN).expectBody(String.class) - .value(containsString("type Book"))); + testWithWebClient((client) -> client.get() + .uri("/graphql/schema") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.TEXT_PLAIN) + .expectBody(String.class) + .value(containsString("type Book"))); } @Test void shouldExposeGraphiqlEndpoint() { testWithWebClient((client) -> { - client.get().uri("/graphiql").exchange().expectStatus().is3xxRedirection().expectHeader() - .location("https://spring.example.org/graphiql?path=/graphql"); - client.get().uri("/graphiql?path=/graphql").accept(MediaType.ALL).exchange().expectStatus().isOk() - .expectHeader().contentType(MediaType.TEXT_HTML); + client.get() + .uri("/graphiql") + .exchange() + .expectStatus() + .is3xxRedirection() + .expectHeader() + .location("https://spring.example.org/graphiql?path=/graphql"); + client.get() + .uri("/graphiql?path=/graphql") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentType(MediaType.TEXT_HTML); }); } @@ -138,18 +175,25 @@ class GraphQlWebFluxAutoConfigurationTests { testWithWebClient((client) -> { String query = "{" + " bookById(id: \\\"book-1\\\"){ " + " id" + " name" + " pageCount" + " author" + " }" + "}"; - client.post().uri("/graphql").bodyValue("{ \"query\": \"" + query + "\"}") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") - .header(HttpHeaders.ORIGIN, "https://example.com").exchange().expectStatus().isOk().expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com").expectHeader() - .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); + client.post() + .uri("/graphql") + .bodyValue("{ \"query\": \"" + query + "\"}") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") + .header(HttpHeaders.ORIGIN, "https://example.com") + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com") + .expectHeader() + .valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); }); } @Test void shouldConfigureWebSocketBeans() { this.contextRunner.withPropertyValues("spring.graphql.websocket.path=/ws") - .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); } @Test @@ -172,11 +216,14 @@ class GraphQlWebFluxAutoConfigurationTests { private void testWithWebClient(Consumer consumer) { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context).configureClient() - .defaultHeaders((headers) -> { - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_GRAPHQL_RESPONSE)); - }).baseUrl(BASE_URL).build(); + WebTestClient client = WebTestClient.bindToApplicationContext(context) + .configureClient() + .defaultHeaders((headers) -> { + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_GRAPHQL_RESPONSE)); + }) + .baseUrl(BASE_URL) + .build(); consumer.accept(client); }); } @@ -186,8 +233,8 @@ class GraphQlWebFluxAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher() { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - GraphQlTestDataFetchers.getBookByIdDataFetcher())); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", GraphQlTestDataFetchers.getBookByIdDataFetcher())); } } @@ -198,7 +245,7 @@ class GraphQlWebFluxAutoConfigurationTests { @Bean WebGraphQlInterceptor customWebGraphQlInterceptor() { return (webInput, interceptorChain) -> interceptorChain.next(webInput) - .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); + .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java index 827a47e495..69f664ef0e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/GraphQlRSocketAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,17 +56,17 @@ import static org.assertj.core.api.Assertions.assertThat; class GraphQlRSocketAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class) - .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); + .withConfiguration( + AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, + GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class) + .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); @Test void shouldContributeDefaultBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(GraphQlRSocketHandler.class) - .hasSingleBean(GraphQlRSocketController.class)); + .hasSingleBean(GraphQlRSocketController.class)); } @Test @@ -81,45 +81,52 @@ class GraphQlRSocketAutoConfigurationTests { private void assertThatSimpleQueryWorks(RSocketGraphQlClient client) { String document = "{ bookById(id: \"book-1\"){ id name pageCount author } }"; - String bookName = client.document(document).retrieve("bookById.name").toEntity(String.class) - .block(Duration.ofSeconds(5)); + String bookName = client.document(document) + .retrieve("bookById.name") + .toEntity(String.class) + .block(Duration.ofSeconds(5)); assertThat(bookName).isEqualTo("GraphQL for beginners"); } private void testWithRSocketTcp(Consumer consumer) { ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class).withPropertyValues( - "spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); + .withConfiguration( + AutoConfigurations.of(JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, + GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class) + .withPropertyValues("spring.main.web-application-type=reactive", "spring.graphql.rsocket.mapping=graphql"); contextRunner.withInitializer(new RSocketPortInfoApplicationContextInitializer()) - .withPropertyValues("spring.rsocket.server.port=0").run((context) -> { - String serverPort = context.getEnvironment().getProperty("local.rsocket.server.port"); - RSocketGraphQlClient client = RSocketGraphQlClient.builder() - .tcp("localhost", Integer.parseInt(serverPort)).route("graphql").build(); - consumer.accept(client); - }); + .withPropertyValues("spring.rsocket.server.port=0") + .run((context) -> { + String serverPort = context.getEnvironment().getProperty("local.rsocket.server.port"); + RSocketGraphQlClient client = RSocketGraphQlClient.builder() + .tcp("localhost", Integer.parseInt(serverPort)) + .route("graphql") + .build(); + consumer.accept(client); + }); } private void testWithRSocketWebSocket(Consumer consumer) { ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( - AnnotationConfigReactiveWebServerApplicationContext::new).withConfiguration( - AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) - .withInitializer(new ServerPortInfoApplicationContextInitializer()) - .withUserConfiguration(DataFetchersConfiguration.class, NettyServerConfiguration.class) - .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0", - "spring.graphql.rsocket.mapping=graphql", "spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket"); + AnnotationConfigReactiveWebServerApplicationContext::new) + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + JacksonAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketServerAutoConfiguration.class, + GraphQlAutoConfiguration.class, GraphQlRSocketAutoConfiguration.class)) + .withInitializer(new ServerPortInfoApplicationContextInitializer()) + .withUserConfiguration(DataFetchersConfiguration.class, NettyServerConfiguration.class) + .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0", + "spring.graphql.rsocket.mapping=graphql", "spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket"); contextRunner.run((context) -> { String serverPort = context.getEnvironment().getProperty("local.server.port"); RSocketGraphQlClient client = RSocketGraphQlClient.builder() - .webSocket(URI.create("ws://localhost:" + serverPort + "/rsocket")).route("graphql").build(); + .webSocket(URI.create("ws://localhost:" + serverPort + "/rsocket")) + .route("graphql") + .build(); consumer.accept(client); }); } @@ -141,8 +148,8 @@ class GraphQlRSocketAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher() { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - GraphQlTestDataFetchers.getBookByIdDataFetcher())); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", GraphQlTestDataFetchers.getBookByIdDataFetcher())); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java index f46a2d25d5..e320690455 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/rsocket/RSocketGraphQlClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,8 +38,8 @@ class RSocketGraphQlClientAutoConfigurationTests { private static final RSocketGraphQlClient.Builder builderInstance = RSocketGraphQlClient.builder(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class, - RSocketRequesterAutoConfiguration.class, RSocketGraphQlClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RSocketStrategiesAutoConfiguration.class, + RSocketRequesterAutoConfiguration.class, RSocketGraphQlClientAutoConfiguration.class)); @Test void shouldCreateBuilder() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java index 30ded29aed..f388ac3541 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebFluxSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2022 the original author or authors. + * Copyright 2020-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. @@ -64,26 +64,34 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { private static final String BASE_URL = "https://spring.example.org/graphql"; private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, - GraphQlWebFluxAutoConfiguration.class, GraphQlWebFluxSecurityAutoConfiguration.class, - ReactiveSecurityAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) - .withPropertyValues("spring.main.web-application-type=reactive"); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + CodecsAutoConfiguration.class, JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, + GraphQlWebFluxAutoConfiguration.class, GraphQlWebFluxSecurityAutoConfiguration.class, + ReactiveSecurityAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) + .withPropertyValues("spring.main.web-application-type=reactive"); @Test void contributesExceptionResolver() { - this.contextRunner.run( - (context) -> assertThat(context).hasSingleBean(ReactiveSecurityDataFetcherExceptionResolver.class)); + this.contextRunner + .run((context) -> assertThat(context).hasSingleBean(ReactiveSecurityDataFetcherExceptionResolver.class)); } @Test void anonymousUserShouldBeUnauthorized() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; - client.post().uri("").bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk() - .expectBody().jsonPath("data.bookById.name").doesNotExist() - .jsonPath("errors[0].extensions.classification").isEqualTo(ErrorType.UNAUTHORIZED.toString()); + client.post() + .uri("") + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("data.bookById.name") + .doesNotExist() + .jsonPath("errors[0].extensions.classification") + .isEqualTo(ErrorType.UNAUTHORIZED.toString()); }); } @@ -91,20 +99,31 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { void authenticatedUserShouldGetData() { testWithWebClient((client) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; - client.post().uri("").headers((headers) -> headers.setBasicAuth("rob", "rob")) - .bodyValue("{ \"query\": \"" + query + "\"}").exchange().expectStatus().isOk().expectBody() - .jsonPath("data.bookById.name").isEqualTo("GraphQL for beginners") - .jsonPath("errors[0].extensions.classification").doesNotExist(); + client.post() + .uri("") + .headers((headers) -> headers.setBasicAuth("rob", "rob")) + .bodyValue("{ \"query\": \"" + query + "\"}") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("data.bookById.name") + .isEqualTo("GraphQL for beginners") + .jsonPath("errors[0].extensions.classification") + .doesNotExist(); }); } private void testWithWebClient(Consumer consumer) { this.contextRunner.run((context) -> { - WebTestClient client = WebTestClient.bindToApplicationContext(context).configureClient() - .defaultHeaders((headers) -> { - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - }).baseUrl(BASE_URL).build(); + WebTestClient client = WebTestClient.bindToApplicationContext(context) + .configureClient() + .defaultHeaders((headers) -> { + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + }) + .baseUrl(BASE_URL) + .build(); consumer.accept(client); }); } @@ -114,8 +133,8 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher(BookService bookService) { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - (env) -> bookService.getBookdById(env.getArgument("id")))); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", (env) -> bookService.getBookdById(env.getArgument("id")))); } @Bean @@ -143,10 +162,11 @@ class GraphQlWebFluxSecurityAutoConfigurationTests { @Bean SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) { return http.csrf((spec) -> spec.disable()) - // Demonstrate that method security works - // Best practice to use both for defense in depth - .authorizeExchange((requests) -> requests.anyExchange().permitAll()).httpBasic(withDefaults()) - .build(); + // Demonstrate that method security works + // Best practice to use both for defense in depth + .authorizeExchange((requests) -> requests.anyExchange().permitAll()) + .httpBasic(withDefaults()) + .build(); } @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java index 816909f2f4..a7deb9a3af 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/security/GraphQlWebMvcSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2022 the original author or authors. + * Copyright 2020-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. @@ -67,18 +67,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class GraphQlWebMvcSecurityAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, JacksonAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class, - GraphQlWebMvcSecurityAutoConfiguration.class, SecurityAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) - .withPropertyValues("spring.main.web-application-type=servlet"); + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class, + GraphQlWebMvcSecurityAutoConfiguration.class, SecurityAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, SecurityConfig.class) + .withPropertyValues("spring.main.web-application-type=servlet"); @Test void contributesSecurityComponents() { this.contextRunner - .run((context) -> assertThat(context).hasSingleBean(SecurityDataFetcherExceptionResolver.class)); + .run((context) -> assertThat(context).hasSingleBean(SecurityDataFetcherExceptionResolver.class)); } @Test @@ -86,10 +85,11 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; MvcResult result = mockMvc.perform(post("/graphql").content("{\"query\": \"" + query + "\"}")).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("data.bookById.name").doesNotExist()).andExpect( - jsonPath("errors[0].extensions.classification").value(ErrorType.UNAUTHORIZED.toString())); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("data.bookById.name").doesNotExist()) + .andExpect(jsonPath("errors[0].extensions.classification").value(ErrorType.UNAUTHORIZED.toString())); }); } @@ -98,11 +98,13 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author }}"; MvcResult result = mockMvc - .perform(post("/graphql").content("{\"query\": \"" + query + "\"}").with(user("rob"))).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")) - .andExpect(jsonPath("errors").doesNotExist()); + .perform(post("/graphql").content("{\"query\": \"" + query + "\"}").with(user("rob"))) + .andReturn(); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")) + .andExpect(jsonPath("errors").doesNotExist()); }); } @@ -111,8 +113,9 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { this.contextRunner.run((context) -> { MediaType mediaType = MediaType.APPLICATION_JSON; MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context) - .defaultRequest(post("/graphql").contentType(mediaType).accept(mediaType)).apply(springSecurity()) - .build(); + .defaultRequest(post("/graphql").contentType(mediaType).accept(mediaType)) + .apply(springSecurity()) + .build(); mockMvcConsumer.accept(mockMvc); }); } @@ -128,8 +131,8 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher(BookService bookService) { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - (env) -> bookService.getBookdById(env.getArgument("id")))); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", (env) -> bookService.getBookdById(env.getArgument("id")))); } @Bean @@ -158,10 +161,11 @@ class GraphQlWebMvcSecurityAutoConfigurationTests { @Bean DefaultSecurityFilterChain springWebFilterChain(HttpSecurity http) throws Exception { return http.csrf((c) -> c.disable()) - // Demonstrate that method security works - // Best practice to use both for defense in depth - .authorizeHttpRequests((requests) -> requests.anyRequest().permitAll()).httpBasic(withDefaults()) - .build(); + // Demonstrate that method security works + // Best practice to use both for defense in depth + .authorizeHttpRequests((requests) -> requests.anyRequest().permitAll()) + .httpBasic(withDefaults()) + .build(); } @Bean diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java index 9eb187b0eb..e99c778746 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/graphql/servlet/GraphQlWebMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -65,20 +65,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. class GraphQlWebMvcAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, JacksonAutoConfiguration.class, - GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class)) - .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) - .withPropertyValues("spring.main.web-application-type=servlet", "spring.graphql.graphiql.enabled=true", - "spring.graphql.schema.printer.enabled=true", - "spring.graphql.cors.allowed-origins=https://example.com", - "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); + .withConfiguration(AutoConfigurations.of(DispatcherServletAutoConfiguration.class, + WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, + JacksonAutoConfiguration.class, GraphQlAutoConfiguration.class, GraphQlWebMvcAutoConfiguration.class)) + .withUserConfiguration(DataFetchersConfiguration.class, CustomWebInterceptor.class) + .withPropertyValues("spring.main.web-application-type=servlet", "spring.graphql.graphiql.enabled=true", + "spring.graphql.schema.printer.enabled=true", "spring.graphql.cors.allowed-origins=https://example.com", + "spring.graphql.cors.allowed-methods=POST", "spring.graphql.cors.allow-credentials=true"); @Test void shouldContributeDefaultBeans() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(GraphQlHttpHandler.class) - .hasSingleBean(WebGraphQlHandler.class).doesNotHaveBean(GraphQlWebSocketHandler.class)); + .hasSingleBean(WebGraphQlHandler.class) + .doesNotHaveBean(GraphQlWebSocketHandler.class)); } @Test @@ -86,9 +85,10 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; MvcResult result = mockMvc.perform(post("/graphql").content("{\"query\": \"" + query + "\"}")).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_GRAPHQL_RESPONSE)) - .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_GRAPHQL_RESPONSE)) + .andExpect(jsonPath("data.bookById.name").value("GraphQL for beginners")); }); } @@ -97,7 +97,8 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; mockMvc.perform(get("/graphql?query={query}", "{\"query\": \"" + query + "\"}")) - .andExpect(status().isMethodNotAllowed()).andExpect(header().string("Allow", "POST")); + .andExpect(status().isMethodNotAllowed()) + .andExpect(header().string("Allow", "POST")); }); } @@ -116,25 +117,29 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{ bookById(id: \\\"book-1\\\"){ id name pageCount author } }"; MvcResult result = mockMvc.perform(post("/graphql").content("{\"query\": \"" + query + "\"}")).andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(header().string("X-Custom-Header", "42")); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(header().string("X-Custom-Header", "42")); }); } @Test void shouldExposeSchemaEndpoint() { - testWith((mockMvc) -> mockMvc.perform(get("/graphql/schema")).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.TEXT_PLAIN)) - .andExpect(content().string(Matchers.containsString("type Book")))); + testWith((mockMvc) -> mockMvc.perform(get("/graphql/schema")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.TEXT_PLAIN)) + .andExpect(content().string(Matchers.containsString("type Book")))); } @Test void shouldExposeGraphiqlEndpoint() { testWith((mockMvc) -> { - mockMvc.perform(get("/graphiql")).andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrl("http://localhost/graphiql?path=/graphql")); - mockMvc.perform(get("/graphiql?path=/graphql")).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.TEXT_HTML)); + mockMvc.perform(get("/graphiql")) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("http://localhost/graphiql?path=/graphql")); + mockMvc.perform(get("/graphiql?path=/graphql")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.TEXT_HTML)); }); } @@ -143,20 +148,22 @@ class GraphQlWebMvcAutoConfigurationTests { testWith((mockMvc) -> { String query = "{" + " bookById(id: \\\"book-1\\\"){ " + " id" + " name" + " pageCount" + " author" + " }" + "}"; - MvcResult result = mockMvc.perform(post("/graphql") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") - .header(HttpHeaders.ORIGIN, "https://example.com").content("{\"query\": \"" + query + "\"}")) - .andReturn(); - mockMvc.perform(asyncDispatch(result)).andExpect(status().isOk()) - .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com")) - .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); + MvcResult result = mockMvc + .perform(post("/graphql").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") + .header(HttpHeaders.ORIGIN, "https://example.com") + .content("{\"query\": \"" + query + "\"}")) + .andReturn(); + mockMvc.perform(asyncDispatch(result)) + .andExpect(status().isOk()) + .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com")) + .andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); }); } @Test void shouldConfigureWebSocketBeans() { this.contextRunner.withPropertyValues("spring.graphql.websocket.path=/ws") - .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(GraphQlWebSocketHandler.class)); } @Test @@ -179,8 +186,10 @@ class GraphQlWebMvcAutoConfigurationTests { private void testWith(MockMvcConsumer mockMvcConsumer) { this.contextRunner.run((context) -> { - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).defaultRequest(post("/graphql") - .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_GRAPHQL_RESPONSE)).build(); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context) + .defaultRequest(post("/graphql").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_GRAPHQL_RESPONSE)) + .build(); mockMvcConsumer.accept(mockMvc); }); } @@ -196,8 +205,8 @@ class GraphQlWebMvcAutoConfigurationTests { @Bean RuntimeWiringConfigurer bookDataFetcher() { - return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("bookById", - GraphQlTestDataFetchers.getBookByIdDataFetcher())); + return (builder) -> builder.type(TypeRuntimeWiring.newTypeWiring("Query") + .dataFetcher("bookById", GraphQlTestDataFetchers.getBookByIdDataFetcher())); } } @@ -208,7 +217,7 @@ class GraphQlWebMvcAutoConfigurationTests { @Bean WebGraphQlInterceptor customWebGraphQlInterceptor() { return (webInput, interceptorChain) -> interceptorChain.next(webInput) - .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); + .doOnNext((output) -> output.getResponseHeaders().add("X-Custom-Header", "42")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java index 2a9b25f19d..ddea016a6f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfigurationTests.java @@ -162,7 +162,8 @@ class GroovyTemplateAutoConfigurationTests { MarkupTemplateEngine engine = config.getTemplateEngine(); Writer writer = new StringWriter(); engine.createTemplate(new ClassPathResource("templates/message.tpl").getFile()) - .make(new HashMap(Collections.singletonMap("greeting", "Hello World"))).writeTo(writer); + .make(new HashMap(Collections.singletonMap("greeting", "Hello World"))) + .writeTo(writer); assertThat(writer.toString()).contains("Hello World"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java index 4f704681bc..70849ec751 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,41 +41,47 @@ class GroovyTemplateAvailabilityProviderTests { @Test void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isFalse(); + this.resourceLoader)) + .isFalse(); } @Test void availabilityOfTemplateWithCustomLoaderPath() { this.environment.setProperty("spring.groovy.template.resource-loader-path", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomLoaderPathConfiguredAsAList() { this.environment.setProperty("spring.groovy.template.resource-loader-path[0]", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.groovy.template.prefix", "prefix/"); assertThat(this.provider.isTemplateAvailable("prefixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.groovy.template.suffix", ".groovytemplate"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java index 1072fd28d8..9084e4a494 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/gson/GsonAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; class GsonAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)); @Test void gsonRegistration() { @@ -70,10 +70,10 @@ class GsonAutoConfigurationTests { @Test void excludeFieldsWithoutExposeAnnotation() { this.contextRunner.withPropertyValues("spring.gson.exclude-fields-without-expose-annotation:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); - }); + .run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isEqualTo("{}"); + }); } @Test @@ -95,12 +95,12 @@ class GsonAutoConfigurationTests { @Test void enableComplexMapKeySerialization() { this.contextRunner.withPropertyValues("spring.gson.enable-complex-map-key-serialization:true") - .run((context) -> { - Gson gson = context.getBean(Gson.class); - Map original = new LinkedHashMap<>(); - original.put(new DataObject(), "a"); - assertThat(gson.toJson(original)).isEqualTo("[[{\"data\":1},\"a\"]]"); - }); + .run((context) -> { + Gson gson = context.getBean(Gson.class); + Map original = new LinkedHashMap<>(); + original.put(new DataObject(), "a"); + assertThat(gson.toJson(original)).isEqualTo("[[{\"data\":1},\"a\"]]"); + }); } @Test @@ -124,10 +124,10 @@ class GsonAutoConfigurationTests { @Test void withLongSerializationPolicy() { this.contextRunner.withPropertyValues("spring.gson.long-serialization-policy:" + LongSerializationPolicy.STRING) - .run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":\"1\"}"); - }); + .run((context) -> { + Gson gson = context.getBean(Gson.class); + assertThat(gson.toJson(new DataObject())).isEqualTo("{\"data\":\"1\"}"); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java index 48b391af2f..f478262c81 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ import static org.mockito.Mockito.mock; class H2ConsoleAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(H2ConsoleAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(H2ConsoleAutoConfiguration.class)); @Test void consoleIsDisabledByDefault() { @@ -77,67 +77,72 @@ class H2ConsoleAutoConfigurationTests { @Test void customPathMustBeginWithASlash() { this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.path=custom") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class).cause() - .isInstanceOf(ConfigurationPropertiesBindException.class).cause() - .isInstanceOf(BindException.class) - .hasMessageContaining("Failed to bind properties under 'spring.h2.console'"); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) + .cause() + .isInstanceOf(ConfigurationPropertiesBindException.class) + .cause() + .isInstanceOf(BindException.class) + .hasMessageContaining("Failed to bind properties under 'spring.h2.console'"); + }); } @Test void customPathWithTrailingSlash() { this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.path=/custom/") - .run((context) -> { - assertThat(context).hasSingleBean(ServletRegistrationBean.class); - ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); - assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); + assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); + }); } @Test void customPath() { this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.path=/custom") - .run((context) -> { - assertThat(context).hasSingleBean(ServletRegistrationBean.class); - ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); - assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); + assertThat(registrationBean.getUrlMappings()).contains("/custom/*"); + }); } @Test void customInitParameters() { - this.contextRunner.withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.settings.trace=true", - "spring.h2.console.settings.web-allow-others=true", - "spring.h2.console.settings.web-admin-password=abcd").run((context) -> { - assertThat(context).hasSingleBean(ServletRegistrationBean.class); - ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); - assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); - assertThat(registrationBean.getInitParameters()).containsEntry("trace", ""); - assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", ""); - assertThat(registrationBean.getInitParameters()).containsEntry("webAdminPassword", "abcd"); - }); + this.contextRunner + .withPropertyValues("spring.h2.console.enabled=true", "spring.h2.console.settings.trace=true", + "spring.h2.console.settings.web-allow-others=true", + "spring.h2.console.settings.web-admin-password=abcd") + .run((context) -> { + assertThat(context).hasSingleBean(ServletRegistrationBean.class); + ServletRegistrationBean registrationBean = context.getBean(ServletRegistrationBean.class); + assertThat(registrationBean.getUrlMappings()).contains("/h2-console/*"); + assertThat(registrationBean.getInitParameters()).containsEntry("trace", ""); + assertThat(registrationBean.getInitParameters()).containsEntry("webAllowOthers", ""); + assertThat(registrationBean.getInitParameters()).containsEntry("webAdminPassword", "abcd"); + }); } @Test @ExtendWith(OutputCaptureExtension.class) void singleDataSourceUrlIsLoggedWhenOnlyOneAvailable(CapturedOutput output) { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.h2.console.enabled=true").run((context) -> { - try (Connection connection = context.getBean(DataSource.class).getConnection()) { - assertThat(output).contains("H2 console available at '/h2-console'. Database available at '" - + connection.getMetaData().getURL() + "'"); - } - }); + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> { + try (Connection connection = context.getBean(DataSource.class).getConnection()) { + assertThat(output).contains("H2 console available at '/h2-console'. Database available at '" + + connection.getMetaData().getURL() + "'"); + } + }); } @Test @ExtendWith(OutputCaptureExtension.class) void noDataSourceIsLoggedWhenNoneAvailable(CapturedOutput output) { this.contextRunner.withUserConfiguration(FailingDataSourceConfiguration.class) - .withPropertyValues("spring.h2.console.enabled=true") - .run((context) -> assertThat(output).doesNotContain("H2 console available")); + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> assertThat(output).doesNotContain("H2 console available")); } @Test @@ -145,16 +150,17 @@ class H2ConsoleAutoConfigurationTests { void allDataSourceUrlsAreLoggedWhenMultipleAvailable(CapturedOutput output) { ClassLoader webAppClassLoader = new URLClassLoader(new URL[0]); this.contextRunner.withClassLoader(webAppClassLoader) - .withUserConfiguration(FailingDataSourceConfiguration.class, MultiDataSourceConfiguration.class) - .withPropertyValues("spring.h2.console.enabled=true").run((context) -> assertThat(output).contains( - "H2 console available at '/h2-console'. Databases available at 'someJdbcUrl', 'anotherJdbcUrl'")); + .withUserConfiguration(FailingDataSourceConfiguration.class, MultiDataSourceConfiguration.class) + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> assertThat(output).contains( + "H2 console available at '/h2-console'. Databases available at 'someJdbcUrl', 'anotherJdbcUrl'")); } @Test void h2ConsoleShouldNotFailIfDatabaseConnectionFails() { this.contextRunner.withUserConfiguration(FailingDataSourceConfiguration.class) - .withPropertyValues("spring.h2.console.enabled=true") - .run((context) -> assertThat(context.isRunning()).isTrue()); + .withPropertyValues("spring.h2.console.enabled=true") + .run((context) -> assertThat(context.isRunning()).isTrue()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java index 2cf6f66ea9..e60e6abcfa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -31,21 +31,21 @@ class H2ConsolePropertiesTests { void pathMustNotBeEmpty() { H2ConsoleProperties properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setPath("")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void pathMustHaveLengthGreaterThanOne() { H2ConsoleProperties properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setPath("/")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void customPathMustBeginWithASlash() { H2ConsoleProperties properties = new H2ConsoleProperties(); assertThatIllegalArgumentException().isThrownBy(() -> properties.setPath("custom")) - .withMessageContaining("Path must start with '/'"); + .withMessageContaining("Path must start with '/'"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java index f9d59e63f5..76441b4481 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfigurationTests.java @@ -54,12 +54,12 @@ import static org.assertj.core.api.Assertions.assertThat; class HypermediaAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withUserConfiguration(BaseConfig.class); + .withUserConfiguration(BaseConfig.class); @Test void autoConfigurationWhenSpringMvcNotOnClasspathShouldBackOff() { this.contextRunner.withClassLoader(new FilteredClassLoader(RequestMappingHandlerAdapter.class)) - .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); + .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); } @Test @@ -83,32 +83,37 @@ class HypermediaAutoConfigurationTests { @Test void doesBackOffIfEnableHypermediaSupportIsDeclaredManually() { this.contextRunner.withUserConfiguration(EnableHypermediaSupportConfig.class) - .withPropertyValues("spring.jackson.serialization.INDENT_OUTPUT:true") - .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); + .withPropertyValues("spring.jackson.serialization.INDENT_OUTPUT:true") + .run((context) -> assertThat(context.getBeansOfType(HypermediaConfiguration.class)).isEmpty()); } @Test void whenUsingTheDefaultConfigurationThenMappingJacksonConverterCanWriteHateoasTypeAsApplicationJson() { this.contextRunner.run((context) -> { RequestMappingHandlerAdapter handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class); - Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters().stream() - .filter(MappingJackson2HttpMessageConverter.class::isInstance).findFirst(); + Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters() + .stream() + .filter(MappingJackson2HttpMessageConverter.class::isInstance) + .findFirst(); assertThat(mappingJacksonConverter).hasValueSatisfying( (converter) -> assertThat(converter.canWrite(RepresentationModel.class, MediaType.APPLICATION_JSON)) - .isTrue()); + .isTrue()); }); } @Test void whenHalIsNotTheDefaultJsonMediaTypeThenMappingJacksonConverterCannotWriteHateoasTypeAsApplicationJson() { this.contextRunner.withPropertyValues("spring.hateoas.use-hal-as-default-json-media-type:false") - .run((context) -> { - RequestMappingHandlerAdapter handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class); - Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters() - .stream().filter(MappingJackson2HttpMessageConverter.class::isInstance).findFirst(); - assertThat(mappingJacksonConverter).hasValueSatisfying((converter) -> assertThat( - converter.canWrite(RepresentationModel.class, MediaType.APPLICATION_JSON)).isFalse()); - }); + .run((context) -> { + RequestMappingHandlerAdapter handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class); + Optional> mappingJacksonConverter = handlerAdapter.getMessageConverters() + .stream() + .filter(MappingJackson2HttpMessageConverter.class::isInstance) + .findFirst(); + assertThat(mappingJacksonConverter).hasValueSatisfying((converter) -> assertThat( + converter.canWrite(RepresentationModel.class, MediaType.APPLICATION_JSON)) + .isFalse()); + }); } @ImportAutoConfiguration({ HttpMessageConvertersAutoConfiguration.class, WebMvcAutoConfiguration.class, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java index c1cd46fdd6..dbe06a3501 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,120 +63,132 @@ class HazelcastAutoConfigurationClientTests { } private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test void systemPropertyWithXml() { this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") - .run(assertSpecificHazelcastClient("explicit-xml")); + .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") + .run(assertSpecificHazelcastClient("explicit-xml")); } @Test void systemPropertyWithYaml() { this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") - .run(assertSpecificHazelcastClient("explicit-yaml")); + .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") + .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test void systemPropertyWithYml() { this.contextRunner - .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") - .run(assertSpecificHazelcastClient("explicit-yml")); + .withSystemProperties(HazelcastClientConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") + .run(assertSpecificHazelcastClient("explicit-yml")); } @Test void explicitConfigFileWithXml() { - this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.xml").run(assertSpecificHazelcastClient("explicit-xml")); + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.xml") + .run(assertSpecificHazelcastClient("explicit-xml")); } @Test void explicitConfigFileWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.yaml") - .run(assertSpecificHazelcastClient("explicit-yaml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.yaml") + .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test void explicitConfigFileWithYml() { - this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.yml").run(assertSpecificHazelcastClient("explicit-yml")); + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.yml") + .run(assertSpecificHazelcastClient("explicit-yml")); } @Test void explicitConfigUrlWithXml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") - .run(assertSpecificHazelcastClient("explicit-xml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-specific.xml") + .run(assertSpecificHazelcastClient("explicit-xml")); } @Test void explicitConfigUrlWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") - .run(assertSpecificHazelcastClient("explicit-yaml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yaml") + .run(assertSpecificHazelcastClient("explicit-yaml")); } @Test void explicitConfigUrlWithYml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") - .run(assertSpecificHazelcastClient("explicit-yml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-specific.yml") + .run(assertSpecificHazelcastClient("explicit-yml")); } @Test void unknownConfigFile() { this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("foo/bar/unknown.xml")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("foo/bar/unknown.xml")); } @Test void clientConfigTakesPrecedence() { this.contextRunner.withUserConfiguration(HazelcastServerAndClientConfig.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> assertThat(context) - .getBean(HazelcastInstance.class).isInstanceOf(HazelcastClientProxy.class)); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((context) -> assertThat(context).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastClientProxy.class)); } @Test void clientConfigWithInstanceNameCreatesClientIfNecessary() { assertThat(HazelcastClient.getHazelcastClientByName("spring-boot")).isNull(); this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-client-instance.xml") - .run((context) -> assertThat(context).getBean(HazelcastInstance.class) - .extracting(HazelcastInstance::getName).isEqualTo("spring-boot")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-client-instance.xml") + .run((context) -> assertThat(context).getBean(HazelcastInstance.class) + .extracting(HazelcastInstance::getName) + .isEqualTo("spring-boot")); } @Test void autoConfiguredClientConfigUsesApplicationClassLoader() { - this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" - + "hazelcast/hazelcast-client-specific.xml").run((context) -> { - HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); - assertThat(hazelcast).isInstanceOf(HazelcastClientProxy.class); - ClientConfig clientConfig = ((HazelcastClientProxy) hazelcast).getClientConfig(); - assertThat(clientConfig.getClassLoader()) - .isSameAs(context.getSourceApplicationContext().getClassLoader()); - }); + this.contextRunner + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/" + + "hazelcast/hazelcast-client-specific.xml") + .run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + assertThat(hazelcast).isInstanceOf(HazelcastClientProxy.class); + ClientConfig clientConfig = ((HazelcastClientProxy) hazelcast).getClientConfig(); + assertThat(clientConfig.getClassLoader()) + .isSameAs(context.getSourceApplicationContext().getClassLoader()); + }); } private ContextConsumer assertSpecificHazelcastClient(String label) { - return (context) -> assertThat(context).getBean(HazelcastInstance.class).isInstanceOf(HazelcastInstance.class) - .has(labelEqualTo(label)); + return (context) -> assertThat(context).getBean(HazelcastInstance.class) + .isInstanceOf(HazelcastInstance.class) + .has(labelEqualTo(label)); } private static Condition labelEqualTo(String label) { - return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig().getLabels().stream() - .anyMatch((e) -> e.equals(label)), "Label equals to " + label); + return new Condition<>((o) -> ((HazelcastClientProxy) o).getClientConfig() + .getLabels() + .stream() + .anyMatch((e) -> e.equals(label)), "Label equals to " + label); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java index c9bc6388f9..9a533d108c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastAutoConfigurationServerTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test void defaultConfigFile() { @@ -68,88 +68,88 @@ class HazelcastAutoConfigurationServerTests { @Test void systemPropertyWithXml() { this.contextRunner - .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); - }); + .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); + }); } @Test void systemPropertyWithYaml() { this.contextRunner - .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); - }); + .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); + }); } @Test void systemPropertyWithYml() { this.contextRunner - .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY - + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml") - .run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); - }); + .withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + + "=classpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + assertThat(config.getMapConfigs().keySet()).containsOnly("foobar"); + }); } @Test void explicitConfigFileWithXml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.xml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + + "hazelcast-specific.xml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); } @Test void explicitConfigFileWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.yaml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + + "hazelcast-specific.yaml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); } @Test void explicitConfigFileWithYml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" - + "hazelcast-specific.yml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); + .withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + + "hazelcast-specific.yml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); } @Test void explicitConfigUrlWithXml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.xml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.xml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml")); } @Test void explicitConfigUrlWithYaml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.yaml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.yaml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yaml")); } @Test void explicitConfigUrlWithYml() { this.contextRunner - .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" - + "boot/autoconfigure/hazelcast/hazelcast-specific.yml") - .run(assertSpecificHazelcastServer( - "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); + .withPropertyValues("spring.hazelcast.config=classpath:org/springframework/" + + "boot/autoconfigure/hazelcast/hazelcast-specific.yml") + .run(assertSpecificHazelcastServer( + "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.yml")); } private ContextConsumer assertSpecificHazelcastServer(String location) { @@ -162,8 +162,9 @@ class HazelcastAutoConfigurationServerTests { @Test void unknownConfigFile() { this.contextRunner.withPropertyValues("spring.hazelcast.config=foo/bar/unknown.xml") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("foo/bar/unknown.xml")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("foo/bar/unknown.xml")); } @Test @@ -172,12 +173,13 @@ class HazelcastAutoConfigurationServerTests { HazelcastInstance existing = Hazelcast.newHazelcastInstance(config); try { this.contextRunner.withUserConfiguration(HazelcastConfigWithName.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> { - HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); - assertThat(hazelcast.getConfig().getInstanceName()).isEqualTo("my-test-instance"); - // Should reuse any existing instance by default. - assertThat(hazelcast).isEqualTo(existing); - }); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((context) -> { + HazelcastInstance hazelcast = context.getBean(HazelcastInstance.class); + assertThat(hazelcast.getConfig().getInstanceName()).isEqualTo("my-test-instance"); + // Should reuse any existing instance by default. + assertThat(hazelcast).isEqualTo(existing); + }); } finally { existing.shutdown(); @@ -187,11 +189,12 @@ class HazelcastAutoConfigurationServerTests { @Test void configInstanceWithoutName() { this.contextRunner.withUserConfiguration(HazelcastConfigNoName.class) - .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> { - Config config = context.getBean(HazelcastInstance.class).getConfig(); - Map queueConfigs = config.getQueueConfigs(); - assertThat(queueConfigs.keySet()).containsOnly("another-queue"); - }); + .withPropertyValues("spring.hazelcast.config=this-is-ignored.xml") + .run((context) -> { + Config config = context.getBean(HazelcastInstance.class).getConfig(); + Map queueConfigs = config.getQueueConfigs(); + assertThat(queueConfigs.keySet()).containsOnly("another-queue"); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java index b371a070bc..fdff5e4210 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HazelcastAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HazelcastAutoConfiguration.class)); @Test void defaultConfigFile() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java index c50db4119d..d1c1928114 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/hazelcast/HazelcastJpaDependencyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -46,12 +46,12 @@ import static org.mockito.Mockito.mock; class HazelcastJpaDependencyAutoConfigurationTests { private static final String POST_PROCESSOR_BEAN_NAME = HazelcastInstanceEntityManagerFactoryDependsOnPostProcessor.class - .getName(); + .getName(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class, HazelcastJpaDependencyAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, + HazelcastJpaDependencyAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void registrationIfHazelcastInstanceHasRegularBeanName() { @@ -80,8 +80,8 @@ class HazelcastJpaDependencyAutoConfigurationTests { @Test void noRegistrationWithNoEntityManagerFactory() { new ApplicationContextRunner().withUserConfiguration(HazelcastConfiguration.class) - .withConfiguration(AutoConfigurations.of(HazelcastJpaDependencyAutoConfiguration.class)) - .run((context) -> assertThat(postProcessors(context)).doesNotContainKey(POST_PROCESSOR_BEAN_NAME)); + .withConfiguration(AutoConfigurations.of(HazelcastJpaDependencyAutoConfiguration.class)) + .run((context) -> assertThat(postProcessors(context)).doesNotContainKey(POST_PROCESSOR_BEAN_NAME)); } private Map postProcessors( @@ -91,7 +91,8 @@ class HazelcastJpaDependencyAutoConfigurationTests { private List entityManagerFactoryDependencies(AssertableApplicationContext context) { String[] dependsOn = ((BeanDefinitionRegistry) context.getSourceApplicationContext()) - .getBeanDefinition("entityManagerFactory").getDependsOn(); + .getBeanDefinition("entityManagerFactory") + .getDependsOn(); return (dependsOn != null) ? Arrays.asList(dependsOn) : Collections.emptyList(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java index 6b65831cd2..bf760a5719 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HttpMessageConvertersAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); @Test void jacksonNotAvailable() { @@ -85,25 +85,26 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void jacksonDefaultConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test void jacksonConverterWithBuilder() { this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "mappingJackson2HttpMessageConverter")); } @Test void jacksonXmlConverterWithBuilder() { - this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class).run(assertConverter( - MappingJackson2XmlHttpMessageConverter.class, "mappingJackson2XmlHttpMessageConverter")); + this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class) + .run(assertConverter(MappingJackson2XmlHttpMessageConverter.class, + "mappingJackson2XmlHttpMessageConverter")); } @Test void jacksonCustomConverter() { this.contextRunner.withUserConfiguration(JacksonObjectMapperConfig.class, JacksonConverterConfig.class) - .run(assertConverter(MappingJackson2HttpMessageConverter.class, "customJacksonMessageConverter")); + .run(assertConverter(MappingJackson2HttpMessageConverter.class, "customJacksonMessageConverter")); } @Test @@ -117,14 +118,14 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void gsonDefaultConverter() { this.contextRunner.withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) - .run(assertConverter(GsonHttpMessageConverter.class, "gsonHttpMessageConverter")); + .run(assertConverter(GsonHttpMessageConverter.class, "gsonHttpMessageConverter")); } @Test void gsonCustomConverter() { this.contextRunner.withUserConfiguration(GsonConverterConfig.class) - .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) - .run(assertConverter(GsonHttpMessageConverter.class, "customGsonMessageConverter")); + .withConfiguration(AutoConfigurations.of(GsonAutoConfiguration.class)) + .run(assertConverter(GsonHttpMessageConverter.class, "customGsonMessageConverter")); } @Test @@ -148,14 +149,14 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void jsonbDefaultConverter() { this.contextRunner.withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) - .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); + .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); } @Test void jsonbCustomConverter() { this.contextRunner.withUserConfiguration(JsonbConverterConfig.class) - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) - .run(assertConverter(JsonbHttpMessageConverter.class, "customJsonbMessageConverter")); + .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)) + .run(assertConverter(JsonbHttpMessageConverter.class, "customJsonbMessageConverter")); } @Test @@ -176,30 +177,31 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void stringCustomConverter() { this.contextRunner.withUserConfiguration(StringConverterConfig.class) - .run(assertConverter(StringHttpMessageConverter.class, "customStringMessageConverter")); + .run(assertConverter(StringHttpMessageConverter.class, "customStringMessageConverter")); } @Test void typeConstrainedConverterDoesNotPreventAutoConfigurationOfJacksonConverter() { - this.contextRunner.withUserConfiguration(JacksonObjectMapperBuilderConfig.class, - TypeConstrainedConverterConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) - .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()) - .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); - }); + this.contextRunner + .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, TypeConstrainedConverterConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) + .getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); + }); } @Test void typeConstrainedConverterFromSpringDataDoesNotPreventAutoConfigurationOfJacksonConverter() { this.contextRunner - .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, RepositoryRestMvcConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) - .getBeanDefinition("mappingJackson2HttpMessageConverter"); - assertThat(beanDefinition.getFactoryBeanName()) - .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); - }); + .withUserConfiguration(JacksonObjectMapperBuilderConfig.class, RepositoryRestMvcConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = ((GenericApplicationContext) context.getSourceApplicationContext()) + .getBeanDefinition("mappingJackson2HttpMessageConverter"); + assertThat(beanDefinition.getFactoryBeanName()) + .isEqualTo(MappingJackson2HttpMessageConverterConfiguration.class.getName()); + }); } @Test @@ -216,65 +218,66 @@ class HttpMessageConvertersAutoConfigurationTests { @Test void gsonIsPreferredIfJacksonIsNotAvailable() { allOptionsRunner().withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName())) - .run((context) -> { - assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); - assertConverterBeanRegisteredWithHttpMessageConverters(context, GsonHttpMessageConverter.class); - assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); - }); + .run((context) -> { + assertConverterBeanExists(context, GsonHttpMessageConverter.class, "gsonHttpMessageConverter"); + assertConverterBeanRegisteredWithHttpMessageConverters(context, GsonHttpMessageConverter.class); + assertThat(context).doesNotHaveBean(JsonbHttpMessageConverter.class); + }); } @Test void jsonbIsPreferredIfJacksonAndGsonAreNotAvailable() { allOptionsRunner() - .withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName(), - Gson.class.getPackage().getName())) - .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); + .withClassLoader(new FilteredClassLoader(ObjectMapper.class.getPackage().getName(), + Gson.class.getPackage().getName())) + .run(assertConverter(JsonbHttpMessageConverter.class, "jsonbHttpMessageConverter")); } @Test void whenServletWebApplicationHttpMessageConvertersIsConfigured() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(HttpMessageConverters.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(HttpMessageConverters.class)); } @Test void whenReactiveWebApplicationHttpMessageConvertersIsNotConfigured() { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(HttpMessageConverters.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(HttpMessageConverters.class)); } @Test void whenEncodingCharsetIsNotConfiguredThenStringMessageConverterUsesUtf8() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(StringHttpMessageConverter.class); - assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) - .isEqualTo(StandardCharsets.UTF_8); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(StringHttpMessageConverter.class); + assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) + .isEqualTo(StandardCharsets.UTF_8); + }); } @Test void whenEncodingCharsetIsConfiguredThenStringMessageConverterUsesSpecificCharset() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .withPropertyValues("server.servlet.encoding.charset=UTF-16").run((context) -> { - assertThat(context).hasSingleBean(StringHttpMessageConverter.class); - assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) - .isEqualTo(StandardCharsets.UTF_16); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .withPropertyValues("server.servlet.encoding.charset=UTF-16") + .run((context) -> { + assertThat(context).hasSingleBean(StringHttpMessageConverter.class); + assertThat(context.getBean(StringHttpMessageConverter.class).getDefaultCharset()) + .isEqualTo(StandardCharsets.UTF_16); + }); } @Test // gh-21789 void whenAutoConfigurationIsActiveThenServerPropertiesConfigurationPropertiesAreNotEnabled() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(HttpMessageConverters.class); - assertThat(context).doesNotHaveBean(ServerProperties.class); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(HttpMessageConverters.class); + assertThat(context).doesNotHaveBean(ServerProperties.class); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java index 0a907eaff7..edb4cb1463 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersAutoConfigurationWithoutJacksonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class HttpMessageConvertersAutoConfigurationWithoutJacksonTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)); @Test void autoConfigurationWorksWithSpringHateoasButWithoutJackson() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java index 3125d585b0..a32ee3da12 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/codec/CodecsAutoConfigurationTests.java @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; class CodecsAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CodecsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(CodecsAutoConfiguration.class)); @Test void autoConfigShouldProvideALoggingRequestDetailsCustomizer() { @@ -86,17 +86,17 @@ class CodecsAutoConfigurationTests { @Test void jacksonCodecCustomizerIsAutoConfiguredWhenObjectMapperIsPresent() { this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class) - .run((context) -> assertThat(context).hasBean("jacksonCodecCustomizer")); + .run((context) -> assertThat(context).hasBean("jacksonCodecCustomizer")); } @Test void userProvidedCustomizerCanOverrideJacksonCodecCustomizer() { this.contextRunner.withUserConfiguration(ObjectMapperConfiguration.class, CodecCustomizerConfiguration.class) - .run((context) -> { - List codecCustomizers = context.getBean(CodecCustomizers.class).codecCustomizers; - assertThat(codecCustomizers).hasSize(3); - assertThat(codecCustomizers.get(2)).isInstanceOf(TestCodecCustomizer.class); - }); + .run((context) -> { + List codecCustomizers = context.getBean(CodecCustomizers.class).codecCustomizers; + assertThat(codecCustomizers).hasSize(3); + assertThat(codecCustomizers.get(2)).isInstanceOf(TestCodecCustomizer.class); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java index 34033cd669..2bed18e3f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/influx/InfluxDbAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; class InfluxDbAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(InfluxDbAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(InfluxDbAutoConfiguration.class)); @Test void influxDbRequiresUrl() { @@ -52,9 +52,9 @@ class InfluxDbAutoConfigurationTests { @Test void influxDbCanBeCustomized() { this.contextRunner - .withPropertyValues("spring.influx.url=http://localhost", "spring.influx.user=user", - "spring.influx.password=password") - .run((context) -> assertThat(context).hasSingleBean(InfluxDB.class)); + .withPropertyValues("spring.influx.url=http://localhost", "spring.influx.user=user", + "spring.influx.password=password") + .run((context) -> assertThat(context).hasSingleBean(InfluxDB.class)); } @Test @@ -69,21 +69,23 @@ class InfluxDbAutoConfigurationTests { @Test void influxDbWithOkHttpClientBuilderProvider() { this.contextRunner.withUserConfiguration(CustomOkHttpClientBuilderProviderConfig.class) - .withPropertyValues("spring.influx.url=http://localhost").run((context) -> { - assertThat(context).hasSingleBean(InfluxDB.class); - int readTimeout = getReadTimeoutProperty(context); - assertThat(readTimeout).isEqualTo(40_000); - }); + .withPropertyValues("spring.influx.url=http://localhost") + .run((context) -> { + assertThat(context).hasSingleBean(InfluxDB.class); + int readTimeout = getReadTimeoutProperty(context); + assertThat(readTimeout).isEqualTo(40_000); + }); } @Test void influxDbWithCustomizer() { this.contextRunner.withBean(InfluxDbCustomizer.class, () -> (influxDb) -> influxDb.setDatabase("test")) - .withPropertyValues("spring.influx.url=http://localhost").run((context) -> { - assertThat(context).hasSingleBean(InfluxDB.class); - InfluxDB influxDb = context.getBean(InfluxDB.class); - assertThat(influxDb).hasFieldOrPropertyWithValue("database", "test"); - }); + .withPropertyValues("spring.influx.url=http://localhost") + .run((context) -> { + assertThat(context).hasSingleBean(InfluxDB.class); + InfluxDB influxDb = context.getBean(InfluxDB.class); + assertThat(influxDb).hasFieldOrPropertyWithValue("database", "test"); + }); } private int getReadTimeoutProperty(AssertableApplicationContext context) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java index d4d79ed642..9d86809998 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -48,42 +48,45 @@ class ProjectInfoAutoConfigurationTests { @Test void gitPropertiesWithNoData() { this.contextRunner - .withPropertyValues("spring.info.git.location=" - + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties.getBranch()).isNull(); - }); + .withPropertyValues("spring.info.git.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties.getBranch()).isNull(); + }); } @Test void gitPropertiesFallbackWithGitPropertiesBean() { - this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class).withPropertyValues( - "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties).isSameAs(context.getBean("customGitProperties")); - }); + this.contextRunner.withUserConfiguration(CustomInfoPropertiesConfiguration.class) + .withPropertyValues( + "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties).isSameAs(context.getBean("customGitProperties")); + }); } @Test void gitPropertiesUsesUtf8ByDefault() { - this.contextRunner.withPropertyValues( - "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties.get("commit.charset")).isEqualTo("test™"); - }); + this.contextRunner + .withPropertyValues( + "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties.get("commit.charset")).isEqualTo("test™"); + }); } @Test void gitPropertiesEncodingCanBeConfigured() { - this.contextRunner.withPropertyValues("spring.info.git.encoding=US-ASCII", - "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") - .run((context) -> { - GitProperties gitProperties = context.getBean(GitProperties.class); - assertThat(gitProperties.get("commit.charset")).isNotEqualTo("test™"); - }); + this.contextRunner + .withPropertyValues("spring.info.git.encoding=US-ASCII", + "spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties") + .run((context) -> { + GitProperties gitProperties = context.getBean(GitProperties.class); + assertThat(gitProperties.get("commit.charset")).isNotEqualTo("test™"); + }); } @Test @@ -101,22 +104,22 @@ class ProjectInfoAutoConfigurationTests { @Test void buildPropertiesCustomLocation() { this.contextRunner - .withPropertyValues("spring.info.build.location=" - + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") - .run((context) -> { - BuildProperties buildProperties = context.getBean(BuildProperties.class); - assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme"); - assertThat(buildProperties.getArtifact()).isEqualTo("acme"); - assertThat(buildProperties.getName()).isEqualTo("acme"); - assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT"); - assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457088120000L); - }); + .withPropertyValues("spring.info.build.location=" + + "classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.getGroup()).isEqualTo("com.example.acme"); + assertThat(buildProperties.getArtifact()).isEqualTo("acme"); + assertThat(buildProperties.getName()).isEqualTo("acme"); + assertThat(buildProperties.getVersion()).isEqualTo("1.0.1-SNAPSHOT"); + assertThat(buildProperties.getTime().toEpochMilli()).isEqualTo(1457088120000L); + }); } @Test void buildPropertiesCustomInvalidLocation() { this.contextRunner.withPropertyValues("spring.info.build.location=classpath:/org/acme/no-build-info.properties") - .run((context) -> assertThat(context.getBeansOfType(BuildProperties.class)).hasSize(0)); + .run((context) -> assertThat(context.getBeansOfType(BuildProperties.class)).hasSize(0)); } @Test @@ -131,20 +134,20 @@ class ProjectInfoAutoConfigurationTests { void buildPropertiesUsesUtf8ByDefault() { this.contextRunner.withPropertyValues( "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") - .run((context) -> { - BuildProperties buildProperties = context.getBean(BuildProperties.class); - assertThat(buildProperties.get("charset")).isEqualTo("test™"); - }); + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.get("charset")).isEqualTo("test™"); + }); } @Test void buildPropertiesEncodingCanBeConfigured() { this.contextRunner.withPropertyValues("spring.info.build.encoding=US-ASCII", "spring.info.build.location=classpath:/org/springframework/boot/autoconfigure/info/build-info.properties") - .run((context) -> { - BuildProperties buildProperties = context.getBean(BuildProperties.class); - assertThat(buildProperties.get("charset")).isNotEqualTo("test™"); - }); + .run((context) -> { + BuildProperties buildProperties = context.getBean(BuildProperties.class); + assertThat(buildProperties.get("charset")).isNotEqualTo("test™"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java index 5415191893..43849aa436 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java @@ -97,7 +97,7 @@ import static org.mockito.Mockito.mock; class IntegrationAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)); @Test void integrationIsAvailable() { @@ -118,7 +118,7 @@ class IntegrationAutoConfigurationTests { @Test void noMBeanServerAvailable() { ApplicationContextRunner contextRunnerWithoutJmx = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(IntegrationAutoConfiguration.class)); contextRunnerWithoutJmx.run((context) -> { assertThat(context).hasSingleBean(TestGateway.class); assertThat(context).hasSingleBean(IntegrationComponentScanConfiguration.class); @@ -128,8 +128,8 @@ class IntegrationAutoConfigurationTests { @Test void parentContext() { this.contextRunner.run((context) -> this.contextRunner.withParent(context) - .withPropertyValues("spring.jmx.default_domain=org.foo") - .run((child) -> assertThat(child).hasSingleBean(HeaderChannelRegistry.class))); + .withPropertyValues("spring.jmx.default_domain=org.foo") + .run((child) -> assertThat(child).hasSingleBean(HeaderChannelRegistry.class))); } @Test @@ -153,143 +153,144 @@ class IntegrationAutoConfigurationTests { @Test void customizeJmxDomain() { this.contextRunner.withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default_domain=org.foo") - .run((context) -> { - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - assertThat(mBeanServer.getDomains()).contains("org.foo").doesNotContain( - "org.springframework.integration", "org.springframework.integration.monitor"); - }); + .run((context) -> { + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + assertThat(mBeanServer.getDomains()).contains("org.foo") + .doesNotContain("org.springframework.integration", "org.springframework.integration.monitor"); + }); } @Test void primaryExporterIsAllowed() { this.contextRunner.withPropertyValues("spring.jmx.enabled=true") - .withUserConfiguration(CustomMBeanExporter.class).run((context) -> { - assertThat(context).getBeans(MBeanExporter.class).hasSize(2); - assertThat(context.getBean(MBeanExporter.class)).isSameAs(context.getBean("myMBeanExporter")); - }); + .withUserConfiguration(CustomMBeanExporter.class) + .run((context) -> { + assertThat(context).getBeans(MBeanExporter.class).hasSize(2); + assertThat(context.getBean(MBeanExporter.class)).isSameAs(context.getBean("myMBeanExporter")); + }); } @Test void integrationJdbcDataSourceInitializerEnabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.integration.jdbc.initialize-schema=always") - .run((context) -> { - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.integration.jdbc.initialize-schema=always") + .run((context) -> { + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); + }); } @Test void whenIntegrationJdbcDataSourceInitializerIsEnabledThenFlywayCanBeUsed() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class, - FlywayAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.integration.jdbc.initialize-schema=always") - .run((context) -> { - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); - assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class, + FlywayAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.integration.jdbc.initialize-schema=always") + .run((context) -> { + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.ALWAYS); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_GROUP_TO_MESSAGE")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_MESSAGE_GROUP")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_LOCK")).isEmpty(); + assertThat(jdbc.queryForList("select * from INT_CHANNEL_MESSAGE")).isEmpty(); + }); } @Test void integrationJdbcDataSourceInitializerDisabled() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.integration.jdbc.initialize-schema=never") - .run((context) -> { - assertThat(context).doesNotHaveBean(IntegrationDataSourceScriptDatabaseInitializer.class); - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.NEVER); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThatExceptionOfType(BadSqlGrammarException.class) - .isThrownBy(() -> jdbc.queryForList("select * from INT_MESSAGE")); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.integration.jdbc.initialize-schema=never") + .run((context) -> { + assertThat(context).doesNotHaveBean(IntegrationDataSourceScriptDatabaseInitializer.class); + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.NEVER); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> jdbc.queryForList("select * from INT_MESSAGE")); + }); } @Test void integrationJdbcDataSourceInitializerEnabledByDefaultWithEmbeddedDb() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true").run((context) -> { - IntegrationProperties properties = context.getBean(IntegrationProperties.class); - assertThat(properties.getJdbc().getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - JdbcOperations jdbc = context.getBean(JdbcOperations.class); - assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true") + .run((context) -> { + IntegrationProperties properties = context.getBean(IntegrationProperties.class); + assertThat(properties.getJdbc().getInitializeSchema()).isEqualTo(DatabaseInitializationMode.EMBEDDED); + JdbcOperations jdbc = context.getBean(JdbcOperations.class); + assertThat(jdbc.queryForList("select * from INT_MESSAGE")).isEmpty(); + }); } @Test void rsocketSupportEnabled() { this.contextRunner.withUserConfiguration(RSocketServerConfiguration.class) - .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class, - RSocketStrategiesAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, - RSocketRequesterAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .withPropertyValues("spring.rsocket.server.port=0", "spring.integration.rsocket.client.port=0", - "spring.integration.rsocket.client.host=localhost", - "spring.integration.rsocket.server.message-mapping-enabled=true") - .run((context) -> { - assertThat(context).hasSingleBean(ClientRSocketConnector.class).hasBean("clientRSocketConnector") - .hasSingleBean(ServerRSocketConnector.class) - .hasSingleBean(ServerRSocketMessageHandler.class) - .hasSingleBean(RSocketMessageHandler.class); - - ServerRSocketMessageHandler serverRSocketMessageHandler = context - .getBean(ServerRSocketMessageHandler.class); - assertThat(context).getBean(RSocketMessageHandler.class).isSameAs(serverRSocketMessageHandler); - - ClientRSocketConnector clientRSocketConnector = context.getBean(ClientRSocketConnector.class); - ClientTransport clientTransport = (ClientTransport) new DirectFieldAccessor(clientRSocketConnector) - .getPropertyValue("clientTransport"); - - assertThat(clientTransport).isInstanceOf(TcpClientTransport.class); - }); + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class, + RSocketStrategiesAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, + RSocketRequesterAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .withPropertyValues("spring.rsocket.server.port=0", "spring.integration.rsocket.client.port=0", + "spring.integration.rsocket.client.host=localhost", + "spring.integration.rsocket.server.message-mapping-enabled=true") + .run((context) -> { + assertThat(context).hasSingleBean(ClientRSocketConnector.class) + .hasBean("clientRSocketConnector") + .hasSingleBean(ServerRSocketConnector.class) + .hasSingleBean(ServerRSocketMessageHandler.class) + .hasSingleBean(RSocketMessageHandler.class); + + ServerRSocketMessageHandler serverRSocketMessageHandler = context + .getBean(ServerRSocketMessageHandler.class); + assertThat(context).getBean(RSocketMessageHandler.class).isSameAs(serverRSocketMessageHandler); + + ClientRSocketConnector clientRSocketConnector = context.getBean(ClientRSocketConnector.class); + ClientTransport clientTransport = (ClientTransport) new DirectFieldAccessor(clientRSocketConnector) + .getPropertyValue("clientTransport"); + + assertThat(clientTransport).isInstanceOf(TcpClientTransport.class); + }); } @Test void taskSchedulerIsNotOverridden() { this.contextRunner.withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withPropertyValues("spring.task.scheduling.thread-name-prefix=integration-scheduling-", - "spring.task.scheduling.pool.size=3") - .run((context) -> { - assertThat(context).hasSingleBean(TaskScheduler.class); - assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class) - .hasFieldOrPropertyWithValue("threadNamePrefix", "integration-scheduling-") - .hasFieldOrPropertyWithValue("scheduledExecutor.corePoolSize", 3); - }); + .withPropertyValues("spring.task.scheduling.thread-name-prefix=integration-scheduling-", + "spring.task.scheduling.pool.size=3") + .run((context) -> { + assertThat(context).hasSingleBean(TaskScheduler.class); + assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class) + .hasFieldOrPropertyWithValue("threadNamePrefix", "integration-scheduling-") + .hasFieldOrPropertyWithValue("scheduledExecutor.corePoolSize", 3); + }); } @Test void taskSchedulerCanBeCustomized() { TaskScheduler customTaskScheduler = mock(TaskScheduler.class); this.contextRunner.withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class, - () -> customTaskScheduler) - .run((context) -> { - assertThat(context).hasSingleBean(TaskScheduler.class); - assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME) - .isSameAs(customTaskScheduler); - }); + .withBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class, () -> customTaskScheduler) + .run((context) -> { + assertThat(context).hasSingleBean(TaskScheduler.class); + assertThat(context).getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME) + .isSameAs(customTaskScheduler); + }); } @Test @@ -301,21 +302,20 @@ class IntegrationAutoConfigurationTests { "spring.integration.endpoint.throw-exception-on-late-reply=true", "spring.integration.endpoint.read-only-headers=ignoredHeader", "spring.integration.endpoint.no-auto-startup=notStartedEndpoint,_org.springframework.integration.errorLogger") - .run((context) -> { - assertThat(context) - .hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); - org.springframework.integration.context.IntegrationProperties integrationProperties = context - .getBean(org.springframework.integration.context.IntegrationProperties.class); - assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); - assertThat(integrationProperties.getChannelsMaxUnicastSubscribers()).isEqualTo(2); - assertThat(integrationProperties.getChannelsMaxBroadcastSubscribers()).isEqualTo(3); - assertThat(integrationProperties.isErrorChannelRequireSubscribers()).isFalse(); - assertThat(integrationProperties.isErrorChannelIgnoreFailures()).isFalse(); - assertThat(integrationProperties.isMessagingTemplateThrowExceptionOnLateReply()).isTrue(); - assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); - assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("notStartedEndpoint", - "_org.springframework.integration.errorLogger"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); + org.springframework.integration.context.IntegrationProperties integrationProperties = context + .getBean(org.springframework.integration.context.IntegrationProperties.class); + assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); + assertThat(integrationProperties.getChannelsMaxUnicastSubscribers()).isEqualTo(2); + assertThat(integrationProperties.getChannelsMaxBroadcastSubscribers()).isEqualTo(3); + assertThat(integrationProperties.isErrorChannelRequireSubscribers()).isFalse(); + assertThat(integrationProperties.isErrorChannelIgnoreFailures()).isFalse(); + assertThat(integrationProperties.isMessagingTemplateThrowExceptionOnLateReply()).isTrue(); + assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); + assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("notStartedEndpoint", + "_org.springframework.integration.errorLogger"); + }); } @Test @@ -324,23 +324,23 @@ class IntegrationAutoConfigurationTests { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); org.springframework.integration.context.IntegrationProperties integrationProperties = context - .getBean(org.springframework.integration.context.IntegrationProperties.class); + .getBean(org.springframework.integration.context.IntegrationProperties.class); assertThat(integrationProperties.isChannelsAutoCreate()) - .isEqualTo(defaultIntegrationProperties.isChannelsAutoCreate()); + .isEqualTo(defaultIntegrationProperties.isChannelsAutoCreate()); assertThat(integrationProperties.getChannelsMaxUnicastSubscribers()) - .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); + .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); assertThat(integrationProperties.getChannelsMaxBroadcastSubscribers()) - .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); + .isEqualTo(defaultIntegrationProperties.getChannelsMaxBroadcastSubscribers()); assertThat(integrationProperties.isErrorChannelRequireSubscribers()) - .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); + .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); assertThat(integrationProperties.isErrorChannelIgnoreFailures()) - .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); + .isEqualTo(defaultIntegrationProperties.isErrorChannelIgnoreFailures()); assertThat(integrationProperties.isMessagingTemplateThrowExceptionOnLateReply()) - .isEqualTo(defaultIntegrationProperties.isMessagingTemplateThrowExceptionOnLateReply()); + .isEqualTo(defaultIntegrationProperties.isMessagingTemplateThrowExceptionOnLateReply()); assertThat(integrationProperties.getReadOnlyHeaders()) - .isEqualTo(defaultIntegrationProperties.getReadOnlyHeaders()); + .isEqualTo(defaultIntegrationProperties.getReadOnlyHeaders()); assertThat(integrationProperties.getNoAutoStartupEndpoints()) - .isEqualTo(defaultIntegrationProperties.getNoAutoStartupEndpoints()); + .isEqualTo(defaultIntegrationProperties.getNoAutoStartupEndpoints()); }); } @@ -348,55 +348,51 @@ class IntegrationAutoConfigurationTests { void integrationGlobalPropertiesUserBeanOverridesAutoConfiguration() { org.springframework.integration.context.IntegrationProperties userIntegrationProperties = new org.springframework.integration.context.IntegrationProperties(); this.contextRunner.withPropertyValues() - .withBean(IntegrationContextUtils.INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME, - org.springframework.integration.context.IntegrationProperties.class, - () -> userIntegrationProperties) - .run((context) -> { - assertThat(context) - .hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); - assertThat(context.getBean(org.springframework.integration.context.IntegrationProperties.class)) - .isSameAs(userIntegrationProperties); - }); + .withBean(IntegrationContextUtils.INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME, + org.springframework.integration.context.IntegrationProperties.class, + () -> userIntegrationProperties) + .run((context) -> { + assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); + assertThat(context.getBean(org.springframework.integration.context.IntegrationProperties.class)) + .isSameAs(userIntegrationProperties); + }); } @Test void integrationGlobalPropertiesFromSpringIntegrationPropertiesFile() { this.contextRunner - .withPropertyValues("spring.integration.channel.auto-create=false", - "spring.integration.endpoint.read-only-headers=ignoredHeader") - .withInitializer((applicationContext) -> new IntegrationPropertiesEnvironmentPostProcessor() - .postProcessEnvironment(applicationContext.getEnvironment(), null)) - .run((context) -> { - assertThat(context) - .hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); - org.springframework.integration.context.IntegrationProperties integrationProperties = context - .getBean(org.springframework.integration.context.IntegrationProperties.class); - assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); - assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); - // See META-INF/spring.integration.properties - assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("testService*"); - }); + .withPropertyValues("spring.integration.channel.auto-create=false", + "spring.integration.endpoint.read-only-headers=ignoredHeader") + .withInitializer((applicationContext) -> new IntegrationPropertiesEnvironmentPostProcessor() + .postProcessEnvironment(applicationContext.getEnvironment(), null)) + .run((context) -> { + assertThat(context).hasSingleBean(org.springframework.integration.context.IntegrationProperties.class); + org.springframework.integration.context.IntegrationProperties integrationProperties = context + .getBean(org.springframework.integration.context.IntegrationProperties.class); + assertThat(integrationProperties.isChannelsAutoCreate()).isFalse(); + assertThat(integrationProperties.getReadOnlyHeaders()).containsOnly("ignoredHeader"); + // See META-INF/spring.integration.properties + assertThat(integrationProperties.getNoAutoStartupEndpoints()).containsOnly("testService*"); + }); } @Test void whenTheUserDefinesTheirOwnIntegrationDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomIntegrationDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("integrationDataSourceScriptDatabaseInitializer") - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("integrationDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredIntegrationInitializerRemains() { this.contextRunner.withUserConfiguration(CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(IntegrationDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Test @@ -417,93 +413,99 @@ class IntegrationAutoConfigurationTests { @Test void whenCustomPollerPropertiesAreSetThenTheyAreReflectedInPollerMetadata() { this.contextRunner.withUserConfiguration(PollingConsumerConfiguration.class) - .withPropertyValues("spring.integration.poller.cron=* * * ? * *", - "spring.integration.poller.max-messages-per-poll=1", - "spring.integration.poller.receive-timeout=10s") - .run((context) -> { - assertThat(context).hasSingleBean(PollerMetadata.class); - PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); - assertThat(metadata.getMaxMessagesPerPoll()).isOne(); - assertThat(metadata.getReceiveTimeout()).isEqualTo(10000L); - assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(CronTrigger.class)) - .satisfies((trigger) -> assertThat(trigger.getExpression()).isEqualTo("* * * ? * *")); - }); + .withPropertyValues("spring.integration.poller.cron=* * * ? * *", + "spring.integration.poller.max-messages-per-poll=1", + "spring.integration.poller.receive-timeout=10s") + .run((context) -> { + assertThat(context).hasSingleBean(PollerMetadata.class); + PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); + assertThat(metadata.getMaxMessagesPerPoll()).isOne(); + assertThat(metadata.getReceiveTimeout()).isEqualTo(10000L); + assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(CronTrigger.class)) + .satisfies((trigger) -> assertThat(trigger.getExpression()).isEqualTo("* * * ? * *")); + }); } @Test void whenPollerPropertiesForMultipleTriggerTypesAreSetThenRefreshFails() { this.contextRunner - .withPropertyValues("spring.integration.poller.cron=* * * ? * *", - "spring.integration.poller.fixed-delay=1s") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasRootCauseExactlyInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class) - .rootCause() - .asInstanceOf( - InstanceOfAssertFactories.type(MutuallyExclusiveConfigurationPropertiesException.class)) - .satisfies((ex) -> { - assertThat(ex.getConfiguredNames()).containsExactlyInAnyOrder( - "spring.integration.poller.cron", "spring.integration.poller.fixed-delay"); - assertThat(ex.getMutuallyExclusiveNames()).containsExactlyInAnyOrder( - "spring.integration.poller.cron", "spring.integration.poller.fixed-delay", - "spring.integration.poller.fixed-rate"); - })); + .withPropertyValues("spring.integration.poller.cron=* * * ? * *", + "spring.integration.poller.fixed-delay=1s") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasRootCauseExactlyInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class) + .rootCause() + .asInstanceOf(InstanceOfAssertFactories.type(MutuallyExclusiveConfigurationPropertiesException.class)) + .satisfies((ex) -> { + assertThat(ex.getConfiguredNames()).containsExactlyInAnyOrder("spring.integration.poller.cron", + "spring.integration.poller.fixed-delay"); + assertThat(ex.getMutuallyExclusiveNames()).containsExactlyInAnyOrder( + "spring.integration.poller.cron", "spring.integration.poller.fixed-delay", + "spring.integration.poller.fixed-rate"); + })); } @Test void whenFixedDelayPollerPropertyIsSetThenItIsReflectedAsFixedDelayPropertyOfPeriodicTrigger() { this.contextRunner.withUserConfiguration(PollingConsumerConfiguration.class) - .withPropertyValues("spring.integration.poller.fixed-delay=5000").run((context) -> { - assertThat(context).hasSingleBean(PollerMetadata.class); - PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); - assertThat(metadata.getTrigger()) - .asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) - .satisfies((trigger) -> { - assertThat(trigger.getPeriodDuration()).isEqualTo(Duration.ofSeconds(5)); - assertThat(trigger.isFixedRate()).isFalse(); - }); - }); + .withPropertyValues("spring.integration.poller.fixed-delay=5000") + .run((context) -> { + assertThat(context).hasSingleBean(PollerMetadata.class); + PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); + assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) + .satisfies((trigger) -> { + assertThat(trigger.getPeriodDuration()).isEqualTo(Duration.ofSeconds(5)); + assertThat(trigger.isFixedRate()).isFalse(); + }); + }); } @Test void whenFixedRatePollerPropertyIsSetThenItIsReflectedAsFixedRatePropertyOfPeriodicTrigger() { this.contextRunner.withUserConfiguration(PollingConsumerConfiguration.class) - .withPropertyValues("spring.integration.poller.fixed-rate=5000").run((context) -> { - assertThat(context).hasSingleBean(PollerMetadata.class); - PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); - assertThat(metadata.getTrigger()) - .asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) - .satisfies((trigger) -> { - assertThat(trigger.getPeriodDuration()).isEqualTo(Duration.ofSeconds(5)); - assertThat(trigger.isFixedRate()).isTrue(); - }); - }); + .withPropertyValues("spring.integration.poller.fixed-rate=5000") + .run((context) -> { + assertThat(context).hasSingleBean(PollerMetadata.class); + PollerMetadata metadata = context.getBean(PollerMetadata.DEFAULT_POLLER, PollerMetadata.class); + assertThat(metadata.getTrigger()).asInstanceOf(InstanceOfAssertFactories.type(PeriodicTrigger.class)) + .satisfies((trigger) -> { + assertThat(trigger.getPeriodDuration()).isEqualTo(Duration.ofSeconds(5)); + assertThat(trigger.isFixedRate()).isTrue(); + }); + }); } @Test void integrationManagementLoggingIsEnabledByDefault() { - this.contextRunner.withBean(DirectChannel.class, DirectChannel::new).run((context) -> assertThat(context) - .getBean(DirectChannel.class).extracting(DirectChannel::isLoggingEnabled).isEqualTo(true)); + this.contextRunner.withBean(DirectChannel.class, DirectChannel::new) + .run((context) -> assertThat(context).getBean(DirectChannel.class) + .extracting(DirectChannel::isLoggingEnabled) + .isEqualTo(true)); } @Test void integrationManagementLoggingCanBeDisabled() { this.contextRunner.withPropertyValues("spring.integration.management.defaultLoggingEnabled=false") - .withBean(DirectChannel.class, DirectChannel::new).run((context) -> assertThat(context) - .getBean(DirectChannel.class).extracting(DirectChannel::isLoggingEnabled).isEqualTo(false)); + .withBean(DirectChannel.class, DirectChannel::new) + .run((context) -> assertThat(context).getBean(DirectChannel.class) + .extracting(DirectChannel::isLoggingEnabled) + .isEqualTo(false)); } @Test void integrationManagementInstrumentedWithObservation() { this.contextRunner.withPropertyValues("spring.integration.management.observation-patterns=testHandler") - .withBean("testHandler", LoggingHandler.class, () -> new LoggingHandler("warn")) - .withBean(ObservationRegistry.class, ObservationRegistry::create) - .withBean(BridgeHandler.class, BridgeHandler::new).run((context) -> { - assertThat(context).getBean("testHandler").extracting("observationRegistry").isNotNull(); - assertThat(context).getBean(BridgeHandler.class).extracting("observationRegistry") - .isEqualTo(ObservationRegistry.NOOP); - }); + .withBean("testHandler", LoggingHandler.class, () -> new LoggingHandler("warn")) + .withBean(ObservationRegistry.class, ObservationRegistry::create) + .withBean(BridgeHandler.class, BridgeHandler::new) + .run((context) -> { + assertThat(context).getBean("testHandler").extracting("observationRegistry").isNotNull(); + assertThat(context).getBean(BridgeHandler.class) + .extracting("observationRegistry") + .isEqualTo(ObservationRegistry.NOOP); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java index 8ee28ad832..20e89e4741 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ class IntegrationDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = IntegrationDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties.getJdbc()); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/springframework/integration/jdbc/schema-test.sql"); + .containsOnly("classpath:org/springframework/integration/jdbc/schema-test.sql"); then(dataSource).shouldHaveNoInteractions(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java index c11de4c54d..d6076db260 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationPropertiesEnvironmentPostProcessorTests.java @@ -56,8 +56,9 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { @Test void postProcessEnvironmentAddPropertySourceLast() { ConfigurableEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addLast(new MapPropertySource("test", - Collections.singletonMap("spring.integration.endpoint.no-auto-startup", "another*"))); + environment.getPropertySources() + .addLast(new MapPropertySource("test", + Collections.singletonMap("spring.integration.endpoint.no-auto-startup", "another*"))); new IntegrationPropertiesEnvironmentPostProcessor().postProcessEnvironment(environment, mock(SpringApplication.class)); assertThat(environment.getPropertySources().contains("META-INF/spring.integration.properties")).isTrue(); @@ -69,9 +70,10 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { ConfigurableEnvironment environment = new StandardEnvironment(); ClassPathResource unknown = new ClassPathResource("does-not-exist.properties", getClass()); assertThatThrownBy(() -> new IntegrationPropertiesEnvironmentPostProcessor() - .registerIntegrationPropertiesPropertySource(environment, unknown)) - .isInstanceOf(IllegalStateException.class).hasCauseInstanceOf(FileNotFoundException.class) - .hasMessageContaining(unknown.toString()); + .registerIntegrationPropertiesPropertySource(environment, unknown)) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(FileNotFoundException.class) + .hasMessageContaining(unknown.toString()); } @Test @@ -81,17 +83,17 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { new ClassPathResource("spring.integration.properties", getClass())); assertThat(environment.getProperty("spring.integration.channel.auto-create", Boolean.class)).isFalse(); assertThat(environment.getProperty("spring.integration.channel.max-unicast-subscribers", Integer.class)) - .isEqualTo(4); + .isEqualTo(4); assertThat(environment.getProperty("spring.integration.channel.max-broadcast-subscribers", Integer.class)) - .isEqualTo(6); + .isEqualTo(6); assertThat(environment.getProperty("spring.integration.error.require-subscribers", Boolean.class)).isFalse(); assertThat(environment.getProperty("spring.integration.error.ignore-failures", Boolean.class)).isFalse(); assertThat(environment.getProperty("spring.integration.endpoint.throw-exception-on-late-reply", Boolean.class)) - .isTrue(); + .isTrue(); assertThat(environment.getProperty("spring.integration.endpoint.read-only-headers", String.class)) - .isEqualTo("header1,header2"); + .isEqualTo("header1,header2"); assertThat(environment.getProperty("spring.integration.endpoint.no-auto-startup", String.class)) - .isEqualTo("testService,anotherService"); + .isEqualTo("testService,anotherService"); } @Test @@ -105,11 +107,11 @@ class IntegrationPropertiesEnvironmentPostProcessorTests { assertThat(ps).isInstanceOf(OriginLookup.class); OriginLookup originLookup = (OriginLookup) ps; assertThat(originLookup.getOrigin("spring.integration.channel.auto-create")) - .satisfies(textOrigin(resource, 0, 39)); + .satisfies(textOrigin(resource, 0, 39)); assertThat(originLookup.getOrigin("spring.integration.channel.max-unicast-subscribers")) - .satisfies(textOrigin(resource, 1, 50)); + .satisfies(textOrigin(resource, 1, 50)); assertThat(originLookup.getOrigin("spring.integration.channel.max-broadcast-subscribers")) - .satisfies(textOrigin(resource, 2, 52)); + .satisfies(textOrigin(resource, 2, 52)); } private Consumer textOrigin(Resource resource, int line, int column) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java index ca9fc101ce..3c14adc3ef 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfigurationTests.java @@ -92,16 +92,16 @@ import static org.mockito.Mockito.mock; class JacksonAutoConfigurationTests { protected final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)); @Test void doubleModuleRegistration() { this.contextRunner.withUserConfiguration(DoubleModulesConfig.class) - .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); - }); + .withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.writeValueAsString(new Foo())).isEqualTo("{\"foo\":\"bar\"}"); + }); } @Test @@ -110,7 +110,7 @@ class JacksonAutoConfigurationTests { assertThat(context).hasSingleBean(JsonMixinModule.class).hasSingleBean(JsonMixinModuleEntries.class); JsonMixinModuleEntries moduleEntries = context.getBean(JsonMixinModuleEntries.class); assertThat(moduleEntries).extracting("entries", InstanceOfAssertFactories.MAP) - .contains(entry(Person.class, EmptyMixin.class)); + .contains(entry(Person.class, EmptyMixin.class)); }); } @@ -136,10 +136,10 @@ class JacksonAutoConfigurationTests { void customDateFormatClass() { this.contextRunner.withPropertyValues( "spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); + }); } @Test @@ -162,10 +162,10 @@ class JacksonAutoConfigurationTests { void customPropertyNamingStrategyClass() { this.contextRunner.withPropertyValues( "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(mapper.getPropertyNamingStrategy()).isInstanceOf(SnakeCaseStrategy.class); + }); } @Test @@ -174,58 +174,55 @@ class JacksonAutoConfigurationTests { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()).isFalse(); assertThat(mapper.getSerializationConfig() - .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())).isTrue(); + .hasSerializationFeatures(SerializationFeature.INDENT_OUTPUT.getMask())).isTrue(); }); } @Test void disableSerializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.serialization.write_dates_as_timestamps:false") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()).isTrue(); - assertThat(mapper.getSerializationConfig() - .hasSerializationFeatures(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())) - .isFalse(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault()).isTrue(); + assertThat(mapper.getSerializationConfig() + .hasSerializationFeatures(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.getMask())).isFalse(); + }); } @Test void enableDeserializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.deserialization.use_big_decimal_for_floats:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()).isFalse(); - assertThat(mapper.getDeserializationConfig() - .hasDeserializationFeatures(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())) - .isTrue(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.enabledByDefault()).isFalse(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS.getMask())).isTrue(); + }); } @Test void disableDeserializationFeature() { this.contextRunner.withPropertyValues("spring.jackson.deserialization.fail-on-unknown-properties:false") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); - assertThat(mapper.getDeserializationConfig() - .hasDeserializationFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())) - .isFalse(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); + assertThat(mapper.getDeserializationConfig() + .hasDeserializationFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.getMask())).isFalse(); + }); } @Test void enableMapperFeature() { this.contextRunner.withPropertyValues("spring.jackson.mapper.require_setters_for_getters:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()).isFalse(); - - assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) - .isTrue(); - assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) - .isTrue(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + assertThat(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()).isFalse(); + + assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) + .isTrue(); + assertThat(mapper.getDeserializationConfig().isEnabled(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)) + .isTrue(); + }); } @Test @@ -259,12 +256,12 @@ class JacksonAutoConfigurationTests { @Test void enableGeneratorFeature() { this.contextRunner.withPropertyValues("spring.jackson.generator.strict_duplicate_detection:true") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - JsonGenerator.Feature feature = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION; - assertThat(feature.enabledByDefault()).isFalse(); - assertThat(mapper.getFactory().isEnabled(feature)).isTrue(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + JsonGenerator.Feature feature = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION; + assertThat(feature.enabledByDefault()).isFalse(); + assertThat(mapper.getFactory().isEnabled(feature)).isTrue(); + }); } @Test @@ -288,7 +285,7 @@ class JacksonAutoConfigurationTests { assertThat(mapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)).isFalse(); assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault()).isTrue(); assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) - .isFalse(); + .isFalse(); }); } @@ -306,7 +303,7 @@ class JacksonAutoConfigurationTests { this.contextRunner.run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) - .isEqualTo(JsonInclude.Include.USE_DEFAULTS); + .isEqualTo(JsonInclude.Include.USE_DEFAULTS); }); } @@ -315,18 +312,18 @@ class JacksonAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.jackson.default-property-inclusion:non_null").run((context) -> { ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion().getValueInclusion()) - .isEqualTo(JsonInclude.Include.NON_NULL); + .isEqualTo(JsonInclude.Include.NON_NULL); }); } @Test void customTimeZoneFormattingADate() { this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10", "spring.jackson.date-format:z") - .run((context) -> { - ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); - Date date = new Date(1436966242231L); - assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); - }); + .run((context) -> { + ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class).build(); + Date date = new Date(1436966242231L); + assertThat(objectMapper.writeValueAsString(date)).isEqualTo("\"GMT+10:00\""); + }); } @Test @@ -343,8 +340,9 @@ class JacksonAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.jackson.default-leniency:false").run((context) -> { ObjectMapper mapper = context.getBean(ObjectMapper.class); assertThatThrownBy(() -> mapper.readValue("{\"birthDate\": \"2010-12-30\"}", Person.class)) - .isInstanceOf(InvalidFormatException.class).hasMessageContaining("expected format") - .hasMessageContaining("yyyyMMdd"); + .isInstanceOf(InvalidFormatException.class) + .hasMessageContaining("expected format") + .hasMessageContaining("yyyyMMdd"); }); } @@ -373,13 +371,13 @@ class JacksonAutoConfigurationTests { @Test void constructorDetectorWithUsePropertiesBasedStrategy() { this.contextRunner.withPropertyValues("spring.jackson.constructor-detector=use-properties-based") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - ConstructorDetector cd = mapper.getDeserializationConfig().getConstructorDetector(); - assertThat(cd.singleArgMode()).isEqualTo(SingleArgConstructor.PROPERTIES); - assertThat(cd.requireCtorAnnotation()).isFalse(); - assertThat(cd.allowJDKTypeConstructors()).isFalse(); - }); + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + ConstructorDetector cd = mapper.getDeserializationConfig().getConstructorDetector(); + assertThat(cd.singleArgMode()).isEqualTo(SingleArgConstructor.PROPERTIES); + assertThat(cd.requireCtorAnnotation()).isFalse(); + assertThat(cd.allowJDKTypeConstructors()).isFalse(); + }); } @Test @@ -435,14 +433,14 @@ class JacksonAutoConfigurationTests { @Test void writeWithVisibility() { this.contextRunner - .withPropertyValues("spring.jackson.visibility.getter:none", "spring.jackson.visibility.field:any") - .run((context) -> { - ObjectMapper mapper = context.getBean(ObjectMapper.class); - String json = mapper.writeValueAsString(new VisibilityBean()); - assertThat(json).contains("property1"); - assertThat(json).contains("property2"); - assertThat(json).doesNotContain("property3"); - }); + .withPropertyValues("spring.jackson.visibility.getter:none", "spring.jackson.visibility.field:any") + .run((context) -> { + ObjectMapper mapper = context.getBean(ObjectMapper.class); + String json = mapper.writeValueAsString(new VisibilityBean()); + assertThat(json).contains("property1"); + assertThat(json).contains("property2"); + assertThat(json).doesNotContain("property3"); + }); } @Test @@ -473,16 +471,19 @@ class JacksonAutoConfigurationTests { RuntimeHints hints = new RuntimeHints(); new JacksonAutoConfigurationRuntimeHints().registerHints(hints, getClass().getClassLoader()); ReflectionHintsPredicates reflection = RuntimeHintsPredicates.reflection(); - Stream.of(fieldNames).map((name) -> reflection.onField(type, name)) - .forEach((predicate) -> assertThat(predicate).accepts(hints)); + Stream.of(fieldNames) + .map((name) -> reflection.onField(type, name)) + .forEach((predicate) -> assertThat(predicate).accepts(hints)); } private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, Class... configClasses) { this.contextRunner.withUserConfiguration(configClasses).run((context) -> { DeserializationConfig deserializationConfig = context.getBean(ObjectMapper.class) - .getDeserializationConfig(); + .getDeserializationConfig(); AnnotationIntrospector annotationIntrospector = deserializationConfig.getAnnotationIntrospector() - .allIntrospectors().iterator().next(); + .allIntrospectors() + .iterator() + .next(); assertThat(annotationIntrospector).hasFieldOrPropertyWithValue("creatorBinding", expectedMode); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java index c94f25503d..181eab518d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,8 +64,8 @@ import static org.mockito.Mockito.mock; class DataSourceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb-" + new Random().nextInt()); @Test void testDefaultDataSourceExists() { @@ -84,21 +84,22 @@ class DataSourceAutoConfigurationTests { @Test void testBadUrl() { this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:not-going-to-work") - .withClassLoader(new DisableEmbeddedDatabaseClassLoader()) - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .withClassLoader(new DisableEmbeddedDatabaseClassLoader()) + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test void testBadDriverClass() { this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.none.jdbcDriver") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("org.none.jdbcDriver")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("org.none.jdbcDriver")); } @Test void datasourceWhenConnectionFactoryPresentIsNotAutoConfigured() { this.contextRunner.withBean(ConnectionFactory.class, () -> mock(ConnectionFactory.class)) - .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); + .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); } @Test @@ -159,20 +160,22 @@ class DataSourceAutoConfigurationTests { @Test @SuppressWarnings("resource") void testEmbeddedTypeDefaultsUsername() { - this.contextRunner.withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", - "spring.datasource.url:jdbc:hsqldb:mem:testdb").run((context) -> { - DataSource bean = context.getBean(DataSource.class); - HikariDataSource pool = (HikariDataSource) bean; - assertThat(pool.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); - assertThat(pool.getUsername()).isEqualTo("sa"); - }); + this.contextRunner + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + "spring.datasource.url:jdbc:hsqldb:mem:testdb") + .run((context) -> { + DataSource bean = context.getBean(DataSource.class); + HikariDataSource pool = (HikariDataSource) bean; + assertThat(pool.getDriverClassName()).isEqualTo("org.hsqldb.jdbcDriver"); + assertThat(pool.getUsername()).isEqualTo("sa"); + }); } @Test void dataSourceWhenNoConnectionPoolsAreAvailableWithUrlDoesNotCreateDataSource() { this.contextRunner.with(hideConnectionPools()) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb") - .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testdb") + .run((context) -> assertThat(context).doesNotHaveBean(DataSource.class)); } /** @@ -182,19 +185,19 @@ class DataSourceAutoConfigurationTests { @Test void dataSourceWhenNoConnectionPoolsAreAvailableWithUrlAndTypeCreatesDataSource() { this.contextRunner.with(hideConnectionPools()) - .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", - "spring.datasource.url:jdbc:hsqldb:mem:testdb", - "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) - .run(this::containsOnlySimpleDriverDataSource); + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + "spring.datasource.url:jdbc:hsqldb:mem:testdb", + "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) + .run(this::containsOnlySimpleDriverDataSource); } @Test void explicitTypeSupportedDataSource() { this.contextRunner - .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", - "spring.datasource.url:jdbc:hsqldb:mem:testdb", - "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) - .run(this::containsOnlySimpleDriverDataSource); + .withPropertyValues("spring.datasource.driverClassName:org.hsqldb.jdbcDriver", + "spring.datasource.url:jdbc:hsqldb:mem:testdb", + "spring.datasource.type:" + SimpleDriverDataSource.class.getName()) + .run(this::containsOnlySimpleDriverDataSource); } private void containsOnlySimpleDriverDataSource(AssertableApplicationContext context) { @@ -204,38 +207,41 @@ class DataSourceAutoConfigurationTests { @Test void testExplicitDriverClassClearsUsername() { - this.contextRunner.withPropertyValues("spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), - "spring.datasource.url:jdbc:foo://localhost").run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - HikariDataSource dataSource = context.getBean(HikariDataSource.class); - assertThat(dataSource.getDriverClassName()).isEqualTo(DatabaseTestDriver.class.getName()); - assertThat(dataSource.getUsername()).isNull(); - }); + this.contextRunner + .withPropertyValues("spring.datasource.driverClassName:" + DatabaseTestDriver.class.getName(), + "spring.datasource.url:jdbc:foo://localhost") + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + HikariDataSource dataSource = context.getBean(HikariDataSource.class); + assertThat(dataSource.getDriverClassName()).isEqualTo(DatabaseTestDriver.class.getName()); + assertThat(dataSource.getUsername()).isNull(); + }); } @Test void testDefaultDataSourceCanBeOverridden() { this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class) - .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); + .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); } @Test void whenThereIsAUserProvidedDataSourceAnUnresolvablePlaceholderDoesNotCauseAProblem() { this.contextRunner.withUserConfiguration(TestDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.url:${UNRESOLVABLE_PLACEHOLDER}") - .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); + .withPropertyValues("spring.datasource.url:${UNRESOLVABLE_PLACEHOLDER}") + .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(BasicDataSource.class)); } @Test void whenThereIsAnEmptyUserProvidedDataSource() { - this.contextRunner.with(hideConnectionPools()).withPropertyValues("spring.datasource.url:") - .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(EmbeddedDatabase.class)); + this.contextRunner.with(hideConnectionPools()) + .withPropertyValues("spring.datasource.url:") + .run((context) -> assertThat(context).getBean(DataSource.class).isInstanceOf(EmbeddedDatabase.class)); } @Test void whenNoInitializationRelatedSpringDataSourcePropertiesAreConfiguredThenInitializationBacksOff() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); } private static Function hideConnectionPools() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java index 93364ecc4d..b8c365a8f5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJmxConfigurationTests.java @@ -51,26 +51,25 @@ import static org.assertj.core.api.Assertions.assertThat; class DataSourceJmxConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.url=jdbc:hsqldb:mem:test-" + UUID.randomUUID()) - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, DataSourceAutoConfiguration.class)); + .withPropertyValues("spring.datasource.url=jdbc:hsqldb:mem:test-" + UUID.randomUUID()) + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, DataSourceAutoConfiguration.class)); @Test void hikariAutoConfiguredCanUseRegisterMBeans() { String poolName = UUID.randomUUID().toString(); this.contextRunner - .withPropertyValues("spring.jmx.enabled=true", - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") - .run((context) -> { - assertThat(context).hasSingleBean(HikariDataSource.class); - HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - validateHikariMBeansRegistration(mBeanServer, poolName, true); - }); + .withPropertyValues("spring.jmx.enabled=true", "spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(HikariDataSource.class); + HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + validateHikariMBeansRegistration(mBeanServer, poolName, true); + }); } @Test @@ -78,103 +77,108 @@ class DataSourceJmxConfigurationTests { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); Set existingInstances = mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null); - this.contextRunner.withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.hikari.register-mbeans=true").run((context) -> { - assertThat(context).hasSingleBean(HikariDataSource.class); - HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - // We can't rely on the number of MBeans so we're checking that the - // pool and pool config MBeans were registered - assertThat(mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null)) - .hasSize(existingInstances.size() + 2); - }); + this.contextRunner + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(HikariDataSource.class); + HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + // We can't rely on the number of MBeans so we're checking that the + // pool and pool config MBeans were registered + assertThat(mBeanServer.queryMBeans(new ObjectName("com.zaxxer.hikari:type=*"), null)) + .hasSize(existingInstances.size() + 2); + }); } @Test void hikariAutoConfiguredUsesJmxFlag() { String poolName = UUID.randomUUID().toString(); - this.contextRunner.withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.jmx.enabled=false", "spring.datasource.name=" + poolName, - "spring.datasource.hikari.register-mbeans=true").run((context) -> { - assertThat(context).hasSingleBean(HikariDataSource.class); - HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - // Hikari can still register mBeans - validateHikariMBeansRegistration(ManagementFactory.getPlatformMBeanServer(), poolName, true); - }); + this.contextRunner + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.jmx.enabled=false", "spring.datasource.name=" + poolName, + "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(HikariDataSource.class); + HikariDataSource hikariDataSource = context.getBean(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + // Hikari can still register mBeans + validateHikariMBeansRegistration(ManagementFactory.getPlatformMBeanServer(), poolName, true); + }); } @Test void hikariProxiedCanUseRegisterMBeans() { String poolName = UUID.randomUUID().toString(); this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) - .withPropertyValues("spring.jmx.enabled=true", - "spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") - .run((context) -> { - assertThat(context).hasSingleBean(javax.sql.DataSource.class); - HikariDataSource hikariDataSource = context.getBean(javax.sql.DataSource.class) - .unwrap(HikariDataSource.class); - assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); - // Ensure that the pool has been initialized, triggering MBean - // registration - hikariDataSource.getConnection().close(); - MBeanServer mBeanServer = context.getBean(MBeanServer.class); - validateHikariMBeansRegistration(mBeanServer, poolName, true); - }); + .withPropertyValues("spring.jmx.enabled=true", "spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.name=" + poolName, "spring.datasource.hikari.register-mbeans=true") + .run((context) -> { + assertThat(context).hasSingleBean(javax.sql.DataSource.class); + HikariDataSource hikariDataSource = context.getBean(javax.sql.DataSource.class) + .unwrap(HikariDataSource.class); + assertThat(hikariDataSource.isRegisterMbeans()).isTrue(); + // Ensure that the pool has been initialized, triggering MBean + // registration + hikariDataSource.getConnection().close(); + MBeanServer mBeanServer = context.getBean(MBeanServer.class); + validateHikariMBeansRegistration(mBeanServer, poolName, true); + }); } private void validateHikariMBeansRegistration(MBeanServer mBeanServer, String poolName, boolean expected) throws MalformedObjectNameException { assertThat(mBeanServer.isRegistered(new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")"))) - .isEqualTo(expected); + .isEqualTo(expected); assertThat(mBeanServer.isRegistered(new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")"))) - .isEqualTo(expected); + .isEqualTo(expected); } @Test void tomcatDoesNotExposeMBeanPoolByDefault() { this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName()) - .run((context) -> assertThat(context).doesNotHaveBean(ConnectionPool.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ConnectionPool.class)); } @Test void tomcatAutoConfiguredCanExposeMBeanPool() { - this.contextRunner.withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), - "spring.datasource.tomcat.jmx-enabled=true").run((context) -> { - assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).hasSingleBean(ConnectionPool.class); - assertThat(context.getBean(DataSourceProxy.class).createPool().getJmxPool()) - .isSameAs(context.getBean(ConnectionPool.class)); - }); + this.contextRunner + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), + "spring.datasource.tomcat.jmx-enabled=true") + .run((context) -> { + assertThat(context).hasBean("dataSourceMBean"); + assertThat(context).hasSingleBean(ConnectionPool.class); + assertThat(context.getBean(DataSourceProxy.class).createPool().getJmxPool()) + .isSameAs(context.getBean(ConnectionPool.class)); + }); } @Test void tomcatProxiedCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceProxyConfiguration.class) - .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), - "spring.datasource.tomcat.jmx-enabled=true") - .run((context) -> { - assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); - }); + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), + "spring.datasource.tomcat.jmx-enabled=true") + .run((context) -> { + assertThat(context).hasBean("dataSourceMBean"); + assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); + }); } @Test void tomcatDelegateCanExposeMBeanPool() { this.contextRunner.withUserConfiguration(DataSourceDelegateConfiguration.class) - .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), - "spring.datasource.tomcat.jmx-enabled=true") - .run((context) -> { - assertThat(context).hasBean("dataSourceMBean"); - assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); - }); + .withPropertyValues("spring.datasource.type=" + DataSource.class.getName(), + "spring.datasource.tomcat.jmx-enabled=true") + .run((context) -> { + assertThat(context).hasBean("dataSourceMBean"); + assertThat(context).getBean("dataSourceMBean").isInstanceOf(ConnectionPool.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java index cb528d9492..a1d2cafc8b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceJsonSerializationTests.java @@ -56,7 +56,7 @@ class DataSourceJsonSerializationTests { void serializerFactory() throws Exception { DataSource dataSource = new DataSource(); SerializerFactory factory = BeanSerializerFactory.instance - .withSerializerModifier(new GenericSerializerModifier()); + .withSerializerModifier(new GenericSerializerModifier()); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializerFactory(factory); String value = mapper.writeValueAsString(dataSource); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java index 2a60b090e7..981b89ff1a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java @@ -66,7 +66,8 @@ class DataSourcePropertiesTests { properties.setBeanClassLoader(new FilteredClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); properties.afterPropertiesSet(); assertThatExceptionOfType(DataSourceProperties.DataSourceBeanCreationException.class) - .isThrownBy(properties::determineUrl).withMessageContaining("Failed to determine suitable jdbc url"); + .isThrownBy(properties::determineUrl) + .withMessageContaining("Failed to determine suitable jdbc url"); } @Test @@ -84,7 +85,8 @@ class DataSourcePropertiesTests { properties.setGenerateUniqueName(false); properties.setEmbeddedDatabaseConnection(EmbeddedDatabaseConnection.NONE); assertThatExceptionOfType(DataSourceProperties.DataSourceBeanCreationException.class) - .isThrownBy(properties::determineUrl).withMessageContaining("Failed to determine suitable jdbc url"); + .isThrownBy(properties::determineUrl) + .withMessageContaining("Failed to determine suitable jdbc url"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java index 9d9d42e25f..a469c0495a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceTransactionManagerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,9 +42,9 @@ import static org.mockito.Mockito.mock; class DataSourceTransactionManagerAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:test-" + UUID.randomUUID()); + .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:test-" + UUID.randomUUID()); @Test void transactionManagerWithoutDataSourceIsNotConfigured() { @@ -54,63 +54,61 @@ class DataSourceTransactionManagerAutoConfigurationTests { @Test void transactionManagerWithExistingDataSourceIsConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(TransactionManager.class) - .hasSingleBean(JdbcTransactionManager.class); - assertThat(context.getBean(JdbcTransactionManager.class).getDataSource()) - .isSameAs(context.getBean(DataSource.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(TransactionManager.class).hasSingleBean(JdbcTransactionManager.class); + assertThat(context.getBean(JdbcTransactionManager.class).getDataSource()) + .isSameAs(context.getBean(DataSource.class)); + }); } @Test void transactionManagerWithCustomizationIsConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.transaction.default-timeout=1m", - "spring.transaction.rollback-on-commit-failure=true") - .run((context) -> { - assertThat(context).hasSingleBean(TransactionManager.class) - .hasSingleBean(JdbcTransactionManager.class); - JdbcTransactionManager transactionManager = context.getBean(JdbcTransactionManager.class); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(60); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + .withPropertyValues("spring.transaction.default-timeout=1m", + "spring.transaction.rollback-on-commit-failure=true") + .run((context) -> { + assertThat(context).hasSingleBean(TransactionManager.class).hasSingleBean(JdbcTransactionManager.class); + JdbcTransactionManager transactionManager = context.getBean(JdbcTransactionManager.class); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(60); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void transactionManagerWithExistingTransactionManagerIsNotOverridden() { this.contextRunner - .withBean("myTransactionManager", TransactionManager.class, () -> mock(TransactionManager.class)) - .run((context) -> assertThat(context).hasSingleBean(TransactionManager.class) - .hasBean("myTransactionManager")); + .withBean("myTransactionManager", TransactionManager.class, () -> mock(TransactionManager.class)) + .run((context) -> assertThat(context).hasSingleBean(TransactionManager.class) + .hasBean("myTransactionManager")); } @Test // gh-24321 void transactionManagerWithDaoExceptionTranslationDisabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.dao.exceptiontranslation.enabled=false") - .run((context) -> assertThat(context.getBean(TransactionManager.class)) - .isExactlyInstanceOf(DataSourceTransactionManager.class)); + .withPropertyValues("spring.dao.exceptiontranslation.enabled=false") + .run((context) -> assertThat(context.getBean(TransactionManager.class)) + .isExactlyInstanceOf(DataSourceTransactionManager.class)); } @Test // gh-24321 void transactionManagerWithDaoExceptionTranslationEnabled() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.dao.exceptiontranslation.enabled=true") - .run((context) -> assertThat(context.getBean(TransactionManager.class)) - .isExactlyInstanceOf(JdbcTransactionManager.class)); + .withPropertyValues("spring.dao.exceptiontranslation.enabled=true") + .run((context) -> assertThat(context.getBean(TransactionManager.class)) + .isExactlyInstanceOf(JdbcTransactionManager.class)); } @Test // gh-24321 void transactionManagerWithDaoExceptionTranslationDefault() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(TransactionManager.class)) - .isExactlyInstanceOf(JdbcTransactionManager.class)); + .run((context) -> assertThat(context.getBean(TransactionManager.class)) + .isExactlyInstanceOf(JdbcTransactionManager.class)); } @Test void transactionWithMultipleDataSourcesIsNotConfigured() { this.contextRunner.withUserConfiguration(MultiDataSourceConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(TransactionManager.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TransactionManager.class)); } @Test @@ -118,7 +116,7 @@ class DataSourceTransactionManagerAutoConfigurationTests { this.contextRunner.withUserConfiguration(MultiDataSourceUsingPrimaryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(TransactionManager.class).hasSingleBean(JdbcTransactionManager.class); assertThat(context.getBean(JdbcTransactionManager.class).getDataSource()) - .isSameAs(context.getBean("test1DataSource")); + .isSameAs(context.getBean("test1DataSource")); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java index ebd28e9cfb..e308663eb3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -35,8 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; class HikariDataSourceConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName()); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.type=" + HikariDataSource.class.getName()); @Test void testDataSourceExists() { @@ -48,25 +48,27 @@ class HikariDataSourceConfigurationTests { @Test void testDataSourcePropertiesOverridden() { - this.contextRunner.withPropertyValues("spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", - "spring.datasource.hikari.max-lifetime=1234").run((context) -> { - HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); - assertThat(ds.getMaxLifetime()).isEqualTo(1234); - }); + this.contextRunner + .withPropertyValues("spring.datasource.hikari.jdbc-url=jdbc:foo//bar/spam", + "spring.datasource.hikari.max-lifetime=1234") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getJdbcUrl()).isEqualTo("jdbc:foo//bar/spam"); + assertThat(ds.getMaxLifetime()).isEqualTo(1234); + }); } @Test void testDataSourceGenericPropertiesOverridden() { this.contextRunner - .withPropertyValues( - "spring.datasource.hikari.data-source-properties.dataSourceClassName=org.h2.JDBCDataSource") - .run((context) -> { - HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) - .isEqualTo("org.h2.JDBCDataSource"); - - }); + .withPropertyValues( + "spring.datasource.hikari.data-source-properties.dataSourceClassName=org.h2.JDBCDataSource") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getDataSourceProperties().getProperty("dataSourceClassName")) + .isEqualTo("org.h2.JDBCDataSource"); + + }); } @Test @@ -89,11 +91,11 @@ class HikariDataSourceConfigurationTests { @Test void poolNameTakesPrecedenceOverName() { this.contextRunner - .withPropertyValues("spring.datasource.name=myDS", "spring.datasource.hikari.pool-name=myHikariDS") - .run((context) -> { - HikariDataSource ds = context.getBean(HikariDataSource.class); - assertThat(ds.getPoolName()).isEqualTo("myHikariDS"); - }); + .withPropertyValues("spring.datasource.name=myDS", "spring.datasource.hikari.pool-name=myHikariDS") + .run((context) -> { + HikariDataSource ds = context.getBean(HikariDataSource.class); + assertThat(ds.getPoolName()).isEqualTo("myHikariDS"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java index 0937cdfbb3..9dafdc04b7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/HikariDriverConfigurationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -40,15 +40,15 @@ class HikariDriverConfigurationFailureAnalyzerTests { void failureAnalysisIsPerformed() { FailureAnalysis failureAnalysis = performAnalysis(TestConfiguration.class); assertThat(failureAnalysis).isNotNull(); - assertThat(failureAnalysis.getDescription()).isEqualTo( - "Configuration of the Hikari connection pool failed: 'dataSourceClassName' is not supported."); + assertThat(failureAnalysis.getDescription()) + .isEqualTo("Configuration of the Hikari connection pool failed: 'dataSourceClassName' is not supported."); assertThat(failureAnalysis.getAction()).contains("Spring Boot auto-configures only a driver"); } @Test void unrelatedIllegalStateExceptionIsSkipped() { FailureAnalysis failureAnalysis = new HikariDriverConfigurationFailureAnalyzer() - .analyze(new RuntimeException("foo", new IllegalStateException("bar"))); + .analyze(new RuntimeException("foo", new IllegalStateException("bar"))); assertThat(failureAnalysis).isNull(); } @@ -60,9 +60,10 @@ class HikariDriverConfigurationFailureAnalyzerTests { private BeanCreationException createFailure(Class configuration) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - TestPropertyValues.of("spring.datasource.type=" + HikariDataSource.class.getName(), - "spring.datasource.hikari.data-source-class-name=com.example.Foo", "spring.sql.init.mode=always") - .applyTo(context); + TestPropertyValues + .of("spring.datasource.type=" + HikariDataSource.class.getName(), + "spring.datasource.hikari.data-source-class-name=com.example.Foo", "spring.sql.init.mode=always") + .applyTo(context); context.register(configuration); try { context.refresh(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java index 2c7a45b5c9..e9424bd2bd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/JdbcTemplateAutoConfigurationTests.java @@ -49,8 +49,9 @@ import static org.mockito.Mockito.mock; class JdbcTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true").withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class)); @Test void testJdbcTemplateExists() { @@ -66,15 +67,17 @@ class JdbcTemplateAutoConfigurationTests { @Test void testJdbcTemplateWithCustomProperties() { - this.contextRunner.withPropertyValues("spring.jdbc.template.fetch-size:100", - "spring.jdbc.template.query-timeout:60", "spring.jdbc.template.max-rows:1000").run((context) -> { - assertThat(context).hasSingleBean(JdbcOperations.class); - JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); - assertThat(jdbcTemplate.getDataSource()).isNotNull(); - assertThat(jdbcTemplate.getFetchSize()).isEqualTo(100); - assertThat(jdbcTemplate.getQueryTimeout()).isEqualTo(60); - assertThat(jdbcTemplate.getMaxRows()).isEqualTo(1000); - }); + this.contextRunner + .withPropertyValues("spring.jdbc.template.fetch-size:100", "spring.jdbc.template.query-timeout:60", + "spring.jdbc.template.max-rows:1000") + .run((context) -> { + assertThat(context).hasSingleBean(JdbcOperations.class); + JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); + assertThat(jdbcTemplate.getDataSource()).isNotNull(); + assertThat(jdbcTemplate.getFetchSize()).isEqualTo(100); + assertThat(jdbcTemplate.getQueryTimeout()).isEqualTo(60); + assertThat(jdbcTemplate.getMaxRows()).isEqualTo(1000); + }); } @Test @@ -106,7 +109,7 @@ class JdbcTemplateAutoConfigurationTests { @Test void testMultiJdbcTemplate() { this.contextRunner.withUserConfiguration(MultiJdbcTemplateConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class)); + .run((context) -> assertThat(context).doesNotHaveBean(NamedParameterJdbcOperations.class)); } @Test @@ -115,7 +118,7 @@ class JdbcTemplateAutoConfigurationTests { assertThat(context).hasSingleBean(JdbcOperations.class); assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(JdbcTemplate.class).getDataSource()) - .isEqualTo(context.getBean("test1DataSource")); + .isEqualTo(context.getBean("test1DataSource")); }); } @@ -124,7 +127,7 @@ class JdbcTemplateAutoConfigurationTests { this.contextRunner.withUserConfiguration(MultiJdbcTemplateUsingPrimaryConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(NamedParameterJdbcTemplate.class).getJdbcOperations()) - .isEqualTo(context.getBean("test1Template")); + .isEqualTo(context.getBean("test1Template")); }); } @@ -141,59 +144,64 @@ class JdbcTemplateAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(NamedParameterJdbcOperations.class); assertThat(context.getBean(NamedParameterJdbcOperations.class)) - .isEqualTo(context.getBean("customNamedParameterJdbcOperations")); + .isEqualTo(context.getBean("customNamedParameterJdbcOperations")); }); } @Test void testDependencyToScriptBasedDataSourceInitialization() { this.contextRunner.withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) - .withUserConfiguration(DataSourceInitializationValidator.class).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceInitializationValidator.class).count).isOne(); - }); + .withUserConfiguration(DataSourceInitializationValidator.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(DataSourceInitializationValidator.class).count).isOne(); + }); } @Test void testDependencyToFlyway() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) - .withPropertyValues("spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceMigrationValidator.class).count).isZero(); - }); + .withPropertyValues("spring.flyway.locations:classpath:db/city") + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(DataSourceMigrationValidator.class).count).isZero(); + }); } @Test void testDependencyToFlywayWithJdbcTemplateMixed() { this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) - .withPropertyValues("spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); - assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isZero(); - }); + .withPropertyValues("spring.flyway.locations:classpath:db/city") + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); + assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isZero(); + }); } @Test void testDependencyToLiquibase() { this.contextRunner.withUserConfiguration(DataSourceMigrationValidator.class) - .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(DataSourceMigrationValidator.class).count).isZero(); - }); + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(DataSourceMigrationValidator.class).count).isZero(); + }); } @Test void testDependencyToLiquibaseWithJdbcTemplateMixed() { this.contextRunner.withUserConfiguration(NamedParameterDataSourceMigrationValidator.class) - .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); - assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isZero(); - }); + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(JdbcTemplate.class)).isNotNull(); + assertThat(context.getBean(NamedParameterDataSourceMigrationValidator.class).count).isZero(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java index 89718788e5..856fe0b408 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/OracleUcpDataSourceConfigurationTests.java @@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; class OracleUcpDataSourceConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.datasource.type=" + PoolDataSource.class.getName()); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.datasource.type=" + PoolDataSource.class.getName()); @Test void testDataSourceExists() { @@ -54,21 +54,23 @@ class OracleUcpDataSourceConfigurationTests { @Test void testDataSourcePropertiesOverridden() { - this.contextRunner.withPropertyValues("spring.datasource.oracleucp.url=jdbc:foo//bar/spam", - "spring.datasource.oracleucp.max-idle-time=1234").run((context) -> { - PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); - assertThat(ds.getURL()).isEqualTo("jdbc:foo//bar/spam"); - assertThat(ds.getMaxIdleTime()).isEqualTo(1234); - }); + this.contextRunner + .withPropertyValues("spring.datasource.oracleucp.url=jdbc:foo//bar/spam", + "spring.datasource.oracleucp.max-idle-time=1234") + .run((context) -> { + PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); + assertThat(ds.getURL()).isEqualTo("jdbc:foo//bar/spam"); + assertThat(ds.getMaxIdleTime()).isEqualTo(1234); + }); } @Test void testDataSourceConnectionPropertiesOverridden() { this.contextRunner.withPropertyValues("spring.datasource.oracleucp.connection-properties.autoCommit=false") - .run((context) -> { - PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); - assertThat(ds.getConnectionProperty("autoCommit")).isEqualTo("false"); - }); + .run((context) -> { + PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); + assertThat(ds.getConnectionProperty("autoCommit")).isEqualTo("false"); + }); } @Test @@ -97,11 +99,13 @@ class OracleUcpDataSourceConfigurationTests { @Test void poolNameTakesPrecedenceOverName() { - this.contextRunner.withPropertyValues("spring.datasource.name=myDS", - "spring.datasource.oracleucp.connection-pool-name=myOracleUcpDS").run((context) -> { - PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); - assertThat(ds.getConnectionPoolName()).isEqualTo("myOracleUcpDS"); - }); + this.contextRunner + .withPropertyValues("spring.datasource.name=myDS", + "spring.datasource.oracleucp.connection-pool-name=myOracleUcpDS") + .run((context) -> { + PoolDataSourceImpl ds = context.getBean(PoolDataSourceImpl.class); + assertThat(ds.getConnectionPoolName()).isEqualTo("myOracleUcpDS"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java index 5c0028b218..ff19386891 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/TomcatDataSourceConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -66,11 +66,11 @@ class TomcatDataSourceConfigurationTests { void testDataSourcePropertiesOverridden() throws Exception { this.context.register(TomcatDataSourceConfiguration.class); TestPropertyValues - .of(PREFIX + "url:jdbc:h2:mem:testdb", PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", - PREFIX + "testOnReturn:true", PREFIX + "timeBetweenEvictionRunsMillis:10000", - PREFIX + "minEvictableIdleTimeMillis:12345", PREFIX + "maxWait:1234", - PREFIX + "jdbcInterceptors:SlowQueryReport", PREFIX + "validationInterval:9999") - .applyTo(this.context); + .of(PREFIX + "url:jdbc:h2:mem:testdb", PREFIX + "testWhileIdle:true", PREFIX + "testOnBorrow:true", + PREFIX + "testOnReturn:true", PREFIX + "timeBetweenEvictionRunsMillis:10000", + PREFIX + "minEvictableIdleTimeMillis:12345", PREFIX + "maxWait:1234", + PREFIX + "jdbcInterceptors:SlowQueryReport", PREFIX + "validationInterval:9999") + .applyTo(this.context); this.context.refresh(); org.apache.tomcat.jdbc.pool.DataSource ds = this.context.getBean(org.apache.tomcat.jdbc.pool.DataSource.class); assertThat(ds.getUrl()).isEqualTo("jdbc:h2:mem:testdb"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java index 336de2b14e..54ff0354f3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/XADataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -67,15 +67,15 @@ class XADataSourceAutoConfigurationTests { @Test void createNonEmbeddedFromXAProperties() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(XADataSourceAutoConfiguration.class)) - .withUserConfiguration(FromProperties.class) - .withClassLoader(new FilteredClassLoader("org.h2.Driver", "org.hsqldb.jdbcDriver")) - .withPropertyValues("spring.datasource.xa.data-source-class-name:com.ibm.db2.jcc.DB2XADataSource", - "spring.datasource.xa.properties.user:test", "spring.datasource.xa.properties.password:secret") - .run((context) -> { - MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); - XADataSource xaDataSource = wrapper.getXaDataSource(); - assertThat(xaDataSource).isInstanceOf(DB2XADataSource.class); - }); + .withUserConfiguration(FromProperties.class) + .withClassLoader(new FilteredClassLoader("org.h2.Driver", "org.hsqldb.jdbcDriver")) + .withPropertyValues("spring.datasource.xa.data-source-class-name:com.ibm.db2.jcc.DB2XADataSource", + "spring.datasource.xa.properties.user:test", "spring.datasource.xa.properties.password:secret") + .run((context) -> { + MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class); + XADataSource xaDataSource = wrapper.getXaDataSource(); + assertThat(xaDataSource).isInstanceOf(DB2XADataSource.class); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java index a6de7ce60a..448f788474 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,8 @@ import static org.assertj.core.api.Assertions.assertThat; class JerseyAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)) - .withUserConfiguration(ResourceConfigConfiguration.class); + .withConfiguration(AutoConfigurations.of(JerseyAutoConfiguration.class)) + .withUserConfiguration(ResourceConfigConfiguration.class); @Test void requestContextFilterRegistrationIsAutoConfigured() { @@ -72,29 +72,40 @@ class JerseyAutoConfigurationTests { void whenJaxbIsAvailableTheObjectMapperIsCustomizedWithAnAnnotationIntrospector() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)).run((context) -> { ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors().stream() - .filter(JakartaXmlBindAnnotationIntrospector.class::isInstance)).hasSize(1); + assertThat(objectMapper.getSerializationConfig() + .getAnnotationIntrospector() + .allIntrospectors() + .stream() + .filter(JakartaXmlBindAnnotationIntrospector.class::isInstance)).hasSize(1); }); } @Test void whenJaxbIsNotAvailableTheObjectMapperCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader("jakarta.xml.bind.annotation")).run((context) -> { - ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors() - .stream().filter(JakartaXmlBindAnnotationIntrospector.class::isInstance)).isEmpty(); - }); + .withClassLoader(new FilteredClassLoader("jakarta.xml.bind.annotation")) + .run((context) -> { + ObjectMapper objectMapper = context.getBean(ObjectMapper.class); + assertThat(objectMapper.getSerializationConfig() + .getAnnotationIntrospector() + .allIntrospectors() + .stream() + .filter(JakartaXmlBindAnnotationIntrospector.class::isInstance)).isEmpty(); + }); } @Test void whenJacksonJaxbModuleIsNotAvailableTheObjectMapperCustomizationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(JakartaXmlBindAnnotationIntrospector.class)).run((context) -> { - ObjectMapper objectMapper = context.getBean(ObjectMapper.class); - assertThat(objectMapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors() - .stream().filter(JakartaXmlBindAnnotationIntrospector.class::isInstance)).isEmpty(); - }); + .withClassLoader(new FilteredClassLoader(JakartaXmlBindAnnotationIntrospector.class)) + .run((context) -> { + ObjectMapper objectMapper = context.getBean(ObjectMapper.class); + assertThat(objectMapper.getSerializationConfig() + .getAnnotationIntrospector() + .allIntrospectors() + .stream() + .filter(JakartaXmlBindAnnotationIntrospector.class::isInstance)).isEmpty(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java index 7b3afa8999..17692a1b7c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsAutoConfigurationTests.java @@ -61,7 +61,7 @@ import static org.mockito.Mockito.mock; class JmsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); @Test void testDefaultJmsConfiguration() { @@ -84,28 +84,28 @@ class JmsAutoConfigurationTests { @Test void testConnectionFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration2.class) - .run((context) -> assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)) - .containsOnlyKeys("customConnectionFactory")); + .run((context) -> assertThat(context.getBeansOfType(ActiveMQConnectionFactory.class)) + .containsOnlyKeys("customConnectionFactory")); } @Test void testJmsTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration3.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).getPriority()).isEqualTo(999)); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).getPriority()).isEqualTo(999)); } @Test void testJmsMessagingTemplateBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration5.class) - .run((context) -> assertThat(context.getBean(JmsMessagingTemplate.class).getDefaultDestinationName()) - .isEqualTo("fooBar")); + .run((context) -> assertThat(context.getBean(JmsMessagingTemplate.class).getDefaultDestinationName()) + .isEqualTo("fooBar")); } @Test void testJmsTemplateBackOffEverything() { this.contextRunner - .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class) - .run(this::testJmsTemplateBackOffEverything); + .withUserConfiguration(TestConfiguration2.class, TestConfiguration3.class, TestConfiguration5.class) + .run(this::testJmsTemplateBackOffEverything); } private void testJmsTemplateBackOffEverything(AssertableApplicationContext loaded) { @@ -120,32 +120,32 @@ class JmsAutoConfigurationTests { @Test void testEnableJmsCreateDefaultContainerFactory() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .run((context) -> assertThat(context) - .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) - .isExactlyInstanceOf(DefaultJmsListenerContainerFactory.class)); + .run((context) -> assertThat(context) + .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) + .isExactlyInstanceOf(DefaultJmsListenerContainerFactory.class)); } @Test void testJmsListenerContainerFactoryBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration6.class, EnableJmsConfiguration.class) - .run((context) -> assertThat(context) - .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) - .isExactlyInstanceOf(SimpleJmsListenerContainerFactory.class)); + .run((context) -> assertThat(context) + .getBean("jmsListenerContainerFactory", JmsListenerContainerFactory.class) + .isExactlyInstanceOf(SimpleJmsListenerContainerFactory.class)); } @Test void jmsListenerContainerFactoryWhenMultipleConnectionFactoryBeansShouldBackOff() { this.contextRunner.withUserConfiguration(TestConfiguration10.class) - .run((context) -> assertThat(context).doesNotHaveBean(JmsListenerContainerFactory.class)); + .run((context) -> assertThat(context).doesNotHaveBean(JmsListenerContainerFactory.class)); } @Test void testJmsListenerContainerFactoryWithCustomSettings() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .withPropertyValues("spring.jms.listener.autoStartup=false", - "spring.jms.listener.acknowledgeMode=client", "spring.jms.listener.concurrency=2", - "spring.jms.listener.receiveTimeout=2s", "spring.jms.listener.maxConcurrency=10") - .run(this::testJmsListenerContainerFactoryWithCustomSettings); + .withPropertyValues("spring.jms.listener.autoStartup=false", "spring.jms.listener.acknowledgeMode=client", + "spring.jms.listener.concurrency=2", "spring.jms.listener.receiveTimeout=2s", + "spring.jms.listener.maxConcurrency=10") + .run(this::testJmsListenerContainerFactoryWithCustomSettings); } private void testJmsListenerContainerFactoryWithCustomSettings(AssertableApplicationContext loaded) { @@ -160,7 +160,7 @@ class JmsAutoConfigurationTests { @Test void testJmsListenerContainerFactoryWithDefaultSettings() { this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .run(this::testJmsListenerContainerFactoryWithDefaultSettings); + .run(this::testJmsListenerContainerFactoryWithDefaultSettings); } private void testJmsListenerContainerFactoryWithDefaultSettings(AssertableApplicationContext loaded) { @@ -171,22 +171,22 @@ class JmsAutoConfigurationTests { @Test void testDefaultContainerFactoryWithJtaTransactionManager() { this.contextRunner.withUserConfiguration(TestConfiguration7.class, EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.isSessionTransacted()).isFalse(); - assertThat(container).hasFieldOrPropertyWithValue("transactionManager", - context.getBean(JtaTransactionManager.class)); - }); + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isFalse(); + assertThat(container).hasFieldOrPropertyWithValue("transactionManager", + context.getBean(JtaTransactionManager.class)); + }); } @Test void testDefaultContainerFactoryNonJtaTransactionManager() { this.contextRunner.withUserConfiguration(TestConfiguration8.class, EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.isSessionTransacted()).isTrue(); - assertThat(container).hasFieldOrPropertyWithValue("transactionManager", null); - }); + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.isSessionTransacted()).isTrue(); + assertThat(container).hasFieldOrPropertyWithValue("transactionManager", null); + }); } @Test @@ -201,30 +201,32 @@ class JmsAutoConfigurationTests { @Test void testDefaultContainerFactoryWithMessageConverters() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class, EnableJmsConfiguration.class) - .run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); - }); + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + }); } @Test void testDefaultContainerFactoryWithExceptionListener() { ExceptionListener exceptionListener = mock(ExceptionListener.class); this.contextRunner.withUserConfiguration(EnableJmsConfiguration.class) - .withBean(ExceptionListener.class, () -> exceptionListener).run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); - assertThat(container.getExceptionListener()).isSameAs(exceptionListener); - }); + .withBean(ExceptionListener.class, () -> exceptionListener) + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "jmsListenerContainerFactory"); + assertThat(container.getExceptionListener()).isSameAs(exceptionListener); + }); } @Test void testCustomContainerFactoryWithConfigurer() { this.contextRunner.withUserConfiguration(TestConfiguration9.class, EnableJmsConfiguration.class) - .withPropertyValues("spring.jms.listener.autoStartup=false").run((context) -> { - DefaultMessageListenerContainer container = getContainer(context, "customListenerContainerFactory"); - assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); - assertThat(container.isAutoStartup()).isFalse(); - }); + .withPropertyValues("spring.jms.listener.autoStartup=false") + .run((context) -> { + DefaultMessageListenerContainer container = getContainer(context, "customListenerContainerFactory"); + assertThat(container.getCacheLevel()).isEqualTo(DefaultMessageListenerContainer.CACHE_CONSUMER); + assertThat(container.isAutoStartup()).isFalse(); + }); } private DefaultMessageListenerContainer getContainer(AssertableApplicationContext loaded, String name) { @@ -244,29 +246,29 @@ class JmsAutoConfigurationTests { @Test void testJmsTemplateWithDestinationResolver() { this.contextRunner.withUserConfiguration(DestinationResolversConfiguration.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).getDestinationResolver()) - .isSameAs(context.getBean("myDestinationResolver"))); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).getDestinationResolver()) + .isSameAs(context.getBean("myDestinationResolver"))); } @Test void testJmsTemplateFullCustomization() { this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.class) - .withPropertyValues("spring.jms.template.default-destination=testQueue", - "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", - "spring.jms.template.priority=6", "spring.jms.template.time-to-live=6000", - "spring.jms.template.receive-timeout=2000") - .run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - assertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); - assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(jmsTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); - assertThat(jmsTemplate.getDeliveryDelay()).isEqualTo(500); - assertThat(jmsTemplate.getDeliveryMode()).isOne(); - assertThat(jmsTemplate.getPriority()).isEqualTo(6); - assertThat(jmsTemplate.getTimeToLive()).isEqualTo(6000); - assertThat(jmsTemplate.isExplicitQosEnabled()).isTrue(); - assertThat(jmsTemplate.getReceiveTimeout()).isEqualTo(2000); - }); + .withPropertyValues("spring.jms.template.default-destination=testQueue", + "spring.jms.template.delivery-delay=500", "spring.jms.template.delivery-mode=non-persistent", + "spring.jms.template.priority=6", "spring.jms.template.time-to-live=6000", + "spring.jms.template.receive-timeout=2000") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + assertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + assertThat(jmsTemplate.isPubSubDomain()).isFalse(); + assertThat(jmsTemplate.getDefaultDestinationName()).isEqualTo("testQueue"); + assertThat(jmsTemplate.getDeliveryDelay()).isEqualTo(500); + assertThat(jmsTemplate.getDeliveryMode()).isOne(); + assertThat(jmsTemplate.getPriority()).isEqualTo(6); + assertThat(jmsTemplate.getTimeToLive()).isEqualTo(6000); + assertThat(jmsTemplate.isExplicitQosEnabled()).isTrue(); + assertThat(jmsTemplate.getReceiveTimeout()).isEqualTo(2000); + }); } @Test @@ -280,40 +282,42 @@ class JmsAutoConfigurationTests { @Test void testPubSubDisabledByDefault() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isFalse()); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isFalse()); } @Test void testJmsTemplatePostProcessedSoThatPubSubIsTrue() { this.contextRunner.withUserConfiguration(TestConfiguration4.class) - .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isTrue()); + .run((context) -> assertThat(context.getBean(JmsTemplate.class).isPubSubDomain()).isTrue()); } @Test void testPubSubDomainActive() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.jms.pubSubDomain:true").run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - DefaultMessageListenerContainer defaultMessageListenerContainer = context - .getBean(DefaultJmsListenerContainerFactory.class) - .createListenerContainer(mock(JmsListenerEndpoint.class)); - assertThat(jmsTemplate.isPubSubDomain()).isTrue(); - assertThat(defaultMessageListenerContainer.isPubSubDomain()).isTrue(); - }); + .withPropertyValues("spring.jms.pubSubDomain:true") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + DefaultMessageListenerContainer defaultMessageListenerContainer = context + .getBean(DefaultJmsListenerContainerFactory.class) + .createListenerContainer(mock(JmsListenerEndpoint.class)); + assertThat(jmsTemplate.isPubSubDomain()).isTrue(); + assertThat(defaultMessageListenerContainer.isPubSubDomain()).isTrue(); + }); } @Test void testPubSubDomainOverride() { this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.jms.pubSubDomain:false").run((context) -> { - assertThat(context).hasSingleBean(JmsTemplate.class); - assertThat(context).hasSingleBean(ConnectionFactory.class); - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory factory = context.getBean(ConnectionFactory.class); - assertThat(jmsTemplate).isNotNull(); - assertThat(jmsTemplate.isPubSubDomain()).isFalse(); - assertThat(factory).isNotNull().isEqualTo(jmsTemplate.getConnectionFactory()); - }); + .withPropertyValues("spring.jms.pubSubDomain:false") + .run((context) -> { + assertThat(context).hasSingleBean(JmsTemplate.class); + assertThat(context).hasSingleBean(ConnectionFactory.class); + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory factory = context.getBean(ConnectionFactory.class); + assertThat(jmsTemplate).isNotNull(); + assertThat(jmsTemplate.isPubSubDomain()).isFalse(); + assertThat(factory).isNotNull().isEqualTo(jmsTemplate.getConnectionFactory()); + }); } private String getBrokerUrl(CachingConnectionFactory connectionFactory) { @@ -329,9 +333,9 @@ class JmsAutoConfigurationTests { @Test void enableJmsAutomatically() { this.contextRunner.withUserConfiguration(NoEnableJmsConfiguration.class) - .run((context) -> assertThat(context) - .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) - .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME)); + .run((context) -> assertThat(context) + .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) + .hasBean(JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java index 50b1c3df83..7ddbecd5c8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JmsPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -83,7 +83,7 @@ class JmsPropertiesTests { @Test void defaultReceiveTimeoutMatchesListenerContainersDefault() { assertThat(new JmsProperties().getListener().getReceiveTimeout()) - .hasMillis(AbstractPollingMessageListenerContainer.DEFAULT_RECEIVE_TIMEOUT); + .hasMillis(AbstractPollingMessageListenerContainer.DEFAULT_RECEIVE_TIMEOUT); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java index ce93c1ff62..f6f8d9351a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/JndiConnectionFactoryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class JndiConnectionFactoryAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JndiConnectionFactoryAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JndiConnectionFactoryAutoConfiguration.class)); private ClassLoader threadContextClassLoader; @@ -90,22 +90,23 @@ class JndiConnectionFactoryAutoConfigurationTests { void jndiNamePropertySet() { ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=java:comp/env/myCF") - .run(assertConnectionFactory(connectionFactory)); + .run(assertConnectionFactory(connectionFactory)); } @Test void jndiNamePropertySetWithResourceRef() { ConnectionFactory connectionFactory = configureConnectionFactory("java:comp/env/myCF"); this.contextRunner.withPropertyValues("spring.jms.jndi-name=myCF") - .run(assertConnectionFactory(connectionFactory)); + .run(assertConnectionFactory(connectionFactory)); } @Test void jndiNamePropertySetWithWrongValue() { this.contextRunner.withPropertyValues("spring.jms.jndi-name=doesNotExistCF").run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("doesNotExistCF"); + assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("doesNotExistCF"); }); } @@ -113,7 +114,7 @@ class JndiConnectionFactoryAutoConfigurationTests { return (context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class).hasBean("jmsConnectionFactory"); assertThat(context.getBean(ConnectionFactory.class)).isSameAs(connectionFactory) - .isSameAs(context.getBean("jmsConnectionFactory")); + .isSameAs(context.getBean("jmsConnectionFactory")); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index 41868b239f..2b362358b7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -65,13 +65,14 @@ import static org.assertj.core.api.Assertions.assertThat; class ArtemisAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ArtemisAutoConfiguration.class, JmsAutoConfiguration.class)); @Test void connectionFactoryIsCachedByDefault() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(CachingConnectionFactory.class) - .hasBean("jmsConnectionFactory"); + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(CachingConnectionFactory.class) + .hasBean("jmsConnectionFactory"); CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); assertThat(connectionFactory.getTargetConnectionFactory()).isInstanceOf(ActiveMQConnectionFactory.class); @@ -84,82 +85,84 @@ class ArtemisAutoConfigurationTests { @Test void connectionFactoryCachingCanBeCustomized() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", - "spring.jms.cache.session-cache-size=10") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(CachingConnectionFactory.class).hasBean("jmsConnectionFactory"); - CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); - assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); - assertThat(connectionFactory.isCacheConsumers()).isTrue(); - assertThat(connectionFactory.isCacheProducers()).isFalse(); - assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); - }); + .withPropertyValues("spring.jms.cache.consumers=true", "spring.jms.cache.producers=false", + "spring.jms.cache.session-cache-size=10") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(CachingConnectionFactory.class) + .hasBean("jmsConnectionFactory"); + CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); + assertThat(context.getBean("jmsConnectionFactory")).isSameAs(connectionFactory); + assertThat(connectionFactory.isCacheConsumers()).isTrue(); + assertThat(connectionFactory.isCacheProducers()).isFalse(); + assertThat(connectionFactory.getSessionCacheSize()).isEqualTo(10); + }); } @Test void connectionFactoryCachingCanBeDisabled() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.jms.cache.enabled=false").run((context) -> { - assertThat(context).doesNotHaveBean(CachingConnectionFactory.class); - ConnectionFactory connectionFactory = getConnectionFactory(context); - assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); - }); + .withPropertyValues("spring.jms.cache.enabled=false") + .run((context) -> { + assertThat(context).doesNotHaveBean(CachingConnectionFactory.class); + ConnectionFactory connectionFactory = getConnectionFactory(context); + assertThat(connectionFactory).isInstanceOf(ActiveMQConnectionFactory.class); + }); } @Test void nativeConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native").run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory connectionFactory = getConnectionFactory(context); - assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory( - connectionFactory); - assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); - assertThat(activeMQConnectionFactory.getUser()).isNull(); - assertThat(activeMQConnectionFactory.getPassword()).isNull(); - }); + .withPropertyValues("spring.artemis.mode:native") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory connectionFactory = getConnectionFactory(context); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); + ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory(connectionFactory); + assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); + assertThat(activeMQConnectionFactory.getUser()).isNull(); + assertThat(activeMQConnectionFactory.getPassword()).isNull(); + }); } @Test void nativeConnectionFactoryCustomBrokerUrl() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native", "spring.artemis.broker-url:tcp://192.168.1.144:9876") - .run((context) -> assertNettyConnectionFactory( - getActiveMQConnectionFactory(getConnectionFactory(context)), "192.168.1.144", 9876)); + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.broker-url:tcp://192.168.1.144:9876") + .run((context) -> assertNettyConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context)), + "192.168.1.144", 9876)); } @Test void nativeConnectionFactoryCredentials() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:native", "spring.artemis.user:user", - "spring.artemis.password:secret") - .run((context) -> { - JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); - ConnectionFactory connectionFactory = getConnectionFactory(context); - assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); - ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory( - connectionFactory); - assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); - assertThat(activeMQConnectionFactory.getUser()).isEqualTo("user"); - assertThat(activeMQConnectionFactory.getPassword()).isEqualTo("secret"); - }); + .withPropertyValues("spring.artemis.mode:native", "spring.artemis.user:user", + "spring.artemis.password:secret") + .run((context) -> { + JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); + ConnectionFactory connectionFactory = getConnectionFactory(context); + assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory()); + ActiveMQConnectionFactory activeMQConnectionFactory = getActiveMQConnectionFactory(connectionFactory); + assertNettyConnectionFactory(activeMQConnectionFactory, "localhost", 61616); + assertThat(activeMQConnectionFactory.getUser()).isEqualTo("user"); + assertThat(activeMQConnectionFactory.getPassword()).isEqualTo("secret"); + }); } @Test void embeddedConnectionFactory() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:embedded").run((context) -> { - ArtemisProperties properties = context.getBean(ArtemisProperties.class); - assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); - assertThat(context).hasSingleBean(EmbeddedActiveMQ.class); - org.apache.activemq.artemis.core.config.Configuration configuration = context - .getBean(org.apache.activemq.artemis.core.config.Configuration.class); - assertThat(configuration.isPersistenceEnabled()).isFalse(); - assertThat(configuration.isSecurityEnabled()).isFalse(); - assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); - }); + .withPropertyValues("spring.artemis.mode:embedded") + .run((context) -> { + ArtemisProperties properties = context.getBean(ArtemisProperties.class); + assertThat(properties.getMode()).isEqualTo(ArtemisMode.EMBEDDED); + assertThat(context).hasSingleBean(EmbeddedActiveMQ.class); + org.apache.activemq.artemis.core.config.Configuration configuration = context + .getBean(org.apache.activemq.artemis.core.config.Configuration.class); + assertThat(configuration.isPersistenceEnabled()).isFalse(); + assertThat(configuration.isSecurityEnabled()).isFalse(); + assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); + }); } @Test @@ -168,7 +171,7 @@ class ArtemisAutoConfigurationTests { this.contextRunner.withUserConfiguration(EmptyConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(EmbeddedActiveMQ.class); org.apache.activemq.artemis.core.config.Configuration configuration = context - .getBean(org.apache.activemq.artemis.core.config.Configuration.class); + .getBean(org.apache.activemq.artemis.core.config.Configuration.class); assertThat(configuration.isPersistenceEnabled()).isFalse(); assertThat(configuration.isSecurityEnabled()).isFalse(); assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); @@ -179,37 +182,37 @@ class ArtemisAutoConfigurationTests { void nativeConnectionFactoryIfEmbeddedServiceDisabledExplicitly() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.enabled:false").run((context) -> { - assertThat(context).doesNotHaveBean(ActiveMQServer.class); - assertNettyConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context)), - "localhost", 61616); - }); + .withPropertyValues("spring.artemis.embedded.enabled:false") + .run((context) -> { + assertThat(context).doesNotHaveBean(ActiveMQServer.class); + assertNettyConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context)), "localhost", + 61616); + }); } @Test void embeddedConnectionFactoryEvenIfEmbeddedServiceDisabled() { // No mode is specified this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false") - .run((context) -> { - assertThat(context.getBeansOfType(ActiveMQServer.class)).isEmpty(); - assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); - }); + .withPropertyValues("spring.artemis.mode:embedded", "spring.artemis.embedded.enabled:false") + .run((context) -> { + assertThat(context.getBeansOfType(ActiveMQServer.class)).isEmpty(); + assertInVmConnectionFactory(getActiveMQConnectionFactory(getConnectionFactory(context))); + }); } @Test void embeddedServerWithDestinations() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2", - "spring.artemis.embedded.topics=Topic1") - .run((context) -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("Queue1", true); - checker.checkQueue("Queue2", true); - checker.checkQueue("NonExistentQueue", false); - checker.checkTopic("Topic1", true); - checker.checkTopic("NonExistentTopic", false); - }); + .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2", "spring.artemis.embedded.topics=Topic1") + .run((context) -> { + DestinationChecker checker = new DestinationChecker(context); + checker.checkQueue("Queue1", true); + checker.checkQueue("Queue2", true); + checker.checkQueue("NonExistentQueue", false); + checker.checkTopic("Topic1", true); + checker.checkTopic("NonExistentTopic", false); + }); } @Test @@ -225,20 +228,21 @@ class ArtemisAutoConfigurationTests { void embeddedServiceWithCustomJmsConfiguration() { // Ignored with custom config this.contextRunner.withUserConfiguration(CustomJmsConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2").run((context) -> { - DestinationChecker checker = new DestinationChecker(context); - checker.checkQueue("custom", true); // See CustomJmsConfiguration - checker.checkQueue("Queue1", false); - checker.checkQueue("Queue2", false); - }); + .withPropertyValues("spring.artemis.embedded.queues=Queue1,Queue2") + .run((context) -> { + DestinationChecker checker = new DestinationChecker(context); + checker.checkQueue("custom", true); // See CustomJmsConfiguration + checker.checkQueue("Queue1", false); + checker.checkQueue("Queue2", false); + }); } @Test void embeddedServiceWithCustomArtemisConfiguration() { this.contextRunner.withUserConfiguration(CustomArtemisConfiguration.class) - .run((context) -> assertThat( - context.getBean(org.apache.activemq.artemis.core.config.Configuration.class).getName()) - .isEqualTo("customFooBar")); + .run((context) -> assertThat( + context.getBean(org.apache.activemq.artemis.core.config.Configuration.class).getName()) + .isEqualTo("customFooBar")); } @Test @@ -247,57 +251,57 @@ class ArtemisAutoConfigurationTests { final String messageId = UUID.randomUUID().toString(); // Start the server and post a message to some queue this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=TestQueue", - "spring.artemis.embedded.persistent:true", - "spring.artemis.embedded.dataDirectory:" + dataDirectory.getAbsolutePath()) - .run((context) -> context.getBean(JmsTemplate.class).send("TestQueue", - (session) -> session.createTextMessage(messageId))) - .run((context) -> { - // Start the server again and check if our message is still here - JmsTemplate jmsTemplate2 = context.getBean(JmsTemplate.class); - jmsTemplate2.setReceiveTimeout(1000L); - Message message = jmsTemplate2.receive("TestQueue"); - assertThat(message).isNotNull(); - assertThat(((TextMessage) message).getText()).isEqualTo(messageId); - }); + .withPropertyValues("spring.artemis.embedded.queues=TestQueue", "spring.artemis.embedded.persistent:true", + "spring.artemis.embedded.dataDirectory:" + dataDirectory.getAbsolutePath()) + .run((context) -> context.getBean(JmsTemplate.class) + .send("TestQueue", (session) -> session.createTextMessage(messageId))) + .run((context) -> { + // Start the server again and check if our message is still here + JmsTemplate jmsTemplate2 = context.getBean(JmsTemplate.class); + jmsTemplate2.setReceiveTimeout(1000L); + Message message = jmsTemplate2.receive("TestQueue"); + assertThat(message).isNotNull(); + assertThat(((TextMessage) message).getText()).isEqualTo(messageId); + }); } @Test void severalEmbeddedBrokers() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.queues=Queue1").run((first) -> { - this.contextRunner.withPropertyValues("spring.artemis.embedded.queues=Queue2").run((second) -> { - ArtemisProperties firstProperties = first.getBean(ArtemisProperties.class); - ArtemisProperties secondProperties = second.getBean(ArtemisProperties.class); - assertThat(firstProperties.getEmbedded().getServerId()) - .isLessThan(secondProperties.getEmbedded().getServerId()); - DestinationChecker firstChecker = new DestinationChecker(first); - firstChecker.checkQueue("Queue1", true); - firstChecker.checkQueue("Queue2", false); - DestinationChecker secondChecker = new DestinationChecker(second); - secondChecker.checkQueue("Queue1", false); - secondChecker.checkQueue("Queue2", true); - }); + .withPropertyValues("spring.artemis.embedded.queues=Queue1") + .run((first) -> { + this.contextRunner.withPropertyValues("spring.artemis.embedded.queues=Queue2").run((second) -> { + ArtemisProperties firstProperties = first.getBean(ArtemisProperties.class); + ArtemisProperties secondProperties = second.getBean(ArtemisProperties.class); + assertThat(firstProperties.getEmbedded().getServerId()) + .isLessThan(secondProperties.getEmbedded().getServerId()); + DestinationChecker firstChecker = new DestinationChecker(first); + firstChecker.checkQueue("Queue1", true); + firstChecker.checkQueue("Queue2", false); + DestinationChecker secondChecker = new DestinationChecker(second); + secondChecker.checkQueue("Queue1", false); + secondChecker.checkQueue("Queue2", true); }); + }); } @Test void connectToASpecificEmbeddedBroker() { this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") - .run((first) -> { - this.contextRunner.withUserConfiguration(EmptyConfiguration.class) - .withPropertyValues("spring.artemis.mode=embedded", - // Connect to the "main" broker - "spring.artemis.embedded.serverId=93", - // Do not start a specific one - "spring.artemis.embedded.enabled=false") - .run((secondContext) -> { - first.getBean(JmsTemplate.class).convertAndSend("Queue1", "test"); - assertThat(secondContext.getBean(JmsTemplate.class).receiveAndConvert("Queue1")) - .isEqualTo("test"); - }); - }); + .withPropertyValues("spring.artemis.embedded.serverId=93", "spring.artemis.embedded.queues=Queue1") + .run((first) -> { + this.contextRunner.withUserConfiguration(EmptyConfiguration.class) + .withPropertyValues("spring.artemis.mode=embedded", + // Connect to the "main" broker + "spring.artemis.embedded.serverId=93", + // Do not start a specific one + "spring.artemis.embedded.enabled=false") + .run((secondContext) -> { + first.getBean(JmsTemplate.class).convertAndSend("Queue1", "test"); + assertThat(secondContext.getBean(JmsTemplate.class).receiveAndConvert("Queue1")) + .isEqualTo("test"); + }); + }); } @Test @@ -307,16 +311,16 @@ class ArtemisAutoConfigurationTests { JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); JmsPoolConnectionFactory defaultFactory = new JmsPoolConnectionFactory(); assertThat(connectionFactory.isBlockIfSessionPoolIsFull()) - .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); + .isEqualTo(defaultFactory.isBlockIfSessionPoolIsFull()); assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()) - .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); + .isEqualTo(defaultFactory.getBlockIfSessionPoolIsFullTimeout()); assertThat(connectionFactory.getConnectionIdleTimeout()) - .isEqualTo(defaultFactory.getConnectionIdleTimeout()); + .isEqualTo(defaultFactory.getConnectionIdleTimeout()); assertThat(connectionFactory.getMaxConnections()).isEqualTo(defaultFactory.getMaxConnections()); assertThat(connectionFactory.getMaxSessionsPerConnection()) - .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); + .isEqualTo(defaultFactory.getMaxSessionsPerConnection()); assertThat(connectionFactory.getConnectionCheckInterval()) - .isEqualTo(defaultFactory.getConnectionCheckInterval()); + .isEqualTo(defaultFactory.getConnectionCheckInterval()); assertThat(connectionFactory.isUseAnonymousProducers()).isEqualTo(defaultFactory.isUseAnonymousProducers()); }); } @@ -324,22 +328,22 @@ class ArtemisAutoConfigurationTests { @Test void customPoolConnectionFactoryIsApplied() { this.contextRunner - .withPropertyValues("spring.artemis.pool.enabled=true", "spring.artemis.pool.blockIfFull=false", - "spring.artemis.pool.blockIfFullTimeout=64", "spring.artemis.pool.idleTimeout=512", - "spring.artemis.pool.maxConnections=256", "spring.artemis.pool.maxSessionsPerConnection=1024", - "spring.artemis.pool.timeBetweenExpirationCheck=2048", - "spring.artemis.pool.useAnonymousProducers=false") - .run((context) -> { - assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); - JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); - assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); - assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); - assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); - assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); - assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); - assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); - assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); - }); + .withPropertyValues("spring.artemis.pool.enabled=true", "spring.artemis.pool.blockIfFull=false", + "spring.artemis.pool.blockIfFullTimeout=64", "spring.artemis.pool.idleTimeout=512", + "spring.artemis.pool.maxConnections=256", "spring.artemis.pool.maxSessionsPerConnection=1024", + "spring.artemis.pool.timeBetweenExpirationCheck=2048", + "spring.artemis.pool.useAnonymousProducers=false") + .run((context) -> { + assertThat(context.getBeansOfType(JmsPoolConnectionFactory.class)).hasSize(1); + JmsPoolConnectionFactory connectionFactory = context.getBean(JmsPoolConnectionFactory.class); + assertThat(connectionFactory.isBlockIfSessionPoolIsFull()).isFalse(); + assertThat(connectionFactory.getBlockIfSessionPoolIsFullTimeout()).isEqualTo(64); + assertThat(connectionFactory.getConnectionIdleTimeout()).isEqualTo(512); + assertThat(connectionFactory.getMaxConnections()).isEqualTo(256); + assertThat(connectionFactory.getMaxSessionsPerConnection()).isEqualTo(1024); + assertThat(connectionFactory.getConnectionCheckInterval()).isEqualTo(2048); + assertThat(connectionFactory.isUseAnonymousProducers()).isFalse(); + }); } @Test @@ -385,7 +389,7 @@ class ArtemisAutoConfigurationTests { private TransportConfiguration getSingleTransportConfiguration(ActiveMQConnectionFactory connectionFactory) { TransportConfiguration[] transportConfigurations = connectionFactory.getServerLocator() - .getStaticTransportConfigurations(); + .getStaticTransportConfigurations(); assertThat(transportConfigurations).hasSize(1); return transportConfigurations[0]; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java index 716f410107..06e2d552c3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisEmbeddedConfigurationFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class ArtemisEmbeddedConfigurationFactoryTests { properties.getEmbedded().setPersistent(true); Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); assertThat(configuration.getJournalDirectory()).startsWith(System.getProperty("java.io.tmpdir")) - .endsWith("/journal"); + .endsWith("/journal"); } @Test @@ -76,9 +76,9 @@ class ArtemisEmbeddedConfigurationFactoryTests { Configuration configuration = new ArtemisEmbeddedConfigurationFactory(properties).createConfiguration(); Map addressSettings = configuration.getAddressSettings(); assertThat((Object) addressSettings.get("#").getDeadLetterAddress()) - .isEqualTo(SimpleString.toSimpleString("DLQ")); + .isEqualTo(SimpleString.toSimpleString("DLQ")); assertThat((Object) addressSettings.get("#").getExpiryAddress()) - .isEqualTo(SimpleString.toSimpleString("ExpiryQueue")); + .isEqualTo(SimpleString.toSimpleString("ExpiryQueue")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java index ce11238e44..2e14f48018 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JmxAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class)); @Test void testDefaultMBeanExport() { @@ -80,16 +80,18 @@ class JmxAutoConfigurationTests { @Test void testDefaultDomainConfiguredOnMBeanExport() { - this.contextRunner.withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default-domain=my-test-domain", - "spring.jmx.unique-names=true").run((context) -> { - assertThat(context).hasSingleBean(MBeanExporter.class); - MBeanExporter exporter = context.getBean(MBeanExporter.class); - assertThat(exporter).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); - MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(exporter, - "namingStrategy"); - assertThat(naming).hasFieldOrPropertyWithValue("defaultDomain", "my-test-domain"); - assertThat(naming).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); - }); + this.contextRunner + .withPropertyValues("spring.jmx.enabled=true", "spring.jmx.default-domain=my-test-domain", + "spring.jmx.unique-names=true") + .run((context) -> { + assertThat(context).hasSingleBean(MBeanExporter.class); + MBeanExporter exporter = context.getBean(MBeanExporter.class); + assertThat(exporter).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); + MetadataNamingStrategy naming = (MetadataNamingStrategy) ReflectionTestUtils.getField(exporter, + "namingStrategy"); + assertThat(naming).hasFieldOrPropertyWithValue("defaultDomain", "my-test-domain"); + assertThat(naming).hasFieldOrPropertyWithValue("ensureUniqueRuntimeObjectNames", true); + }); } @Test @@ -106,21 +108,21 @@ class JmxAutoConfigurationTests { try (AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext()) { parent.register(JmxAutoConfiguration.class, TestConfiguration.class); parent.refresh(); - this.contextRunner.withParent(parent).withConfiguration(UserConfigurations.of(TestConfiguration.class)) - .run((context) -> assertThat(context.isRunning())); + this.contextRunner.withParent(parent) + .withConfiguration(UserConfigurations.of(TestConfiguration.class)) + .run((context) -> assertThat(context.isRunning())); } } @Test void customJmxDomain() { this.contextRunner.withConfiguration(UserConfigurations.of(CustomJmxDomainConfiguration.class)) - .withConfiguration( - AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(IntegrationMBeanExporter.class); - IntegrationMBeanExporter exporter = context.getBean(IntegrationMBeanExporter.class); - assertThat(exporter).hasFieldOrPropertyWithValue("domain", "foo.my"); - }); + .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(IntegrationMBeanExporter.class); + IntegrationMBeanExporter exporter = context.getBean(IntegrationMBeanExporter.class); + assertThat(exporter).hasFieldOrPropertyWithValue("domain", "foo.my"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java index 41ccb73bcb..dc4f3cd505 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/ParentAwareNamingStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class ParentAwareNamingStrategyTests { ParentAwareNamingStrategy strategy = new ParentAwareNamingStrategy(new AnnotationJmxAttributeSource()); strategy.setApplicationContext(context); assertThat(strategy.getObjectName(context.getBean("testManagedResource"), "testManagedResource") - .getKeyPropertyListString()).isEqualTo("type=something,name1=def,name2=ghi"); + .getKeyPropertyListString()).isEqualTo("type=something,name1=def,name2=ghi"); }); } @@ -62,8 +62,10 @@ class ParentAwareNamingStrategyTests { @Test void sameBeanInParentContextAddsContextProperty() { - this.contextRunner.withBean("testManagedResource", TestManagedResource.class).run((parent) -> this.contextRunner - .withBean("testManagedResource", TestManagedResource.class).withParent(parent).run((context) -> { + this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .run((parent) -> this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .withParent(parent) + .run((context) -> { ParentAwareNamingStrategy strategy = new ParentAwareNamingStrategy( new AnnotationJmxAttributeSource()); strategy.setApplicationContext(context); @@ -77,8 +79,10 @@ class ParentAwareNamingStrategyTests { @Test void uniqueObjectNameAndSameBeanInParentContextOnlyAddsIdentityProperty() { - this.contextRunner.withBean("testManagedResource", TestManagedResource.class).run((parent) -> this.contextRunner - .withBean("testManagedResource", TestManagedResource.class).withParent(parent).run((context) -> { + this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .run((parent) -> this.contextRunner.withBean("testManagedResource", TestManagedResource.class) + .withParent(parent) + .run((context) -> { ParentAwareNamingStrategy strategy = new ParentAwareNamingStrategy( new AnnotationJmxAttributeSource()); strategy.setApplicationContext(context); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index 6d608d69af..1e78fee1d9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -59,8 +59,8 @@ import static org.mockito.Mockito.mock; class JooqAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) - .withPropertyValues("spring.datasource.name:jooqtest"); + .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) + .withPropertyValues("spring.datasource.name:jooqtest"); @Test void noDataSource() { @@ -78,8 +78,8 @@ class JooqAutoConfigurationTests { dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('foo');")); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); assertThatExceptionOfType(DataIntegrityViolationException.class) - .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');"))); + .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');"))); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); }); } @@ -87,19 +87,19 @@ class JooqAutoConfigurationTests { @Test void jooqWithTx() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(PlatformTransactionManager.class); - DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); - dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); - dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); - assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy( - () -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');"))); - dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); - }); + .run((context) -> { + assertThat(context).hasSingleBean(PlatformTransactionManager.class); + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().dialect()).isEqualTo(SQLDialect.HSQLDB); + dsl.execute("create table jooqtest_tx (name varchar(255) primary key);"); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "0")); + dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest_tx (name) values ('foo');")); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + assertThatExceptionOfType(DataIntegrityViolationException.class) + .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');"))); + dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); + }); } @Test @@ -116,12 +116,12 @@ class JooqAutoConfigurationTests { @Test void jooqWithDefaultTransactionProvider() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class) - .run((context) -> { - DSLContext dsl = context.getBean(DSLContext.class); - TransactionProvider expectedTransactionProvider = context.getBean(TransactionProvider.class); - TransactionProvider transactionProvider = dsl.configuration().transactionProvider(); - assertThat(transactionProvider).isSameAs(expectedTransactionProvider); - }); + .run((context) -> { + DSLContext dsl = context.getBean(DSLContext.class); + TransactionProvider expectedTransactionProvider = context.getBean(TransactionProvider.class); + TransactionProvider transactionProvider = dsl.configuration().transactionProvider(); + assertThat(transactionProvider).isSameAs(expectedTransactionProvider); + }); } @Test @@ -135,13 +135,13 @@ class JooqAutoConfigurationTests { @Test void jooqWithSeveralExecuteListenerProviders() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TestExecuteListenerProvider.class) - .run((context) -> { - DSLContext dsl = context.getBean(DSLContext.class); - ExecuteListenerProvider[] executeListenerProviders = dsl.configuration().executeListenerProviders(); - assertThat(executeListenerProviders).hasSize(2); - assertThat(executeListenerProviders[0]).isInstanceOf(DefaultExecuteListenerProvider.class); - assertThat(executeListenerProviders[1]).isInstanceOf(TestExecuteListenerProvider.class); - }); + .run((context) -> { + DSLContext dsl = context.getBean(DSLContext.class); + ExecuteListenerProvider[] executeListenerProviders = dsl.configuration().executeListenerProviders(); + assertThat(executeListenerProviders).hasSize(2); + assertThat(executeListenerProviders[0]).isInstanceOf(DefaultExecuteListenerProvider.class); + assertThat(executeListenerProviders[1]).isInstanceOf(TestExecuteListenerProvider.class); + }); } @Test @@ -149,46 +149,48 @@ class JooqAutoConfigurationTests { ConverterProvider converterProvider = mock(ConverterProvider.class); CharsetProvider charsetProvider = mock(CharsetProvider.class); this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class) - .withBean("configurationCustomizer1", DefaultConfigurationCustomizer.class, - () -> (configuration) -> configuration.set(converterProvider)) - .withBean("configurationCustomizer2", DefaultConfigurationCustomizer.class, - () -> (configuration) -> configuration.set(charsetProvider)) - .run((context) -> { - DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().converterProvider()).isSameAs(converterProvider); - assertThat(dsl.configuration().charsetProvider()).isSameAs(charsetProvider); - }); + .withBean("configurationCustomizer1", DefaultConfigurationCustomizer.class, + () -> (configuration) -> configuration.set(converterProvider)) + .withBean("configurationCustomizer2", DefaultConfigurationCustomizer.class, + () -> (configuration) -> configuration.set(charsetProvider)) + .run((context) -> { + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().converterProvider()).isSameAs(converterProvider); + assertThat(dsl.configuration().charsetProvider()).isSameAs(charsetProvider); + }); } @Test void relaxedBindingOfSqlDialect() { this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class) - .withPropertyValues("spring.jooq.sql-dialect:PoSTGrES") - .run((context) -> assertThat(context.getBean(org.jooq.Configuration.class).dialect()) - .isEqualTo(SQLDialect.POSTGRES)); + .withPropertyValues("spring.jooq.sql-dialect:PoSTGrES") + .run((context) -> assertThat(context.getBean(org.jooq.Configuration.class).dialect()) + .isEqualTo(SQLDialect.POSTGRES)); } @Test void transactionProviderBacksOffOnExistingTransactionProvider() { this.contextRunner - .withUserConfiguration(JooqDataSourceConfiguration.class, CustomTransactionProviderConfiguration.class) - .run((context) -> { - TransactionProvider transactionProvider = context.getBean(TransactionProvider.class); - assertThat(transactionProvider).isInstanceOf(CustomTransactionProvider.class); - DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().transactionProvider()).isSameAs(transactionProvider); - }); + .withUserConfiguration(JooqDataSourceConfiguration.class, CustomTransactionProviderConfiguration.class) + .run((context) -> { + TransactionProvider transactionProvider = context.getBean(TransactionProvider.class); + assertThat(transactionProvider).isInstanceOf(CustomTransactionProvider.class); + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().transactionProvider()).isSameAs(transactionProvider); + }); } @Test void transactionProviderFromConfigurationCustomizerOverridesTransactionProviderBean() { - this.contextRunner.withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class, - CustomTransactionProviderFromCustomizerConfiguration.class).run((context) -> { - TransactionProvider transactionProvider = context.getBean(TransactionProvider.class); - assertThat(transactionProvider).isInstanceOf(SpringTransactionProvider.class); - DSLContext dsl = context.getBean(DSLContext.class); - assertThat(dsl.configuration().transactionProvider()).isInstanceOf(CustomTransactionProvider.class); - }); + this.contextRunner + .withUserConfiguration(JooqDataSourceConfiguration.class, TxManagerConfiguration.class, + CustomTransactionProviderFromCustomizerConfiguration.class) + .run((context) -> { + TransactionProvider transactionProvider = context.getBean(TransactionProvider.class); + assertThat(transactionProvider).isInstanceOf(SpringTransactionProvider.class); + DSLContext dsl = context.getBean(DSLContext.class); + assertThat(dsl.configuration().transactionProvider()).isInstanceOf(CustomTransactionProvider.class); + }); } static class AssertFetch implements TransactionalRunnable { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java index a546717b1d..8f0f034d31 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,12 +45,11 @@ class NoDslContextBeanFailureAnalyzerTests { @Test void analysisWithR2dbcAutoConfiguration() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .run((context) -> { - NoDslContextBeanFailureAnalyzer failureAnalyzer = new NoDslContextBeanFailureAnalyzer( - context.getBeanFactory()); - assertThat(failureAnalyzer.analyze(new NoSuchBeanDefinitionException(DSLContext.class))) - .isNotNull(); - }); + .run((context) -> { + NoDslContextBeanFailureAnalyzer failureAnalyzer = new NoDslContextBeanFailureAnalyzer( + context.getBeanFactory()); + assertThat(failureAnalyzer.analyze(new NoSuchBeanDefinitionException(DSLContext.class))).isNotNull(); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java index 19df6198e1..838526a6f2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JsonbAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); @Test void jsonbRegistration() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java index b5c9936d17..6df28de9e1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jsonb/JsonbAutoConfigurationWithNoProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class JsonbAutoConfigurationWithNoProviderTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(JsonbAutoConfiguration.class)); @Test void jsonbBacksOffWhenThereIsNoProvider() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java index 26a0c6eec9..1be7c87581 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationIntegrationTests.java @@ -105,15 +105,18 @@ class KafkaAutoConfigurationIntegrationTests { "spring.kafka.consumer.auto-offset-reset=earliest"); RetryTopicConfiguration configuration = this.context.getBean(RetryTopicConfiguration.class); assertThat(configuration.getDestinationTopicProperties()).extracting(DestinationTopic.Properties::delay) - .containsExactly(0L, 100L, 200L, 300L, 300L, 0L); + .containsExactly(0L, 100L, 200L, 300L, 300L, 0L); KafkaTemplate template = this.context.getBean(KafkaTemplate.class); template.send(TEST_RETRY_TOPIC, "foo", "bar"); RetryListener listener = this.context.getBean(RetryListener.class); assertThat(listener.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(listener).extracting(RetryListener::getKey, RetryListener::getReceived).containsExactly("foo", - "bar"); - assertThat(listener).extracting(RetryListener::getTopics).asList().hasSize(5).containsSequence("testRetryTopic", - "testRetryTopic-retry-0", "testRetryTopic-retry-1", "testRetryTopic-retry-2", "testRetryTopic-retry-3"); + assertThat(listener).extracting(RetryListener::getKey, RetryListener::getReceived) + .containsExactly("foo", "bar"); + assertThat(listener).extracting(RetryListener::getTopics) + .asList() + .hasSize(5) + .containsSequence("testRetryTopic", "testRetryTopic-retry-0", "testRetryTopic-retry-1", + "testRetryTopic-retry-2", "testRetryTopic-retry-3"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java index 158bbbdf3c..6a947895dd 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaAutoConfigurationTests.java @@ -96,7 +96,7 @@ import static org.mockito.Mockito.never; class KafkaAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(KafkaAutoConfiguration.class)); @Test void consumerProperties() { @@ -116,44 +116,42 @@ class KafkaAutoConfigurationTests { "spring.kafka.consumer.security.protocol = SSL", "spring.kafka.consumer.key-deserializer = org.apache.kafka.common.serialization.LongDeserializer", "spring.kafka.consumer.value-deserializer = org.apache.kafka.common.serialization.IntegerDeserializer") - .run((context) -> { - DefaultKafkaConsumerFactory consumerFactory = context - .getBean(DefaultKafkaConsumerFactory.class); - Map configs = consumerFactory.getConfigurationProperties(); - // common - assertThat(configs).containsEntry(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, - Collections.singletonList("foo:1234")); - assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p1"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLoc"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p2"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLoc"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p3"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); - assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); - // consumer - assertThat(configs).containsEntry(ConsumerConfig.CLIENT_ID_CONFIG, "ccid"); // override - assertThat(configs).containsEntry(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Boolean.FALSE); - assertThat(configs).containsEntry(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 123); - assertThat(configs).containsEntry(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - assertThat(configs).containsEntry(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, 456); - assertThat(configs).containsEntry(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1024); - assertThat(configs).containsEntry(ConsumerConfig.GROUP_ID_CONFIG, "bar"); - assertThat(configs).containsEntry(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 234); - assertThat(configs).containsEntry(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed"); - assertThat(configs).containsEntry(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, - LongDeserializer.class); - assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); - assertThat(configs).containsEntry(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, - IntegerDeserializer.class); - assertThat(configs).containsEntry(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 42); - assertThat(configs).containsEntry("foo", "bar"); - assertThat(configs).containsEntry("baz", "qux"); - assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); - assertThat(configs).containsEntry("fiz.buz", "fix.fox"); - }); + .run((context) -> { + DefaultKafkaConsumerFactory consumerFactory = context.getBean(DefaultKafkaConsumerFactory.class); + Map configs = consumerFactory.getConfigurationProperties(); + // common + assertThat(configs).containsEntry(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, + Collections.singletonList("foo:1234")); + assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p1"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLoc"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p2"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLoc"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p3"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); + assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); + // consumer + assertThat(configs).containsEntry(ConsumerConfig.CLIENT_ID_CONFIG, "ccid"); // override + assertThat(configs).containsEntry(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Boolean.FALSE); + assertThat(configs).containsEntry(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 123); + assertThat(configs).containsEntry(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + assertThat(configs).containsEntry(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, 456); + assertThat(configs).containsEntry(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1024); + assertThat(configs).containsEntry(ConsumerConfig.GROUP_ID_CONFIG, "bar"); + assertThat(configs).containsEntry(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 234); + assertThat(configs).containsEntry(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed"); + assertThat(configs).containsEntry(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class); + assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); + assertThat(configs).containsEntry(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, + IntegerDeserializer.class); + assertThat(configs).containsEntry(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 42); + assertThat(configs).containsEntry("foo", "bar"); + assertThat(configs).containsEntry("baz", "qux"); + assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); + assertThat(configs).containsEntry("fiz.buz", "fix.fox"); + }); } @Test @@ -172,162 +170,164 @@ class KafkaAutoConfigurationTests { "spring.kafka.producer.ssl.trust-store-password=p6", "spring.kafka.producer.ssl.trust-store-type=PKCS12", "spring.kafka.producer.ssl.protocol=TLSv1.2", "spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.IntegerSerializer") - .run((context) -> { - DefaultKafkaProducerFactory producerFactory = context - .getBean(DefaultKafkaProducerFactory.class); - Map configs = producerFactory.getConfigurationProperties(); - // common - assertThat(configs).containsEntry(ProducerConfig.CLIENT_ID_CONFIG, "cid"); - // producer - assertThat(configs).containsEntry(ProducerConfig.ACKS_CONFIG, "all"); - assertThat(configs).containsEntry(ProducerConfig.BATCH_SIZE_CONFIG, 2048); - assertThat(configs).containsEntry(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, - Collections.singletonList("bar:1234")); // override - assertThat(configs).containsEntry(ProducerConfig.BUFFER_MEMORY_CONFIG, 4096L); - assertThat(configs).containsEntry(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip"); - assertThat(configs).containsEntry(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class); - assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p4"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p5"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p6"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); - assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); - assertThat(configs).containsEntry(ProducerConfig.RETRIES_CONFIG, 2); - assertThat(configs).containsEntry(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, - IntegerSerializer.class); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); - assertThat(context.getBeansOfType(KafkaTransactionManager.class)).isEmpty(); - assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); - assertThat(configs).containsEntry("fiz.buz", "fix.fox"); - }); + .run((context) -> { + DefaultKafkaProducerFactory producerFactory = context.getBean(DefaultKafkaProducerFactory.class); + Map configs = producerFactory.getConfigurationProperties(); + // common + assertThat(configs).containsEntry(ProducerConfig.CLIENT_ID_CONFIG, "cid"); + // producer + assertThat(configs).containsEntry(ProducerConfig.ACKS_CONFIG, "all"); + assertThat(configs).containsEntry(ProducerConfig.BATCH_SIZE_CONFIG, 2048); + assertThat(configs).containsEntry(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, + Collections.singletonList("bar:1234")); // override + assertThat(configs).containsEntry(ProducerConfig.BUFFER_MEMORY_CONFIG, 4096L); + assertThat(configs).containsEntry(ProducerConfig.COMPRESSION_TYPE_CONFIG, "gzip"); + assertThat(configs).containsEntry(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class); + assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p4"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p5"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p6"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); + assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); + assertThat(configs).containsEntry(ProducerConfig.RETRIES_CONFIG, 2); + assertThat(configs).containsEntry(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, + IntegerSerializer.class); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); + assertThat(context.getBeansOfType(KafkaTransactionManager.class)).isEmpty(); + assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); + assertThat(configs).containsEntry("fiz.buz", "fix.fox"); + }); } @Test void adminProperties() { - this.contextRunner.withPropertyValues("spring.kafka.clientId=cid", - "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.admin.fail-fast=true", - "spring.kafka.admin.properties.fiz.buz=fix.fox", "spring.kafka.admin.security.protocol=SSL", - "spring.kafka.admin.ssl.key-password=p4", "spring.kafka.admin.ssl.key-store-location=classpath:ksLocP", - "spring.kafka.admin.ssl.key-store-password=p5", "spring.kafka.admin.ssl.key-store-type=PKCS12", - "spring.kafka.admin.ssl.trust-store-location=classpath:tsLocP", - "spring.kafka.admin.ssl.trust-store-password=p6", "spring.kafka.admin.ssl.trust-store-type=PKCS12", - "spring.kafka.admin.ssl.protocol=TLSv1.2", "spring.kafka.admin.modify-topic-configs=true") - .run((context) -> { - KafkaAdmin admin = context.getBean(KafkaAdmin.class); - Map configs = admin.getConfigurationProperties(); - // common - assertThat(configs).containsEntry(AdminClientConfig.CLIENT_ID_CONFIG, "cid"); - // admin - assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p4"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p5"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p6"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); - assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); - assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); - assertThat(configs).containsEntry("fiz.buz", "fix.fox"); - assertThat(admin).hasFieldOrPropertyWithValue("fatalIfBrokerNotAvailable", true); - assertThat(admin).hasFieldOrPropertyWithValue("modifyTopicConfigs", true); - }); + this.contextRunner + .withPropertyValues("spring.kafka.clientId=cid", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", + "spring.kafka.admin.fail-fast=true", "spring.kafka.admin.properties.fiz.buz=fix.fox", + "spring.kafka.admin.security.protocol=SSL", "spring.kafka.admin.ssl.key-password=p4", + "spring.kafka.admin.ssl.key-store-location=classpath:ksLocP", + "spring.kafka.admin.ssl.key-store-password=p5", "spring.kafka.admin.ssl.key-store-type=PKCS12", + "spring.kafka.admin.ssl.trust-store-location=classpath:tsLocP", + "spring.kafka.admin.ssl.trust-store-password=p6", "spring.kafka.admin.ssl.trust-store-type=PKCS12", + "spring.kafka.admin.ssl.protocol=TLSv1.2", "spring.kafka.admin.modify-topic-configs=true") + .run((context) -> { + KafkaAdmin admin = context.getBean(KafkaAdmin.class); + Map configs = admin.getConfigurationProperties(); + // common + assertThat(configs).containsEntry(AdminClientConfig.CLIENT_ID_CONFIG, "cid"); + // admin + assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p4"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p5"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p6"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); + assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); + assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); + assertThat(configs).containsEntry("fiz.buz", "fix.fox"); + assertThat(admin).hasFieldOrPropertyWithValue("fatalIfBrokerNotAvailable", true); + assertThat(admin).hasFieldOrPropertyWithValue("modifyTopicConfigs", true); + }); } @SuppressWarnings("unchecked") @Test void streamsProperties() { - this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).withPropertyValues( - "spring.kafka.client-id=cid", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.application.name=appName", "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", - "spring.kafka.streams.auto-startup=false", "spring.kafka.streams.cache-max-size-buffering=1KB", - "spring.kafka.streams.client-id=override", "spring.kafka.streams.properties.fiz.buz=fix.fox", - "spring.kafka.streams.replication-factor=2", "spring.kafka.streams.state-dir=/tmp/state", - "spring.kafka.streams.security.protocol=SSL", "spring.kafka.streams.ssl.key-password=p7", - "spring.kafka.streams.ssl.key-store-location=classpath:ksLocP", - "spring.kafka.streams.ssl.key-store-password=p8", "spring.kafka.streams.ssl.key-store-type=PKCS12", - "spring.kafka.streams.ssl.trust-store-location=classpath:tsLocP", - "spring.kafka.streams.ssl.trust-store-password=p9", "spring.kafka.streams.ssl.trust-store-type=PKCS12", - "spring.kafka.streams.ssl.protocol=TLSv1.2").run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - assertThat(configs).containsEntry(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 1024); - assertThat(configs).containsEntry(StreamsConfig.CLIENT_ID_CONFIG, "override"); - assertThat(configs).containsEntry(StreamsConfig.REPLICATION_FACTOR_CONFIG, 2); - assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); - assertThat(configs).containsEntry(StreamsConfig.STATE_DIR_CONFIG, "/tmp/state"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p7"); - assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "ksLocP"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p8"); - assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); - assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) - .endsWith(File.separator + "tsLocP"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p9"); - assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); - assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); - assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); - assertThat(configs).containsEntry("fiz.buz", "fix.fox"); - assertThat(context.getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME)) - .isNotNull(); - }); + this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class) + .withPropertyValues("spring.kafka.client-id=cid", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.application.name=appName", + "spring.kafka.properties.foo.bar.baz=qux.fiz.buz", "spring.kafka.streams.auto-startup=false", + "spring.kafka.streams.cache-max-size-buffering=1KB", "spring.kafka.streams.client-id=override", + "spring.kafka.streams.properties.fiz.buz=fix.fox", "spring.kafka.streams.replication-factor=2", + "spring.kafka.streams.state-dir=/tmp/state", "spring.kafka.streams.security.protocol=SSL", + "spring.kafka.streams.ssl.key-password=p7", + "spring.kafka.streams.ssl.key-store-location=classpath:ksLocP", + "spring.kafka.streams.ssl.key-store-password=p8", "spring.kafka.streams.ssl.key-store-type=PKCS12", + "spring.kafka.streams.ssl.trust-store-location=classpath:tsLocP", + "spring.kafka.streams.ssl.trust-store-password=p9", + "spring.kafka.streams.ssl.trust-store-type=PKCS12", "spring.kafka.streams.ssl.protocol=TLSv1.2") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + assertThat(configs).containsEntry(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 1024); + assertThat(configs).containsEntry(StreamsConfig.CLIENT_ID_CONFIG, "override"); + assertThat(configs).containsEntry(StreamsConfig.REPLICATION_FACTOR_CONFIG, 2); + assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); + assertThat(configs).containsEntry(StreamsConfig.STATE_DIR_CONFIG, "/tmp/state"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEY_PASSWORD_CONFIG, "p7"); + assertThat((String) configs.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "ksLocP"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "p8"); + assertThat(configs).containsEntry(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); + assertThat((String) configs.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG)) + .endsWith(File.separator + "tsLocP"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, "p9"); + assertThat(configs).containsEntry(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, "PKCS12"); + assertThat(configs).containsEntry(SslConfigs.SSL_PROTOCOL_CONFIG, "TLSv1.2"); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).isEmpty(); + assertThat(configs).containsEntry("foo.bar.baz", "qux.fiz.buz"); + assertThat(configs).containsEntry("fiz.buz", "fix.fox"); + assertThat(context.getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_BUILDER_BEAN_NAME)) + .isNotNull(); + }); } @SuppressWarnings("unchecked") @Test void streamsApplicationIdUsesMainApplicationNameByDefault() { this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false") - .run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - assertThat(configs).containsEntry(StreamsConfig.APPLICATION_ID_CONFIG, "my-test-app"); - }); + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + assertThat(configs).containsEntry(StreamsConfig.APPLICATION_ID_CONFIG, "my-test-app"); + }); } @Test void streamsWithCustomKafkaConfiguration() { this.contextRunner - .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false") - .run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat(configs).containsEntry(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, - "localhost:9094, localhost:9095"); - assertThat(configs).containsEntry(StreamsConfig.APPLICATION_ID_CONFIG, "test-id"); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat(configs).containsEntry(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, + "localhost:9094, localhost:9095"); + assertThat(configs).containsEntry(StreamsConfig.APPLICATION_ID_CONFIG, "test-id"); + }); } @Test void retryTopicConfigurationIsNotEnabledByDefault() { this.contextRunner - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093") - .run((context) -> assertThat(context).doesNotHaveBean(RetryTopicConfiguration.class)); + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093") + .run((context) -> assertThat(context).doesNotHaveBean(RetryTopicConfiguration.class)); } @Test @@ -335,26 +335,28 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", "spring.kafka.retry.topic.attempts=5", "spring.kafka.retry.topic.delay=100ms", - "spring.kafka.retry.topic.multiplier=2", "spring.kafka.retry.topic.max-delay=300ms").run((context) -> { - RetryTopicConfiguration configuration = context.getBean(RetryTopicConfiguration.class); - assertThat(configuration.getDestinationTopicProperties()).hasSize(6) - .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) - .containsExactly(tuple(0L, ""), tuple(100L, "-retry-0"), tuple(200L, "-retry-1"), - tuple(300L, "-retry-2"), tuple(300L, "-retry-3"), tuple(0L, "-dlt")); - }); + "spring.kafka.retry.topic.multiplier=2", "spring.kafka.retry.topic.max-delay=300ms") + .run((context) -> { + RetryTopicConfiguration configuration = context.getBean(RetryTopicConfiguration.class); + assertThat(configuration.getDestinationTopicProperties()).hasSize(6) + .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) + .containsExactly(tuple(0L, ""), tuple(100L, "-retry-0"), tuple(200L, "-retry-1"), + tuple(300L, "-retry-2"), tuple(300L, "-retry-3"), tuple(0L, "-dlt")); + }); } @Test void retryTopicConfigurationWithDefaultProperties() { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true") - .run(assertRetryTopicConfiguration((configuration) -> { - assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) - .containsExactly(tuple(0L, ""), tuple(1000L, "-retry"), tuple(0L, "-dlt")); - assertThat(configuration.forKafkaTopicAutoCreation()).extracting("shouldCreateTopics") - .asInstanceOf(InstanceOfAssertFactories.BOOLEAN).isFalse(); - })); + .run(assertRetryTopicConfiguration((configuration) -> { + assertThat(configuration.getDestinationTopicProperties()).hasSize(3) + .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) + .containsExactly(tuple(0L, ""), tuple(1000L, "-retry"), tuple(0L, "-dlt")); + assertThat(configuration.forKafkaTopicAutoCreation()).extracting("shouldCreateTopics") + .asInstanceOf(InstanceOfAssertFactories.BOOLEAN) + .isFalse(); + })); } @Test @@ -362,9 +364,10 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", "spring.kafka.retry.topic.attempts=4", "spring.kafka.retry.topic.delay=2s") - .run(assertRetryTopicConfiguration( - (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay).containsExactly(0L, 2000L, 0L))); + .run(assertRetryTopicConfiguration( + (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) + .extracting(DestinationTopic.Properties::delay) + .containsExactly(0L, 2000L, 0L))); } @Test @@ -372,9 +375,10 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", "spring.kafka.retry.topic.attempts=4", "spring.kafka.retry.topic.delay=0") - .run(assertRetryTopicConfiguration( - (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay).containsExactly(0L, 0L, 0L))); + .run(assertRetryTopicConfiguration( + (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) + .extracting(DestinationTopic.Properties::delay) + .containsExactly(0L, 0L, 0L))); } private ContextConsumer assertRetryTopicConfiguration( @@ -389,52 +393,54 @@ class KafkaAutoConfigurationTests { @Test void streamsWithSeveralStreamsBuilderFactoryBeans() { this.contextRunner - .withUserConfiguration(EnableKafkaStreamsConfiguration.class, - TestStreamsBuilderFactoryBeanConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false") - .run((context) -> { - Properties configs = context - .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, - KafkaStreamsConfiguration.class) - .asProperties(); - assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) - .containsExactly("localhost:9092", "localhost:9093"); - then(context.getBean("&firstStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) - .should(never()).setAutoStartup(false); - then(context.getBean("&secondStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) - .should(never()).setAutoStartup(false); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class, + TestStreamsBuilderFactoryBeanConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false") + .run((context) -> { + Properties configs = context + .getBean(KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME, + KafkaStreamsConfiguration.class) + .asProperties(); + assertThat((List) configs.get(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) + .containsExactly("localhost:9092", "localhost:9093"); + then(context.getBean("&firstStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) + .should(never()) + .setAutoStartup(false); + then(context.getBean("&secondStreamsBuilderFactoryBean", StreamsBuilderFactoryBean.class)) + .should(never()) + .setAutoStartup(false); + }); } @Test void streamsWithCleanupConfig() { this.contextRunner - .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) - .withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", - "spring.kafka.streams.auto-startup=false", "spring.kafka.streams.cleanup.on-startup=true", - "spring.kafka.streams.cleanup.on-shutdown=false") - .run((context) -> { - StreamsBuilderFactoryBean streamsBuilderFactoryBean = context - .getBean(StreamsBuilderFactoryBean.class); - assertThat(streamsBuilderFactoryBean) - .extracting("cleanupConfig", InstanceOfAssertFactories.type(CleanupConfig.class)) - .satisfies((cleanupConfig) -> { - assertThat(cleanupConfig.cleanupOnStart()).isTrue(); - assertThat(cleanupConfig.cleanupOnStop()).isFalse(); - }); - }); + .withUserConfiguration(EnableKafkaStreamsConfiguration.class, TestKafkaStreamsConfiguration.class) + .withPropertyValues("spring.application.name=my-test-app", + "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", + "spring.kafka.streams.auto-startup=false", "spring.kafka.streams.cleanup.on-startup=true", + "spring.kafka.streams.cleanup.on-shutdown=false") + .run((context) -> { + StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean(StreamsBuilderFactoryBean.class); + assertThat(streamsBuilderFactoryBean) + .extracting("cleanupConfig", InstanceOfAssertFactories.type(CleanupConfig.class)) + .satisfies((cleanupConfig) -> { + assertThat(cleanupConfig.cleanupOnStart()).isTrue(); + assertThat(cleanupConfig.cleanupOnStop()).isFalse(); + }); + }); } @Test void streamsApplicationIdIsMandatory() { this.contextRunner.withUserConfiguration(EnableKafkaStreamsConfiguration.class).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().hasMessageContaining("spring.kafka.streams.application-id") - .hasMessageContaining( - "This property is mandatory and fallback 'spring.application.name' is not set either."); + assertThat(context).getFailure() + .hasMessageContaining("spring.kafka.streams.application-id") + .hasMessageContaining( + "This property is mandatory and fallback 'spring.application.name' is not set either."); }); } @@ -451,74 +457,73 @@ class KafkaAutoConfigurationTests { @Test void listenerProperties() { this.contextRunner - .withPropertyValues("spring.kafka.template.default-topic=testTopic", - "spring.kafka.template.transaction-id-prefix=txOverride", - "spring.kafka.listener.ack-mode=MANUAL", "spring.kafka.listener.client-id=client", - "spring.kafka.listener.ack-count=123", "spring.kafka.listener.ack-time=456", - "spring.kafka.listener.concurrency=3", "spring.kafka.listener.poll-timeout=2000", - "spring.kafka.listener.no-poll-threshold=2.5", "spring.kafka.listener.type=batch", - "spring.kafka.listener.idle-between-polls=1s", "spring.kafka.listener.idle-event-interval=1s", - "spring.kafka.listener.idle-partition-event-interval=1s", - "spring.kafka.listener.monitor-interval=45", "spring.kafka.listener.log-container-config=true", - "spring.kafka.listener.missing-topics-fatal=true", "spring.kafka.jaas.enabled=true", - "spring.kafka.listener.immediate-stop=true", "spring.kafka.producer.transaction-id-prefix=foo", - "spring.kafka.jaas.login-module=foo", "spring.kafka.jaas.control-flag=REQUISITE", - "spring.kafka.jaas.options.useKeyTab=true", "spring.kafka.listener.async-acks=true") - .run((context) -> { - DefaultKafkaProducerFactory producerFactory = context - .getBean(DefaultKafkaProducerFactory.class); - DefaultKafkaConsumerFactory consumerFactory = context - .getBean(DefaultKafkaConsumerFactory.class); - KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); - AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context - .getBean(KafkaListenerContainerFactory.class); - assertThat(kafkaTemplate.getMessageConverter()).isInstanceOf(MessagingMessageConverter.class); - assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("producerFactory", producerFactory); - assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic"); - assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("transactionIdPrefix", "txOverride"); - assertThat(kafkaListenerContainerFactory.getConsumerFactory()).isEqualTo(consumerFactory); - ContainerProperties containerProperties = kafkaListenerContainerFactory.getContainerProperties(); - assertThat(containerProperties.getAckMode()).isEqualTo(AckMode.MANUAL); - assertThat(containerProperties.isAsyncAcks()).isTrue(); - assertThat(containerProperties.getClientId()).isEqualTo("client"); - assertThat(containerProperties.getAckCount()).isEqualTo(123); - assertThat(containerProperties.getAckTime()).isEqualTo(456L); - assertThat(containerProperties.getPollTimeout()).isEqualTo(2000L); - assertThat(containerProperties.getNoPollThreshold()).isEqualTo(2.5f); - assertThat(containerProperties.getIdleBetweenPolls()).isEqualTo(1000L); - assertThat(containerProperties.getIdleEventInterval()).isEqualTo(1000L); - assertThat(containerProperties.getIdlePartitionEventInterval()).isEqualTo(1000L); - assertThat(containerProperties.getMonitorInterval()).isEqualTo(45); - assertThat(containerProperties.isLogContainerConfig()).isTrue(); - assertThat(containerProperties.isMissingTopicsFatal()).isTrue(); - assertThat(containerProperties.isStopImmediate()).isTrue(); - assertThat(kafkaListenerContainerFactory).extracting("concurrency").isEqualTo(3); - assertThat(kafkaListenerContainerFactory.isBatchListener()).isTrue(); - assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).hasSize(1); - KafkaJaasLoginModuleInitializer jaas = context.getBean(KafkaJaasLoginModuleInitializer.class); - assertThat(jaas).hasFieldOrPropertyWithValue("loginModule", "foo"); - assertThat(jaas).hasFieldOrPropertyWithValue("controlFlag", - AppConfigurationEntry.LoginModuleControlFlag.REQUISITE); - assertThat(context.getBeansOfType(KafkaTransactionManager.class)).hasSize(1); - assertThat(((Map) ReflectionTestUtils.getField(jaas, "options"))) - .containsExactly(entry("useKeyTab", "true")); - }); + .withPropertyValues("spring.kafka.template.default-topic=testTopic", + "spring.kafka.template.transaction-id-prefix=txOverride", "spring.kafka.listener.ack-mode=MANUAL", + "spring.kafka.listener.client-id=client", "spring.kafka.listener.ack-count=123", + "spring.kafka.listener.ack-time=456", "spring.kafka.listener.concurrency=3", + "spring.kafka.listener.poll-timeout=2000", "spring.kafka.listener.no-poll-threshold=2.5", + "spring.kafka.listener.type=batch", "spring.kafka.listener.idle-between-polls=1s", + "spring.kafka.listener.idle-event-interval=1s", + "spring.kafka.listener.idle-partition-event-interval=1s", + "spring.kafka.listener.monitor-interval=45", "spring.kafka.listener.log-container-config=true", + "spring.kafka.listener.missing-topics-fatal=true", "spring.kafka.jaas.enabled=true", + "spring.kafka.listener.immediate-stop=true", "spring.kafka.producer.transaction-id-prefix=foo", + "spring.kafka.jaas.login-module=foo", "spring.kafka.jaas.control-flag=REQUISITE", + "spring.kafka.jaas.options.useKeyTab=true", "spring.kafka.listener.async-acks=true") + .run((context) -> { + DefaultKafkaProducerFactory producerFactory = context.getBean(DefaultKafkaProducerFactory.class); + DefaultKafkaConsumerFactory consumerFactory = context.getBean(DefaultKafkaConsumerFactory.class); + KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); + AbstractKafkaListenerContainerFactory kafkaListenerContainerFactory = (AbstractKafkaListenerContainerFactory) context + .getBean(KafkaListenerContainerFactory.class); + assertThat(kafkaTemplate.getMessageConverter()).isInstanceOf(MessagingMessageConverter.class); + assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("producerFactory", producerFactory); + assertThat(kafkaTemplate.getDefaultTopic()).isEqualTo("testTopic"); + assertThat(kafkaTemplate).hasFieldOrPropertyWithValue("transactionIdPrefix", "txOverride"); + assertThat(kafkaListenerContainerFactory.getConsumerFactory()).isEqualTo(consumerFactory); + ContainerProperties containerProperties = kafkaListenerContainerFactory.getContainerProperties(); + assertThat(containerProperties.getAckMode()).isEqualTo(AckMode.MANUAL); + assertThat(containerProperties.isAsyncAcks()).isTrue(); + assertThat(containerProperties.getClientId()).isEqualTo("client"); + assertThat(containerProperties.getAckCount()).isEqualTo(123); + assertThat(containerProperties.getAckTime()).isEqualTo(456L); + assertThat(containerProperties.getPollTimeout()).isEqualTo(2000L); + assertThat(containerProperties.getNoPollThreshold()).isEqualTo(2.5f); + assertThat(containerProperties.getIdleBetweenPolls()).isEqualTo(1000L); + assertThat(containerProperties.getIdleEventInterval()).isEqualTo(1000L); + assertThat(containerProperties.getIdlePartitionEventInterval()).isEqualTo(1000L); + assertThat(containerProperties.getMonitorInterval()).isEqualTo(45); + assertThat(containerProperties.isLogContainerConfig()).isTrue(); + assertThat(containerProperties.isMissingTopicsFatal()).isTrue(); + assertThat(containerProperties.isStopImmediate()).isTrue(); + assertThat(kafkaListenerContainerFactory).extracting("concurrency").isEqualTo(3); + assertThat(kafkaListenerContainerFactory.isBatchListener()).isTrue(); + assertThat(context.getBeansOfType(KafkaJaasLoginModuleInitializer.class)).hasSize(1); + KafkaJaasLoginModuleInitializer jaas = context.getBean(KafkaJaasLoginModuleInitializer.class); + assertThat(jaas).hasFieldOrPropertyWithValue("loginModule", "foo"); + assertThat(jaas).hasFieldOrPropertyWithValue("controlFlag", + AppConfigurationEntry.LoginModuleControlFlag.REQUISITE); + assertThat(context.getBeansOfType(KafkaTransactionManager.class)).hasSize(1); + assertThat(((Map) ReflectionTestUtils.getField(jaas, "options"))) + .containsExactly(entry("useKeyTab", "true")); + }); } @Test void testKafkaTemplateRecordMessageConverters() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { - KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); - assertThat(kafkaTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); - }); + .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test") + .run((context) -> { + KafkaTemplate kafkaTemplate = context.getBean(KafkaTemplate.class); + assertThat(kafkaTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryWithCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("recordMessageConverter", context.getBean("myMessageConverter")); }); @@ -527,34 +532,36 @@ class KafkaAutoConfigurationTests { @Test void testConcurrentKafkaListenerContainerFactoryInBatchModeWithCustomMessageConverter() { this.contextRunner - .withUserConfiguration(BatchMessageConverterConfiguration.class, MessageConverterConfiguration.class) - .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { - ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("batchMessageConverter", - context.getBean("myBatchMessageConverter")); - }); + .withUserConfiguration(BatchMessageConverterConfiguration.class, MessageConverterConfiguration.class) + .withPropertyValues("spring.kafka.listener.type=batch") + .run((context) -> { + ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("batchMessageConverter", + context.getBean("myBatchMessageConverter")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryInBatchModeWrapsCustomMessageConverter() { this.contextRunner.withUserConfiguration(MessageConverterConfiguration.class) - .withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { - ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, - "batchMessageConverter"); - assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); - assertThat(((BatchMessageConverter) messageConverter).getRecordMessageConverter()) - .isSameAs(context.getBean("myMessageConverter")); - }); + .withPropertyValues("spring.kafka.listener.type=batch") + .run((context) -> { + ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, + "batchMessageConverter"); + assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); + assertThat(((BatchMessageConverter) messageConverter).getRecordMessageConverter()) + .isSameAs(context.getBean("myMessageConverter")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryInBatchModeWithNoMessageConverter() { this.contextRunner.withPropertyValues("spring.kafka.listener.type=batch").run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); Object messageConverter = ReflectionTestUtils.getField(kafkaListenerContainerFactory, "batchMessageConverter"); assertThat(messageConverter).isInstanceOf(BatchMessagingMessageConverter.class); @@ -566,7 +573,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithDefaultRecordFilterStrategy() { this.contextRunner.run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("recordFilterStrategy", null); }); } @@ -575,7 +582,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomRecordFilterStrategy() { this.contextRunner.withUserConfiguration(RecordFilterStrategyConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("recordFilterStrategy", context.getBean("recordFilterStrategy")); }); @@ -584,12 +591,11 @@ class KafkaAutoConfigurationTests { @Test void testConcurrentKafkaListenerContainerFactoryWithCustomCommonErrorHandler() { this.contextRunner.withBean("errorHandler", CommonErrorHandler.class, () -> mock(CommonErrorHandler.class)) - .run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("commonErrorHandler", - context.getBean("errorHandler")); - }); + .run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("commonErrorHandler", context.getBean("errorHandler")); + }); } @Test @@ -597,9 +603,9 @@ class KafkaAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { assertThat(context).hasSingleBean(KafkaAwareTransactionManager.class); ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory.getContainerProperties().getTransactionManager()) - .isSameAs(context.getBean(KafkaAwareTransactionManager.class)); + .isSameAs(context.getBean(KafkaAwareTransactionManager.class)); }); } @@ -608,20 +614,21 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomTransactionManager() { KafkaTransactionManager customTransactionManager = mock(KafkaTransactionManager.class); this.contextRunner - .withBean("customTransactionManager", KafkaTransactionManager.class, () -> customTransactionManager) - .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test").run((context) -> { - ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); - assertThat(factory.getContainerProperties().getTransactionManager()) - .isSameAs(context.getBean("customTransactionManager")); - }); + .withBean("customTransactionManager", KafkaTransactionManager.class, () -> customTransactionManager) + .withPropertyValues("spring.kafka.producer.transaction-id-prefix=test") + .run((context) -> { + ConcurrentKafkaListenerContainerFactory factory = context + .getBean(ConcurrentKafkaListenerContainerFactory.class); + assertThat(factory.getContainerProperties().getTransactionManager()) + .isSameAs(context.getBean("customTransactionManager")); + }); } @Test void testConcurrentKafkaListenerContainerFactoryWithCustomAfterRollbackProcessor() { this.contextRunner.withUserConfiguration(AfterRollbackProcessorConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("afterRollbackProcessor", context.getBean("afterRollbackProcessor")); }); @@ -631,7 +638,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomRecordInterceptor() { this.contextRunner.withUserConfiguration(RecordInterceptorConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory).hasFieldOrPropertyWithValue("recordInterceptor", context.getBean("recordInterceptor")); }); } @@ -640,7 +647,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomRebalanceListener() { this.contextRunner.withUserConfiguration(RebalanceListenerConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory factory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(factory.getContainerProperties()).hasFieldOrPropertyWithValue("consumerRebalanceListener", context.getBean("rebalanceListener")); }); @@ -650,7 +657,7 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithKafkaTemplate() { this.contextRunner.run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(kafkaListenerContainerFactory).hasFieldOrPropertyWithValue("replyTemplate", context.getBean(KafkaTemplate.class)); }); @@ -660,24 +667,24 @@ class KafkaAutoConfigurationTests { void testConcurrentKafkaListenerContainerFactoryWithCustomConsumerFactory() { this.contextRunner.withUserConfiguration(ConsumerFactoryConfiguration.class).run((context) -> { ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory = context - .getBean(ConcurrentKafkaListenerContainerFactory.class); + .getBean(ConcurrentKafkaListenerContainerFactory.class); assertThat(kafkaListenerContainerFactory.getConsumerFactory()) - .isNotSameAs(context.getBean(ConsumerFactoryConfiguration.class).consumerFactory); + .isNotSameAs(context.getBean(ConsumerFactoryConfiguration.class).consumerFactory); }); } @Test void specificSecurityProtocolOverridesCommonSecurityProtocol() { - this.contextRunner.withPropertyValues("spring.kafka.security.protocol=SSL", - "spring.kafka.admin.security.protocol=PLAINTEXT").run((context) -> { - DefaultKafkaProducerFactory producerFactory = context - .getBean(DefaultKafkaProducerFactory.class); - Map producerConfigs = producerFactory.getConfigurationProperties(); - assertThat(producerConfigs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); - KafkaAdmin admin = context.getBean(KafkaAdmin.class); - Map configs = admin.getConfigurationProperties(); - assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "PLAINTEXT"); - }); + this.contextRunner + .withPropertyValues("spring.kafka.security.protocol=SSL", "spring.kafka.admin.security.protocol=PLAINTEXT") + .run((context) -> { + DefaultKafkaProducerFactory producerFactory = context.getBean(DefaultKafkaProducerFactory.class); + Map producerConfigs = producerFactory.getConfigurationProperties(); + assertThat(producerConfigs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); + KafkaAdmin admin = context.getBean(KafkaAdmin.class); + Map configs = admin.getConfigurationProperties(); + assertThat(configs).containsEntry(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "PLAINTEXT"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java index 2a897856d0..8ee0486d85 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kafka/KafkaPropertiesTests.java @@ -47,10 +47,10 @@ class KafkaPropertiesTests { @Test void isolationLevelEnumConsistentWithKafkaVersion() { org.apache.kafka.common.IsolationLevel[] original = org.apache.kafka.common.IsolationLevel.values(); - assertThat(original).extracting(Enum::name).containsExactly(IsolationLevel.READ_UNCOMMITTED.name(), - IsolationLevel.READ_COMMITTED.name()); - assertThat(original).extracting("id").containsExactly(IsolationLevel.READ_UNCOMMITTED.id(), - IsolationLevel.READ_COMMITTED.id()); + assertThat(original).extracting(Enum::name) + .containsExactly(IsolationLevel.READ_UNCOMMITTED.name(), IsolationLevel.READ_COMMITTED.name()); + assertThat(original).extracting("id") + .containsExactly(IsolationLevel.READ_UNCOMMITTED.id(), IsolationLevel.READ_COMMITTED.id()); assertThat(original).hasSameSizeAs(IsolationLevel.values()); } @@ -88,7 +88,7 @@ class KafkaPropertiesTests { properties.getSsl().setKeyStoreKey("-----BEGIN"); properties.getSsl().setKeyStoreLocation(new ClassPathResource("ksLoc")); assertThatExceptionOfType(MutuallyExclusiveConfigurationPropertiesException.class) - .isThrownBy(properties::buildConsumerProperties); + .isThrownBy(properties::buildConsumerProperties); } @Test @@ -97,7 +97,7 @@ class KafkaPropertiesTests { properties.getSsl().setTrustStoreLocation(new ClassPathResource("tsLoc")); properties.getSsl().setTrustStoreCertificates("-----BEGIN"); assertThatExceptionOfType(MutuallyExclusiveConfigurationPropertiesException.class) - .isThrownBy(properties::buildConsumerProperties); + .isThrownBy(properties::buildConsumerProperties); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java index 144db9dcd0..ec2aab1bed 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/kubernetes/ApplicationAvailabilityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ApplicationAvailabilityAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ApplicationAvailabilityAutoConfiguration.class)); @Test void providerIsPresent() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java index 53e8a62023..bde394cc67 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/LdapAutoConfigurationTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class LdapAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)); @Test void contextSourceWithDefaultUrl() { @@ -65,12 +65,12 @@ class LdapAutoConfigurationTests { @Test void contextSourceWithSeveralUrls() { this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123,ldap://mycompany:123") - .run((context) -> { - LdapContextSource contextSource = context.getBean(LdapContextSource.class); - LdapProperties ldapProperties = context.getBean(LdapProperties.class); - assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:123", "ldap://mycompany:123"); - assertThat(ldapProperties.getUrls()).hasSize(2); - }); + .run((context) -> { + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + LdapProperties ldapProperties = context.getBean(LdapProperties.class); + assertThat(contextSource.getUrls()).containsExactly("ldap://localhost:123", "ldap://mycompany:123"); + assertThat(ldapProperties.getUrls()).hasSize(2); + }); } @Test @@ -84,19 +84,21 @@ class LdapAutoConfigurationTests { @Test void contextSourceWithExtraCustomization() { - this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", - "spring.ldap.password:secret", "spring.ldap.anonymous-read-only:true", - "spring.ldap.base:cn=SpringDevelopers", - "spring.ldap.baseEnvironment.java.naming.security.authentication:DIGEST-MD5").run((context) -> { - LdapContextSource contextSource = context.getBean(LdapContextSource.class); - assertThat(contextSource.getUserDn()).isEqualTo("root"); - assertThat(contextSource.getPassword()).isEqualTo("secret"); - assertThat(contextSource.isAnonymousReadOnly()).isTrue(); - assertThat(contextSource.getBaseLdapPathAsString()).isEqualTo("cn=SpringDevelopers"); - LdapProperties ldapProperties = context.getBean(LdapProperties.class); - assertThat(ldapProperties.getBaseEnvironment()).containsEntry("java.naming.security.authentication", - "DIGEST-MD5"); - }); + this.contextRunner + .withPropertyValues("spring.ldap.urls:ldap://localhost:123", "spring.ldap.username:root", + "spring.ldap.password:secret", "spring.ldap.anonymous-read-only:true", + "spring.ldap.base:cn=SpringDevelopers", + "spring.ldap.baseEnvironment.java.naming.security.authentication:DIGEST-MD5") + .run((context) -> { + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + assertThat(contextSource.getUserDn()).isEqualTo("root"); + assertThat(contextSource.getPassword()).isEqualTo("secret"); + assertThat(contextSource.isAnonymousReadOnly()).isTrue(); + assertThat(contextSource.getBaseLdapPathAsString()).isEqualTo("cn=SpringDevelopers"); + LdapProperties ldapProperties = context.getBean(LdapProperties.class); + assertThat(ldapProperties.getBaseEnvironment()).containsEntry("java.naming.security.authentication", + "DIGEST-MD5"); + }); } @Test @@ -123,16 +125,18 @@ class LdapAutoConfigurationTests { @Test void templateConfigurationCanBeCustomized() { - this.contextRunner.withPropertyValues("spring.ldap.urls:ldap://localhost:389", - "spring.ldap.template.ignorePartialResultException=true", - "spring.ldap.template.ignoreNameNotFoundException=true", - "spring.ldap.template.ignoreSizeLimitExceededException=false").run((context) -> { - assertThat(context).hasSingleBean(LdapTemplate.class); - LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); - assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignorePartialResultException", true); - assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreNameNotFoundException", true); - assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreSizeLimitExceededException", false); - }); + this.contextRunner + .withPropertyValues("spring.ldap.urls:ldap://localhost:389", + "spring.ldap.template.ignorePartialResultException=true", + "spring.ldap.template.ignoreNameNotFoundException=true", + "spring.ldap.template.ignoreSizeLimitExceededException=false") + .run((context) -> { + assertThat(context).hasSingleBean(LdapTemplate.class); + LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); + assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignorePartialResultException", true); + assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreNameNotFoundException", true); + assertThat(ldapTemplate).hasFieldOrPropertyWithValue("ignoreSizeLimitExceededException", false); + }); } @Test @@ -150,22 +154,24 @@ class LdapAutoConfigurationTests { assertThat(context).hasSingleBean(DirContextAuthenticationStrategy.class); LdapContextSource contextSource = context.getBean(LdapContextSource.class); assertThat(contextSource).extracting("authenticationStrategy") - .isSameAs(context.getBean("customDirContextAuthenticationStrategy")); + .isSameAs(context.getBean("customDirContextAuthenticationStrategy")); }); } @Test void contextSourceWithCustomNonUniqueDirContextAuthenticationStrategy() { - this.contextRunner.withUserConfiguration(CustomDirContextAuthenticationStrategy.class, - AnotherCustomDirContextAuthenticationStrategy.class).run((context) -> { - assertThat(context).hasBean("customDirContextAuthenticationStrategy") - .hasBean("anotherCustomDirContextAuthenticationStrategy"); - LdapContextSource contextSource = context.getBean(LdapContextSource.class); - assertThat(contextSource).extracting("authenticationStrategy") - .isNotSameAs(context.getBean("customDirContextAuthenticationStrategy")) - .isNotSameAs(context.getBean("anotherCustomDirContextAuthenticationStrategy")) - .isInstanceOf(SimpleDirContextAuthenticationStrategy.class); - }); + this.contextRunner + .withUserConfiguration(CustomDirContextAuthenticationStrategy.class, + AnotherCustomDirContextAuthenticationStrategy.class) + .run((context) -> { + assertThat(context).hasBean("customDirContextAuthenticationStrategy") + .hasBean("anotherCustomDirContextAuthenticationStrategy"); + LdapContextSource contextSource = context.getBean(LdapContextSource.class); + assertThat(contextSource).extracting("authenticationStrategy") + .isNotSameAs(context.getBean("customDirContextAuthenticationStrategy")) + .isNotSameAs(context.getBean("anotherCustomDirContextAuthenticationStrategy")) + .isInstanceOf(SimpleDirContextAuthenticationStrategy.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java index 99fc0e38af..8833ccd11b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfigurationTests.java @@ -47,16 +47,16 @@ import static org.assertj.core.api.Assertions.assertThat; class EmbeddedLdapAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EmbeddedLdapAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(EmbeddedLdapAutoConfiguration.class)); @Test void testSetDefaultPort() { this.contextRunner - .withPropertyValues("spring.ldap.embedded.port:1234", "spring.ldap.embedded.base-dn:dc=spring,dc=org") - .run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - assertThat(server.getListenPort()).isEqualTo(1234); - }); + .withPropertyValues("spring.ldap.embedded.port:1234", "spring.ldap.embedded.base-dn:dc=spring,dc=org") + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.getListenPort()).isEqualTo(1234); + }); } @Test @@ -64,7 +64,7 @@ class EmbeddedLdapAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); assertThat(server.getListenPort()) - .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); + .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); }); } @@ -77,18 +77,18 @@ class EmbeddedLdapAutoConfigurationTests { context.refresh(); LDAPConnection connection = context.getBean(LDAPConnection.class); assertThat(connection.getConnectedPort()) - .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); + .isEqualTo(context.getEnvironment().getProperty("local.ldap.port", Integer.class)); } @Test void testSetCredentials() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", "spring.ldap.embedded.credential.username:uid=root", "spring.ldap.embedded.credential.password:boot") - .run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - BindResult result = server.bind("uid=root", "boot"); - assertThat(result).isNotNull(); - }); + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + BindResult result = server.bind("uid=root", "boot"); + assertThat(result).isNotNull(); + }); } @Test @@ -110,54 +110,59 @@ class EmbeddedLdapAutoConfigurationTests { @Test void testQueryEmbeddedLdap() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(LdapTemplate.class); - LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); - assertThat(ldapTemplate.list("ou=company1,c=Sweden,dc=spring,dc=org")).hasSize(4); - }); + .withConfiguration(AutoConfigurations.of(LdapAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(LdapTemplate.class); + LdapTemplate ldapTemplate = context.getBean(LdapTemplate.class); + assertThat(ldapTemplate.list("ou=company1,c=Sweden,dc=spring,dc=org")).hasSize(4); + }); } @Test void testDisableSchemaValidation() { - this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.enabled:false", - "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - assertThat(server.getSchema()).isNull(); - }); + this.contextRunner + .withPropertyValues("spring.ldap.embedded.validation.enabled:false", + "spring.ldap.embedded.base-dn:dc=spring,dc=org") + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.getSchema()).isNull(); + }); } @Test void testCustomSchemaValidation() { - this.contextRunner.withPropertyValues("spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", - "spring.ldap.embedded.ldif:classpath:custom-schema-sample.ldif", - "spring.ldap.embedded.base-dn:dc=spring,dc=org").run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - - assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")).isNotNull(); - assertThat(server.getSchema().getAttributeType("exampleAttributeName")).isNotNull(); - }); + this.contextRunner + .withPropertyValues("spring.ldap.embedded.validation.schema:classpath:custom-schema.ldif", + "spring.ldap.embedded.ldif:classpath:custom-schema-sample.ldif", + "spring.ldap.embedded.base-dn:dc=spring,dc=org") + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + + assertThat(server.getSchema().getObjectClass("exampleAuxiliaryClass")).isNotNull(); + assertThat(server.getSchema().getAttributeType("exampleAttributeName")).isNotNull(); + }); } @Test void testMultiBaseDn() { this.contextRunner.withPropertyValues("spring.ldap.embedded.ldif:classpath:schema-multi-basedn.ldif", "spring.ldap.embedded.base-dn[0]:dc=spring,dc=org", "spring.ldap.embedded.base-dn[1]:dc=vmware,dc=com") - .run((context) -> { - InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); - assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); - assertThat(server.countEntriesBelow("c=Sweden,dc=vmware,dc=com")).isEqualTo(2); - }); + .run((context) -> { + InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); + assertThat(server.countEntriesBelow("ou=company1,c=Sweden,dc=spring,dc=org")).isEqualTo(5); + assertThat(server.countEntriesBelow("c=Sweden,dc=vmware,dc=com")).isEqualTo(2); + }); } @Test void ldapContextSourceWithCredentialsIsCreated() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", "spring.ldap.embedded.credential.username:uid=root", "spring.ldap.embedded.credential.password:boot") - .run((context) -> { - LdapContextSource ldapContextSource = context.getBean(LdapContextSource.class); - assertThat(ldapContextSource.getUrls()).isNotEmpty(); - assertThat(ldapContextSource.getUserDn()).isEqualTo("uid=root"); - }); + .run((context) -> { + LdapContextSource ldapContextSource = context.getBean(LdapContextSource.class); + assertThat(ldapContextSource.getUrls()).isNotEmpty(); + assertThat(ldapContextSource.getUserDn()).isEqualTo("uid=root"); + }); } @Test @@ -172,19 +177,21 @@ class EmbeddedLdapAutoConfigurationTests { @Test void ldapContextWithoutSpringLdapIsNotCreated() { this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org") - .withClassLoader(new FilteredClassLoader(ContextSource.class)).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(LdapContextSource.class); - }); + .withClassLoader(new FilteredClassLoader(ContextSource.class)) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(LdapContextSource.class); + }); } @Test void ldapContextIsCreatedWithBase() { - this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", - "spring.ldap.base:dc=spring,dc=org").run((context) -> { - LdapContextSource ldapContextSource = context.getBean(LdapContextSource.class); - assertThat(ldapContextSource.getBaseLdapPathAsString()).isEqualTo("dc=spring,dc=org"); - }); + this.contextRunner + .withPropertyValues("spring.ldap.embedded.base-dn:dc=spring,dc=org", "spring.ldap.base:dc=spring,dc=org") + .run((context) -> { + LdapContextSource ldapContextSource = context.getBean(LdapContextSource.class); + assertThat(ldapContextSource.getBaseLdapPathAsString()).isEqualTo("dc=spring,dc=org"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java index dfa51d625d..f61a139983 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfigurationTests.java @@ -80,8 +80,8 @@ import static org.assertj.core.api.Assertions.contentOf; class LiquibaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void backsOffWithNoDataSourceBeanAndNoLiquibaseUrl() { @@ -100,118 +100,118 @@ class LiquibaseAutoConfigurationTests { @Test void backsOffWithLiquibaseUrlAndNoSpringJdbc() { this.contextRunner.withPropertyValues("spring.liquibase.url:jdbc:hsqldb:mem:" + UUID.randomUUID()) - .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) - .run((context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); + .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) + .run((context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class)); } @Test void defaultSpringLiquibase() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .run(assertLiquibase((liquibase) -> { - assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); - assertThat(liquibase.getContexts()).isNull(); - assertThat(liquibase.getDefaultSchema()).isNull(); - assertThat(liquibase.isDropFirst()).isFalse(); - assertThat(liquibase.isClearCheckSums()).isFalse(); - })); + .run(assertLiquibase((liquibase) -> { + assertThat(liquibase.getChangeLog()).isEqualTo("classpath:/db/changelog/db.changelog-master.yaml"); + assertThat(liquibase.getContexts()).isNull(); + assertThat(liquibase.getDefaultSchema()).isNull(); + assertThat(liquibase.isDropFirst()).isFalse(); + assertThat(liquibase.isClearCheckSums()).isFalse(); + })); } @Test void changelogXml() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.xml"))); + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.xml"))); } @Test void changelogJson() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.json"))); + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.json"))); } @Test void changelogSql() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) - .isEqualTo("classpath:/db/changelog/db.changelog-override.sql"))); + .withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog()) + .isEqualTo("classpath:/db/changelog/db.changelog-override.sql"))); } @Test void defaultValues() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .run(assertLiquibase((liquibase) -> { - LiquibaseProperties properties = new LiquibaseProperties(); - assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo(properties.getDatabaseChangeLogTable()); - assertThat(liquibase.getDatabaseChangeLogLockTable()) - .isEqualTo(properties.getDatabaseChangeLogLockTable()); - assertThat(liquibase.isDropFirst()).isEqualTo(properties.isDropFirst()); - assertThat(liquibase.isClearCheckSums()).isEqualTo(properties.isClearChecksums()); - assertThat(liquibase.isTestRollbackOnUpdate()).isEqualTo(properties.isTestRollbackOnUpdate()); - })); + .run(assertLiquibase((liquibase) -> { + LiquibaseProperties properties = new LiquibaseProperties(); + assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo(properties.getDatabaseChangeLogTable()); + assertThat(liquibase.getDatabaseChangeLogLockTable()) + .isEqualTo(properties.getDatabaseChangeLogLockTable()); + assertThat(liquibase.isDropFirst()).isEqualTo(properties.isDropFirst()); + assertThat(liquibase.isClearCheckSums()).isEqualTo(properties.isClearChecksums()); + assertThat(liquibase.isTestRollbackOnUpdate()).isEqualTo(properties.isTestRollbackOnUpdate()); + })); } @Test void overrideContexts() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.contexts:test, production") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts()).isEqualTo("test, production"))); + .withPropertyValues("spring.liquibase.contexts:test, production") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts()).isEqualTo("test, production"))); } @Test void overrideDefaultSchema() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.default-schema:public") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getDefaultSchema()).isEqualTo("public"))); + .withPropertyValues("spring.liquibase.default-schema:public") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getDefaultSchema()).isEqualTo("public"))); } @Test void overrideLiquibaseInfrastructure() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.liquibase-schema:public", - "spring.liquibase.liquibase-tablespace:infra", - "spring.liquibase.database-change-log-table:LIQUI_LOG", - "spring.liquibase.database-change-log-lock-table:LIQUI_LOCK") - .run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.getLiquibaseSchema()).isEqualTo("public"); - assertThat(liquibase.getLiquibaseTablespace()).isEqualTo("infra"); - assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo("LIQUI_LOG"); - assertThat(liquibase.getDatabaseChangeLogLockTable()).isEqualTo("LIQUI_LOCK"); - JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); - assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOG", Integer.class)) - .isOne(); - assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOCK", Integer.class)) - .isOne(); - }); + .withPropertyValues("spring.liquibase.liquibase-schema:public", + "spring.liquibase.liquibase-tablespace:infra", + "spring.liquibase.database-change-log-table:LIQUI_LOG", + "spring.liquibase.database-change-log-lock-table:LIQUI_LOCK") + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + assertThat(liquibase.getLiquibaseSchema()).isEqualTo("public"); + assertThat(liquibase.getLiquibaseTablespace()).isEqualTo("infra"); + assertThat(liquibase.getDatabaseChangeLogTable()).isEqualTo("LIQUI_LOG"); + assertThat(liquibase.getDatabaseChangeLogLockTable()).isEqualTo("LIQUI_LOCK"); + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(DataSource.class)); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOG", Integer.class)).isOne(); + assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM public.LIQUI_LOCK", Integer.class)) + .isOne(); + }); } @Test void overrideDropFirst() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.drop-first:true") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.isDropFirst()).isTrue())); + .withPropertyValues("spring.liquibase.drop-first:true") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.isDropFirst()).isTrue())); } @Test void overrideClearChecksums() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.clear-checksums:true") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.isClearCheckSums()).isTrue())); + .withPropertyValues("spring.liquibase.clear-checksums:true") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.isClearCheckSums()).isTrue())); } @Test void overrideDataSource() { String jdbcUrl = "jdbc:hsqldb:mem:liquibase" + UUID.randomUUID(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.url:" + jdbcUrl).run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); - assertThat(dataSource.getDriver().getClass().getName()).isEqualTo("org.hsqldb.jdbc.JDBCDriver"); - })); + .withPropertyValues("spring.liquibase.url:" + jdbcUrl) + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); + assertThat(dataSource.getDriver().getClass().getName()).isEqualTo("org.hsqldb.jdbc.JDBCDriver"); + })); } @Test @@ -219,132 +219,139 @@ class LiquibaseAutoConfigurationTests { String jdbcUrl = "jdbc:hsqldb:mem:liquibase" + UUID.randomUUID(); String driverClassName = "org.hsqldb.jdbcDriver"; this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.url:" + jdbcUrl, - "spring.liquibase.driver-class-name:" + driverClassName) - .run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); - assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); - })); + .withPropertyValues("spring.liquibase.url:" + jdbcUrl, + "spring.liquibase.driver-class-name:" + driverClassName) + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).isEqualTo(jdbcUrl); + assertThat(dataSource.getDriver().getClass().getName()).isEqualTo(driverClassName); + })); } @Test void overrideUser() { String databaseName = "normal" + UUID.randomUUID(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.datasource.generate-unique-name:false", - "spring.datasource.name:" + databaseName, "spring.datasource.username:not-sa", - "spring.liquibase.user:sa") - .run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).contains("jdbc:h2:mem:" + databaseName); - assertThat(dataSource.getUsername()).isEqualTo("sa"); - })); + .withPropertyValues("spring.datasource.generate-unique-name:false", + "spring.datasource.name:" + databaseName, "spring.datasource.username:not-sa", + "spring.liquibase.user:sa") + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).contains("jdbc:h2:mem:" + databaseName); + assertThat(dataSource.getUsername()).isEqualTo("sa"); + })); } @Test void overrideUserWhenCustom() { this.contextRunner.withUserConfiguration(CustomDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.user:test", "spring.liquibase.password:secret").run((context) -> { - String expectedName = context.getBean(CustomDataSourceConfiguration.class).name; - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).contains(expectedName); - assertThat(dataSource.getUsername()).isEqualTo("test"); - }); + .withPropertyValues("spring.liquibase.user:test", "spring.liquibase.password:secret") + .run((context) -> { + String expectedName = context.getBean(CustomDataSourceConfiguration.class).name; + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).contains(expectedName); + assertThat(dataSource.getUsername()).isEqualTo("test"); + }); } @Test void createDataSourceDoesNotFallbackToEmbeddedProperties() { String jdbcUrl = "jdbc:hsqldb:mem:liquibase" + UUID.randomUUID(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.url:" + jdbcUrl).run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUsername()).isNull(); - assertThat(dataSource.getPassword()).isNull(); - })); + .withPropertyValues("spring.liquibase.url:" + jdbcUrl) + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUsername()).isNull(); + assertThat(dataSource.getPassword()).isNull(); + })); } @Test void overrideUserAndFallbackToEmbeddedProperties() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.user:sa").run(assertLiquibase((liquibase) -> { - SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); - assertThat(dataSource.getUrl()).startsWith("jdbc:h2:mem:"); - })); + .withPropertyValues("spring.liquibase.user:sa") + .run(assertLiquibase((liquibase) -> { + SimpleDriverDataSource dataSource = (SimpleDriverDataSource) liquibase.getDataSource(); + assertThat(dataSource.getUrl()).startsWith("jdbc:h2:mem:"); + })); } @Test void overrideTestRollbackOnUpdate() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.test-rollback-on-update:true").run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.isTestRollbackOnUpdate()).isTrue(); - }); + .withPropertyValues("spring.liquibase.test-rollback-on-update:true") + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + assertThat(liquibase.isTestRollbackOnUpdate()).isTrue(); + }); } @Test void changeLogDoesNotExist() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.change-log:classpath:/no-such-changelog.yaml").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); - }); + .withPropertyValues("spring.liquibase.change-log:classpath:/no-such-changelog.yaml") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().isInstanceOf(BeanCreationException.class); + }); } @Test void logging(CapturedOutput output) { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .run(assertLiquibase((liquibase) -> assertThat(output).doesNotContain(": liquibase:"))); + .run(assertLiquibase((liquibase) -> assertThat(output).doesNotContain(": liquibase:"))); } @Test void overrideLabelFilter() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.label-filter:test, production").run(assertLiquibase( - (liquibase) -> assertThat(liquibase.getLabelFilter()).isEqualTo("test, production"))); + .withPropertyValues("spring.liquibase.label-filter:test, production") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabelFilter()).isEqualTo("test, production"))); } @Test @Deprecated(since = "3.0.0", forRemoval = true) void overrideLabelFilterWithDeprecatedLabelsProperty() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.labels:test, production").run(assertLiquibase( - (liquibase) -> assertThat(liquibase.getLabelFilter()).isEqualTo("test, production"))); + .withPropertyValues("spring.liquibase.labels:test, production") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabelFilter()).isEqualTo("test, production"))); } @Test @SuppressWarnings("unchecked") void testOverrideParameters() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.parameters.foo:bar").run(assertLiquibase((liquibase) -> { - Map parameters = (Map) ReflectionTestUtils.getField(liquibase, - "parameters"); - assertThat(parameters).containsKey("foo"); - assertThat(parameters).containsEntry("foo", "bar"); - })); + .withPropertyValues("spring.liquibase.parameters.foo:bar") + .run(assertLiquibase((liquibase) -> { + Map parameters = (Map) ReflectionTestUtils.getField(liquibase, + "parameters"); + assertThat(parameters).containsKey("foo"); + assertThat(parameters).containsEntry("foo", "bar"); + })); } @Test void rollbackFile(@TempDir Path temp) throws IOException { File file = Files.createTempFile(temp, "rollback-file", "sql").toFile(); this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.rollbackFile:" + file.getAbsolutePath()).run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - File actualFile = (File) ReflectionTestUtils.getField(liquibase, "rollbackFile"); - assertThat(actualFile).isEqualTo(file).exists(); - assertThat(contentOf(file)).contains("DROP TABLE PUBLIC.customer;"); - }); + .withPropertyValues("spring.liquibase.rollbackFile:" + file.getAbsolutePath()) + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + File actualFile = (File) ReflectionTestUtils.getField(liquibase, "rollbackFile"); + assertThat(actualFile).isEqualTo(file).exists(); + assertThat(contentOf(file)).contains("DROP TABLE PUBLIC.customer;"); + }); } @Test void liquibaseDataSource() { this.contextRunner - .withUserConfiguration(LiquibaseDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); - assertThat(liquibase.getDataSource()).isEqualTo(context.getBean("liquibaseDataSource")); - }); + .withUserConfiguration(LiquibaseDataSourceConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + SpringLiquibase liquibase = context.getBean(SpringLiquibase.class); + assertThat(liquibase.getDataSource()).isEqualTo(context.getBean("liquibaseDataSource")); + }); } @Test @@ -358,57 +365,58 @@ class LiquibaseAutoConfigurationTests { @Test void userConfigurationBeans() { this.contextRunner - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - assertThat(context).hasBean("springLiquibase"); - assertThat(context).doesNotHaveBean("liquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("springLiquibase"); + assertThat(context).doesNotHaveBean("liquibase"); + }); } @Test void userConfigurationEntityManagerFactoryDependency() { this.contextRunner.withConfiguration(AutoConfigurations.of(HibernateJpaAutoConfiguration.class)) - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("entityManagerFactory"); - assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("entityManagerFactory"); + assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); + }); } @Test void userConfigurationJdbcTemplateDependency() { this.contextRunner.withConfiguration(AutoConfigurations.of(JdbcTemplateAutoConfiguration.class)) - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("jdbcTemplate"); - assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("jdbcTemplate"); + assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); + }); } @Test void overrideTag() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.liquibase.tag:1.0.0") - .run(assertLiquibase((liquibase) -> assertThat(liquibase.getTag()).isEqualTo("1.0.0"))); + .withPropertyValues("spring.liquibase.tag:1.0.0") + .run(assertLiquibase((liquibase) -> assertThat(liquibase.getTag()).isEqualTo("1.0.0"))); } @Test void whenLiquibaseIsAutoConfiguredThenJooqDslContextDependsOnSpringLiquibaseBeans() { this.contextRunner.withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) - .withUserConfiguration(EmbeddedDataSourceConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactly("liquibase"); - }); + .withUserConfiguration(EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactly("liquibase"); + }); } @Test void whenCustomSpringLiquibaseIsDefinedThenJooqDslContextDependsOnSpringLiquibaseBeans() { this.contextRunner.withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) - .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) - .run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); - assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); - }); + .withUserConfiguration(LiquibaseUserConfiguration.class, EmbeddedDataSourceConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition("dslContext"); + assertThat(beanDefinition.getDependsOn()).containsExactly("springLiquibase"); + }); } @Test @@ -416,7 +424,7 @@ class LiquibaseAutoConfigurationTests { RuntimeHints hints = new RuntimeHints(); new LiquibaseAutoConfigurationRuntimeHints().registerHints(hints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.resource().forResource("db/changelog/db.changelog-master.yaml")) - .accepts(hints); + .accepts(hints); } private ContextConsumer assertLiquibase(Consumer consumer) { @@ -439,8 +447,10 @@ class LiquibaseAutoConfigurationTests { @LiquibaseDataSource @Bean DataSource liquibaseDataSource() { - return DataSourceBuilder.create().url("jdbc:hsqldb:mem:liquibasetest" + UUID.randomUUID()).username("sa") - .build(); + return DataSourceBuilder.create() + .url("jdbc:hsqldb:mem:liquibasetest" + UUID.randomUUID()) + .username("sa") + .build(); } } @@ -467,7 +477,8 @@ class LiquibaseAutoConfigurationTests { @Bean(destroyMethod = "shutdown") EmbeddedDatabase dataSource() throws SQLException { EmbeddedDatabase database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) - .setName(this.name).build(); + .setName(this.name) + .build(); insertUser(database); return database; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggerTests.java index 690e74584b..c728158876 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,8 +52,8 @@ class ConditionEvaluationReportLoggerTests { @Test void supportsOnlyInfoAndDebugLogLevels() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ConditionEvaluationReportLogger(LogLevel.TRACE, () -> null)) - .withMessageContaining("LogLevel must be INFO or DEBUG"); + .isThrownBy(() -> new ConditionEvaluationReportLogger(LogLevel.TRACE, () -> null)) + .withMessageContaining("LogLevel must be INFO or DEBUG"); } @Test @@ -110,7 +110,7 @@ class ConditionEvaluationReportLoggerTests { private void withDebugLogging(Runnable runnable) { Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()) - .getLogger(ConditionEvaluationReportLogger.class); + .getLogger(ConditionEvaluationReportLogger.class); Level currentLevel = logger.getLevel(); logger.setLevel(Level.DEBUG); try { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java index 39478c89ae..87b56eae87 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,8 +68,8 @@ class ConditionEvaluationReportLoggingListenerTests { this.initializer.initialize(context); context.register(ErrorConfig.class); assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) - .satisfies((ex) -> withDebugLogging(() -> context.publishEvent( - new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); + .satisfies((ex) -> withDebugLogging(() -> context + .publishEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); assertThat(output).contains("CONDITIONS EVALUATION REPORT"); } @@ -79,10 +79,10 @@ class ConditionEvaluationReportLoggingListenerTests { this.initializer.initialize(context); context.register(ErrorConfig.class); assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) - .satisfies((ex) -> withInfoLogging(() -> context.publishEvent( - new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); + .satisfies((ex) -> withInfoLogging(() -> context + .publishEvent(new ApplicationFailedEvent(new SpringApplication(), new String[0], context, ex)))); assertThat(output).doesNotContain("CONDITIONS EVALUATION REPORT") - .contains("re-run your application with 'debug' enabled"); + .contains("re-run your application with 'debug' enabled"); } @Test @@ -114,7 +114,7 @@ class ConditionEvaluationReportLoggingListenerTests { private void withLoggingLevel(Level logLevel, Runnable runnable) { Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()) - .getLogger(ConditionEvaluationReportLogger.class); + .getLogger(ConditionEvaluationReportLogger.class); Level currentLevel = logger.getLevel(); logger.setLevel(logLevel); try { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessorTests.java index 38c647e490..34c5832b75 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,8 +44,8 @@ class ConditionEvaluationReportLoggingProcessorTests { @Test void logsDebugOnProcessAheadOfTime(CapturedOutput output) { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - ConditionEvaluationReport.get(beanFactory).recordConditionEvaluation("test", mock(Condition.class), - ConditionOutcome.match()); + ConditionEvaluationReport.get(beanFactory) + .recordConditionEvaluation("test", mock(Condition.class), ConditionOutcome.match()); ConditionEvaluationReportLoggingProcessor processor = new ConditionEvaluationReportLoggingProcessor(); processor.processAheadOfTime(beanFactory); assertThat(output).doesNotContain("CONDITIONS EVALUATION REPORT"); @@ -55,7 +55,7 @@ class ConditionEvaluationReportLoggingProcessorTests { private void withDebugLogging(Runnable runnable) { Logger logger = ((LoggerContext) LoggerFactory.getILoggerFactory()) - .getLogger(ConditionEvaluationReportLogger.class); + .getLogger(ConditionEvaluationReportLogger.class); Level currentLevel = logger.getLevel(); logger.setLevel(Level.DEBUG); try { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java index 6ccc7217d7..6fd720cbba 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mail/MailSenderAutoConfigurationTests.java @@ -91,29 +91,31 @@ class MailSenderAutoConfigurationTests { @Test void smtpHostWithSettings() { String host = "192.168.1.234"; - this.contextRunner.withPropertyValues("spring.mail.host:" + host, "spring.mail.port:42", - "spring.mail.username:john", "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", - "spring.mail.protocol:smtps").run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getHost()).isEqualTo(host); - assertThat(mailSender.getPort()).isEqualTo(42); - assertThat(mailSender.getUsername()).isEqualTo("john"); - assertThat(mailSender.getPassword()).isEqualTo("secret"); - assertThat(mailSender.getDefaultEncoding()).isEqualTo("US-ASCII"); - assertThat(mailSender.getProtocol()).isEqualTo("smtps"); - }); + this.contextRunner + .withPropertyValues("spring.mail.host:" + host, "spring.mail.port:42", "spring.mail.username:john", + "spring.mail.password:secret", "spring.mail.default-encoding:US-ASCII", + "spring.mail.protocol:smtps") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getHost()).isEqualTo(host); + assertThat(mailSender.getPort()).isEqualTo(42); + assertThat(mailSender.getUsername()).isEqualTo("john"); + assertThat(mailSender.getPassword()).isEqualTo("secret"); + assertThat(mailSender.getDefaultEncoding()).isEqualTo("US-ASCII"); + assertThat(mailSender.getProtocol()).isEqualTo("smtps"); + }); } @Test void smtpHostWithJavaMailProperties() { this.contextRunner - .withPropertyValues("spring.mail.host:localhost", "spring.mail.properties.mail.smtp.auth:true") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getJavaMailProperties()).containsEntry("mail.smtp.auth", "true"); - }); + .withPropertyValues("spring.mail.host:localhost", "spring.mail.properties.mail.smtp.auth:true") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getJavaMailProperties()).containsEntry("mail.smtp.auth", "true"); + }); } @Test @@ -124,14 +126,14 @@ class MailSenderAutoConfigurationTests { @Test void mailSenderBackOff() { this.contextRunner.withUserConfiguration(ManualMailConfiguration.class) - .withPropertyValues("spring.mail.host:smtp.acme.org", "spring.mail.user:user", - "spring.mail.password:secret") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getUsername()).isNull(); - assertThat(mailSender.getPassword()).isNull(); - }); + .withPropertyValues("spring.mail.host:smtp.acme.org", "spring.mail.user:user", + "spring.mail.password:secret") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getUsername()).isNull(); + assertThat(mailSender.getPassword()).isNull(); + }); } @Test @@ -179,7 +181,7 @@ class MailSenderAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo").run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Unable to find Session in JNDI location foo"); + .hasMessageContaining("Unable to find Session in JNDI location foo"); }); } @@ -187,54 +189,55 @@ class MailSenderAutoConfigurationTests { void jndiSessionTakesPrecedenceOverProperties() { Session session = configureJndiSession("foo"); this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.host:localhost") - .run((context) -> { - assertThat(context).hasSingleBean(Session.class); - Session sessionBean = context.getBean(Session.class); - assertThat(sessionBean).isEqualTo(session); - assertThat(context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Session.class); + Session sessionBean = context.getBean(Session.class); + assertThat(sessionBean).isEqualTo(session); + assertThat(context.getBean(JavaMailSenderImpl.class).getSession()).isEqualTo(sessionBean); + }); } @Test void defaultEncodingWithProperties() { this.contextRunner.withPropertyValues("spring.mail.host:localhost", "spring.mail.default-encoding:UTF-16") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); + }); } @Test void defaultEncodingWithJndi() { configureJndiSession("foo"); this.contextRunner.withPropertyValues("spring.mail.jndi-name:foo", "spring.mail.default-encoding:UTF-16") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + assertThat(mailSender.getDefaultEncoding()).isEqualTo("UTF-16"); + }); } @Test void connectionOnStartup() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) - .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true").run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - then(mailSender).should().testConnection(); - }); + .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:true") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + then(mailSender).should().testConnection(); + }); } @Test void connectionOnStartupNotCalled() { this.contextRunner.withUserConfiguration(MockMailConfiguration.class) - .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:false") - .run((context) -> { - assertThat(context).hasSingleBean(JavaMailSenderImpl.class); - JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); - then(mailSender).should(never()).testConnection(); - }); + .withPropertyValues("spring.mail.host:10.0.0.23", "spring.mail.test-connection:false") + .run((context) -> { + assertThat(context).hasSingleBean(JavaMailSenderImpl.class); + JavaMailSenderImpl mailSender = context.getBean(JavaMailSenderImpl.class); + then(mailSender).should(never()).testConnection(); + }); } private Session configureJndiSession(String name) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java index b6ff9c5521..abe1ec7a09 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; class MongoAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class)); @Test void clientExists() { @@ -52,36 +52,36 @@ class MongoAutoConfigurationTests { @Test void settingsAdded() { this.contextRunner.withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat( - getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(300)); + .run((context) -> assertThat( + getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(300)); } @Test void settingsAddedButNoHost() { this.contextRunner.withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat( - getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(300)); + .run((context) -> assertThat( + getSettings(context).getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) + .isEqualTo(300)); } @Test void settingsSslConfig() { this.contextRunner.withUserConfiguration(SslSettingsConfig.class) - .run((context) -> assertThat(getSettings(context).getSslSettings().isEnabled()).isTrue()); + .run((context) -> assertThat(getSettings(context).getSslSettings().isEnabled()).isTrue()); } @Test void configuresSingleClient() { this.contextRunner.withUserConfiguration(FallbackMongoClientConfig.class) - .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); + .run((context) -> assertThat(context).hasSingleBean(MongoClient.class)); } @Test void customizerOverridesAutoConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") - .withUserConfiguration(SimpleCustomizerConfig.class) - .run((context) -> assertThat(getSettings(context).getApplicationName()).isEqualTo("overridden-name")); + .withUserConfiguration(SimpleCustomizerConfig.class) + .run((context) -> assertThat(getSettings(context).getApplicationName()).isEqualTo("overridden-name")); } private MongoClientSettings getSettings(AssertableApplicationContext context) { @@ -95,8 +95,9 @@ class MongoAutoConfigurationTests { @Bean MongoClientSettings mongoClientSettings() { - return MongoClientSettings.builder().applyToSocketSettings( - (socketSettings) -> socketSettings.connectTimeout(300, TimeUnit.MILLISECONDS)).build(); + return MongoClientSettings.builder() + .applyToSocketSettings((socketSettings) -> socketSettings.connectTimeout(300, TimeUnit.MILLISECONDS)) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java index 1829ec803c..984360a68e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoClientFactorySupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -76,20 +76,20 @@ abstract class MongoClientFactorySupportTests { T client = createMongoClient(settings); MongoClientSettings wrapped = getClientSettings(client); assertThat(wrapped.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS)); assertThat(wrapped.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS)); assertThat(wrapped.getServerSettings().getHeartbeatFrequency(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getServerSettings().getHeartbeatFrequency(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getServerSettings().getHeartbeatFrequency(TimeUnit.MILLISECONDS)); assertThat(wrapped.getServerSettings().getMinHeartbeatFrequency(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getServerSettings().getMinHeartbeatFrequency(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getServerSettings().getMinHeartbeatFrequency(TimeUnit.MILLISECONDS)); assertThat(wrapped.getApplicationName()).isEqualTo(settings.getApplicationName()); assertThat(wrapped.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)); assertThat(wrapped.getConnectionPoolSettings().getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionLifeTime(TimeUnit.MILLISECONDS)); assertThat(wrapped.getConnectionPoolSettings().getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)) - .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)); + .isEqualTo(settings.getConnectionPoolSettings().getMaxConnectionIdleTime(TimeUnit.MILLISECONDS)); assertThat(wrapped.getSslSettings().isEnabled()).isEqualTo(settings.getSslSettings().isEnabled()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java index 30ed753e99..268c8963a1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/MongoReactiveAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ import static org.mockito.Mockito.mock; class MongoReactiveAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MongoReactiveAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MongoReactiveAutoConfiguration.class)); @Test void clientExists() { @@ -61,28 +61,28 @@ class MongoReactiveAutoConfigurationTests { @Test void settingsAdded() { this.contextRunner.withPropertyValues("spring.data.mongodb.host:localhost") - .withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat(getSettings(context).getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) - .isEqualTo(300)); + .withUserConfiguration(SettingsConfig.class) + .run((context) -> assertThat(getSettings(context).getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) + .isEqualTo(300)); } @Test void settingsAddedButNoHost() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") - .withUserConfiguration(SettingsConfig.class) - .run((context) -> assertThat(getSettings(context).getReadPreference()) - .isEqualTo(ReadPreference.nearest())); + .withUserConfiguration(SettingsConfig.class) + .run((context) -> assertThat(getSettings(context).getReadPreference()).isEqualTo(ReadPreference.nearest())); } @Test void settingsSslConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") - .withUserConfiguration(SslSettingsConfig.class).run((context) -> { - assertThat(context).hasSingleBean(MongoClient.class); - MongoClientSettings settings = getSettings(context); - assertThat(settings.getApplicationName()).isEqualTo("test-config"); - assertThat(settings.getStreamFactoryFactory()).isSameAs(context.getBean("myStreamFactoryFactory")); - }); + .withUserConfiguration(SslSettingsConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(MongoClient.class); + MongoClientSettings settings = getSettings(context); + assertThat(settings.getApplicationName()).isEqualTo("test-config"); + assertThat(settings.getStreamFactoryFactory()).isSameAs(context.getBean("myStreamFactoryFactory")); + }); } @Test @@ -102,13 +102,13 @@ class MongoReactiveAutoConfigurationTests { @Test void customizerOverridesAutoConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") - .withUserConfiguration(SimpleCustomizerConfig.class).run((context) -> { - assertThat(context).hasSingleBean(MongoClient.class); - MongoClientSettings settings = getSettings(context); - assertThat(settings.getApplicationName()).isEqualTo("overridden-name"); - assertThat(settings.getStreamFactoryFactory()) - .isEqualTo(SimpleCustomizerConfig.streamFactoryFactory); - }); + .withUserConfiguration(SimpleCustomizerConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(MongoClient.class); + MongoClientSettings settings = getSettings(context); + assertThat(settings.getApplicationName()).isEqualTo("overridden-name"); + assertThat(settings.getStreamFactoryFactory()).isEqualTo(SimpleCustomizerConfig.streamFactoryFactory); + }); } private MongoClientSettings getSettings(ApplicationContext context) { @@ -121,8 +121,10 @@ class MongoReactiveAutoConfigurationTests { @Bean MongoClientSettings mongoClientSettings() { - return MongoClientSettings.builder().readPreference(ReadPreference.nearest()) - .applyToSocketSettings((socket) -> socket.readTimeout(300, TimeUnit.SECONDS)).build(); + return MongoClientSettings.builder() + .readPreference(ReadPreference.nearest()) + .applyToSocketSettings((socket) -> socket.readTimeout(300, TimeUnit.SECONDS)) + .build(); } } @@ -132,8 +134,10 @@ class MongoReactiveAutoConfigurationTests { @Bean MongoClientSettings mongoClientSettings(StreamFactoryFactory streamFactoryFactory) { - return MongoClientSettings.builder().applicationName("test-config") - .streamFactoryFactory(streamFactoryFactory).build(); + return MongoClientSettings.builder() + .applicationName("test-config") + .streamFactoryFactory(streamFactoryFactory) + .build(); } @Bean @@ -149,12 +153,12 @@ class MongoReactiveAutoConfigurationTests { static class SimpleCustomizerConfig { private static final StreamFactoryFactory streamFactoryFactory = new AsynchronousSocketChannelStreamFactoryFactory.Builder() - .build(); + .build(); @Bean MongoClientSettingsBuilderCustomizer customizer() { return (clientSettingsBuilder) -> clientSettingsBuilder.applicationName("overridden-name") - .streamFactoryFactory(streamFactoryFactory); + .streamFactoryFactory(streamFactoryFactory); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java index 61b4091692..9f9524eaa7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -56,15 +56,27 @@ class MustacheAutoConfigurationReactiveIntegrationTests { @Test void testHomePage() { - String result = this.client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) - .returnResult().getResponseBody(); + String result = this.client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); } @Test void testPartialPage() { - String result = this.client.get().uri("/partial").exchange().expectStatus().isOk().expectBody(String.class) - .returnResult().getResponseBody(); + String result = this.client.get() + .uri("/partial") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(result).contains("Hello App").contains("Hello World"); } @@ -93,7 +105,7 @@ class MustacheAutoConfigurationReactiveIntegrationTests { @Bean MustacheViewResolver viewResolver() { Mustache.Compiler compiler = Mustache.compiler() - .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); + .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); MustacheViewResolver resolver = new MustacheViewResolver(compiler); resolver.setPrefix("classpath:/mustache-templates/"); resolver.setSuffix(".html"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java index b8304a1e48..c6c892e333 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationServletIntegrationTests.java @@ -115,7 +115,7 @@ class MustacheAutoConfigurationServletIntegrationTests { @Bean MustacheViewResolver viewResolver() { Mustache.Compiler compiler = Mustache.compiler() - .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); + .withLoader(new MustacheResourceTemplateLoader("classpath:/mustache-templates/", ".html")); MustacheViewResolver resolver = new MustacheViewResolver(compiler); resolver.setPrefix("classpath:/mustache-templates/"); resolver.setSuffix(".html"); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java index 055036f975..7d1d54fc1d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,22 +56,22 @@ class MustacheAutoConfigurationTests { @Test void servletViewResolverCanBeDisabled() { configure(new WebApplicationContextRunner()).withPropertyValues("spring.mustache.enabled=false") - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).doesNotHaveBean(MustacheViewResolver.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context).doesNotHaveBean(MustacheViewResolver.class); + }); } @Test void registerCompilerForServletApp() { configure(new WebApplicationContextRunner()).withUserConfiguration(CustomCompilerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).hasSingleBean(MustacheViewResolver.class); - assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context).hasSingleBean(MustacheViewResolver.class); + assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); + }); } @Test @@ -81,32 +81,32 @@ class MustacheAutoConfigurationTests { assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); assertThat(context).doesNotHaveBean(MustacheViewResolver.class); assertThat(context) - .hasSingleBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + .hasSingleBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); }); } @Test void reactiveViewResolverCanBeDisabled() { configure(new ReactiveWebApplicationContextRunner()).withPropertyValues("spring.mustache.enabled=false") - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).doesNotHaveBean( - org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context) + .doesNotHaveBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + }); } @Test void registerCompilerForReactiveApp() { configure(new ReactiveWebApplicationContextRunner()).withUserConfiguration(CustomCompilerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - assertThat(context).doesNotHaveBean(MustacheViewResolver.class); - assertThat(context).hasSingleBean( - org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); - assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + assertThat(context).doesNotHaveBean(MustacheViewResolver.class); + assertThat(context) + .hasSingleBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + assertThat(context.getBean(Mustache.Compiler.class).standardsMode).isTrue(); + }); } @Test @@ -130,13 +130,13 @@ class MustacheAutoConfigurationTests { void defaultReactiveViewResolverConfiguration() { configure(new ReactiveWebApplicationContextRunner()).run((context) -> { org.springframework.boot.web.reactive.result.view.MustacheViewResolver viewResolver = context - .getBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); + .getBean(org.springframework.boot.web.reactive.result.view.MustacheViewResolver.class); assertThat(viewResolver).extracting("charset").isEqualTo("UTF-8"); assertThat(viewResolver).extracting("prefix").isEqualTo("classpath:/templates/"); assertThat(viewResolver).extracting("requestContextAttribute").isNull(); assertThat(viewResolver).extracting("suffix").isEqualTo(".mustache"); assertThat(viewResolver.getSupportedMediaTypes()) - .containsExactly(MediaType.parseMediaType("text/html;charset=UTF-8")); + .containsExactly(MediaType.parseMediaType("text/html;charset=UTF-8")); }); } @@ -211,9 +211,11 @@ class MustacheAutoConfigurationTests { private void assertViewResolverProperty(ViewResolverKind kind, String property, String field, Object expectedValue) { - kind.runner().withConfiguration(AutoConfigurations.of(MustacheAutoConfiguration.class)) - .withPropertyValues(property).run((context) -> assertThat(context.getBean(kind.viewResolverClass())) - .extracting(field).isEqualTo(expectedValue)); + kind.runner() + .withConfiguration(AutoConfigurations.of(MustacheAutoConfiguration.class)) + .withPropertyValues(property) + .run((context) -> assertThat(context.getBean(kind.viewResolverClass())).extracting(field) + .isEqualTo(expectedValue)); } private > T configure(T runner) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java index be2a47669e..09199b6a29 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheAutoConfigurationWithoutWebMvcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,10 +36,10 @@ class MustacheAutoConfigurationWithoutWebMvcTests { @Test void registerBeansForServletAppWithoutMvc() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(MustacheAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(Mustache.Compiler.class); - assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Mustache.Compiler.class); + assertThat(context).hasSingleBean(MustacheResourceTemplateLoader.class); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java index c4daba94a2..af49dbcbe9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mustache/MustacheStandaloneIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ class MustacheStandaloneIntegrationTests { @Test void directCompilation() { assertThat(this.compiler.compile("Hello: {{world}}").execute(Collections.singletonMap("world", "World"))) - .isEqualTo("Hello: World"); + .isEqualTo("Hello: World"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java index 074db2bce1..c8febbbe60 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,8 @@ class Neo4jAutoConfigurationIntegrationTests { @Container private static final Neo4jContainer neo4jServer = new Neo4jContainer<>(DockerImageNames.neo4j()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java index 65a456845a..3ab281052e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jAutoConfigurationTests.java @@ -54,13 +54,13 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; class Neo4jAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class)); @Test void driverNotConfiguredWithoutDriverApi() { this.contextRunner.withPropertyValues("spring.neo4j.uri=bolt://localhost:4711") - .withClassLoader(new FilteredClassLoader(Driver.class)) - .run((ctx) -> assertThat(ctx).doesNotHaveBean(Driver.class)); + .withClassLoader(new FilteredClassLoader(Driver.class)) + .run((ctx) -> assertThat(ctx).doesNotHaveBean(Driver.class)); } @Test @@ -71,8 +71,8 @@ class Neo4jAutoConfigurationTests { @Test void driverShouldInvokeConfigBuilderCustomizers() { this.contextRunner.withPropertyValues("spring.neo4j.uri=bolt://localhost:4711") - .withBean(ConfigBuilderCustomizer.class, () -> ConfigBuilder::withEncryption) - .run((ctx) -> assertThat(ctx.getBean(Driver.class).isEncrypted()).isTrue()); + .withBean(ConfigBuilderCustomizer.class, () -> ConfigBuilder::withEncryption) + .run((ctx) -> assertThat(ctx.getBean(Driver.class).isEncrypted()).isTrue()); } @ParameterizedTest @@ -98,8 +98,9 @@ class Neo4jAutoConfigurationTests { @ValueSource(strings = { "bolt+routing", "bolt+x", "neo4j+wth" }) void uriWithInvalidSchemesAreDetected(String invalidScheme) { this.contextRunner.withPropertyValues("spring.neo4j.uri=" + invalidScheme + "://localhost:4711") - .run((ctx) -> assertThat(ctx).hasFailed().getFailure() - .hasMessageContaining("'%s' is not a supported scheme.", invalidScheme)); + .run((ctx) -> assertThat(ctx).hasFailed() + .getFailure() + .hasMessageContaining("'%s' is not a supported scheme.", invalidScheme)); } @Test @@ -114,13 +115,13 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.setMaxTransactionRetryTime(Duration.ofSeconds(2)); assertThat(mapDriverConfig(properties)).extracting("retrySettings") - .hasFieldOrPropertyWithValue("maxRetryTimeMs", 2000L); + .hasFieldOrPropertyWithValue("maxRetryTimeMs", 2000L); } @Test void determineServerUriShouldDefaultToLocalhost() { assertThat(determineServerUri(new Neo4jProperties(), new MockEnvironment())) - .isEqualTo(URI.create("bolt://localhost:7687")); + .isEqualTo(URI.create("bolt://localhost:7687")); } @Test @@ -166,7 +167,7 @@ class Neo4jAutoConfigurationTests { authentication.setUsername("Farin"); authentication.setKerberosTicket("AABBCCDDEE"); assertThatIllegalStateException().isThrownBy(() -> mapAuthToken(authentication)) - .withMessage("Cannot specify both username ('Farin') and kerberos ticket ('AABBCCDDEE')"); + .withMessage("Cannot specify both username ('Farin') and kerberos ticket ('AABBCCDDEE')"); } @Test @@ -223,7 +224,7 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); assertThat(mapDriverConfig(properties).trustStrategy().strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); } @Test @@ -231,7 +232,7 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_ALL_CERTIFICATES); assertThat(mapDriverConfig(properties).trustStrategy().strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_ALL_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_ALL_CERTIFICATES); } @Test @@ -252,7 +253,7 @@ class Neo4jAutoConfigurationTests { properties.getSecurity().setCertFile(certFile); Config.TrustStrategy trustStrategy = mapDriverConfig(properties).trustStrategy(); assertThat(trustStrategy.strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES); assertThat(trustStrategy.certFiles()).containsOnly(certFile); } @@ -261,8 +262,9 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES); assertThatExceptionOfType(InvalidConfigurationPropertyValueException.class) - .isThrownBy(() -> mapDriverConfig(properties)).withMessage( - "Property spring.neo4j.security.trust-strategy with value 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' is invalid: Configured trust strategy requires a certificate file."); + .isThrownBy(() -> mapDriverConfig(properties)) + .withMessage( + "Property spring.neo4j.security.trust-strategy with value 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' is invalid: Configured trust strategy requires a certificate file."); } @Test @@ -270,7 +272,7 @@ class Neo4jAutoConfigurationTests { Neo4jProperties properties = new Neo4jProperties(); properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); assertThat(mapDriverConfig(properties).trustStrategy().strategy()) - .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); + .isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java index 07bdc12275..432f3637ca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/neo4j/Neo4jPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -52,9 +52,9 @@ class Neo4jPropertiesTests { Neo4jProperties properties = new Neo4jProperties(); assertThat(properties.getSecurity().isEncrypted()).isEqualTo(defaultConfig.encrypted()); assertThat(properties.getSecurity().getTrustStrategy().name()) - .isEqualTo(defaultConfig.trustStrategy().strategy().name()); + .isEqualTo(defaultConfig.trustStrategy().strategy().name()); assertThat(properties.getSecurity().isHostnameVerificationEnabled()) - .isEqualTo(defaultConfig.trustStrategy().isHostnameVerificationEnabled()); + .isEqualTo(defaultConfig.trustStrategy().isHostnameVerificationEnabled()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java index 821fd4cba9..92136193e7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/netty/NettyAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; class NettyAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(NettyAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(NettyAutoConfiguration.class)); @Test void leakDetectionShouldBeConfigured() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java index dbca9bc1d4..38909c284b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/AbstractJpaAutoConfigurationTests.java @@ -78,12 +78,11 @@ abstract class AbstractJpaAutoConfigurationTests { protected AbstractJpaAutoConfigurationTests(Class autoConfiguredClass) { this.autoConfiguredClass = autoConfiguredClass; this.contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true", - "spring.jta.log-dir=" - + new File(new BuildOutput(getClass()).getRootLocation(), "transaction-logs")) - .withUserConfiguration(TestConfiguration.class).withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, TransactionAutoConfiguration.class, - SqlInitializationAutoConfiguration.class, autoConfiguredClass)); + .withPropertyValues("spring.datasource.generate-unique-name=true", + "spring.jta.log-dir=" + new File(new BuildOutput(getClass()).getRootLocation(), "transaction-logs")) + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, SqlInitializationAutoConfiguration.class, autoConfiguredClass)); } protected ApplicationContextRunner contextRunner() { @@ -93,13 +92,14 @@ abstract class AbstractJpaAutoConfigurationTests { @Test void notConfiguredIfDataSourceIsNotAvailable() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) - .run(assertJpaIsNotAutoConfigured()); + .run(assertJpaIsNotAutoConfigured()); } @Test void notConfiguredIfNoSingleDataSourceCandidateIsAvailable() { new ApplicationContextRunner().withUserConfiguration(TestTwoDataSourcesConfiguration.class) - .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)).run(assertJpaIsNotAutoConfigured()); + .withConfiguration(AutoConfigurations.of(this.autoConfiguredClass)) + .run(assertJpaIsNotAutoConfigured()); } protected ContextConsumer assertJpaIsNotAutoConfigured() { @@ -134,93 +134,94 @@ abstract class AbstractJpaAutoConfigurationTests { @Test void jpaTransactionManagerTakesPrecedenceOverSimpleDataSourceOne() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).hasSingleBean(JpaTransactionManager.class); - assertThat(context).getBean("transactionManager").isInstanceOf(JpaTransactionManager.class); - }); + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + assertThat(context).hasSingleBean(JpaTransactionManager.class); + assertThat(context).getBean("transactionManager").isInstanceOf(JpaTransactionManager.class); + }); } @Test void openEntityManagerInViewInterceptorIsCreated() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).hasSingleBean(OpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).hasSingleBean(OpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterPresent() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestFilterConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestFilterConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorIsNotRegisteredWhenFilterRegistrationPresent() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestFilterRegistrationConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestFilterRegistrationConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorAutoConfigurationBacksOffWhenManuallyRegistered() { new WebApplicationContextRunner().withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestInterceptorManualConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).getBean(OpenEntityManagerInViewInterceptor.class) - .isExactlyInstanceOf( - TestInterceptorManualConfiguration.ManualOpenEntityManagerInViewInterceptor.class)); + .withUserConfiguration(TestInterceptorManualConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).getBean(OpenEntityManagerInViewInterceptor.class) + .isExactlyInstanceOf( + TestInterceptorManualConfiguration.ManualOpenEntityManagerInViewInterceptor.class)); } @Test void openEntityManagerInViewInterceptorIsNotRegisteredWhenExplicitlyOff() { new WebApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.jpa.open-in-view=false") - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - TransactionAutoConfiguration.class, this.autoConfiguredClass)) - .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true", "spring.jpa.open-in-view=false") + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + TransactionAutoConfiguration.class, this.autoConfiguredClass)) + .run((context) -> assertThat(context).doesNotHaveBean(OpenEntityManagerInViewInterceptor.class)); } @Test void customJpaProperties() { - this.contextRunner.withPropertyValues("spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", - "spring.jpa.properties.c:d").run((context) -> { - LocalContainerEntityManagerFactoryBean bean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - Map map = bean.getJpaPropertyMap(); - assertThat(map).containsEntry("a", "b"); - assertThat(map).containsEntry("c", "d"); - assertThat(map).containsEntry("a.b", "c"); - }); + this.contextRunner + .withPropertyValues("spring.jpa.properties.a:b", "spring.jpa.properties.a.b:c", "spring.jpa.properties.c:d") + .run((context) -> { + LocalContainerEntityManagerFactoryBean bean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + Map map = bean.getJpaPropertyMap(); + assertThat(map).containsEntry("a", "b"); + assertThat(map).containsEntry("c", "d"); + assertThat(map).containsEntry("a.b", "c"); + }); } @Test void usesManuallyDefinedLocalContainerEntityManagerFactoryBeanIfAvailable() { this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) - .run((context) -> { - LocalContainerEntityManagerFactoryBean factoryBean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - Map map = factoryBean.getJpaPropertyMap(); - assertThat(map).containsEntry("configured", "manually"); - }); + .run((context) -> { + LocalContainerEntityManagerFactoryBean factoryBean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + Map map = factoryBean.getJpaPropertyMap(); + assertThat(map).containsEntry("configured", "manually"); + }); } @Test void usesManuallyDefinedEntityManagerFactoryIfAvailable() { this.contextRunner.withUserConfiguration(TestConfigurationWithLocalContainerEntityManagerFactoryBean.class) - .run((context) -> { - EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); - Map map = factoryBean.getProperties(); - assertThat(map).containsEntry("configured", "manually"); - }); + .run((context) -> { + EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); + Map map = factoryBean.getProperties(); + assertThat(map).containsEntry("configured", "manually"); + }); } @Test @@ -244,36 +245,36 @@ abstract class AbstractJpaAutoConfigurationTests { @Test void customPersistenceManagedTypes() { this.contextRunner - .withBean(PersistenceManagedTypes.class, () -> PersistenceManagedTypes.of(Country.class.getName())) - .run((context) -> { - assertThat(context).hasSingleBean(PersistenceManagedTypes.class); - EntityManager entityManager = context.getBean(EntityManagerFactory.class).createEntityManager(); - assertThat(getManagedJavaTypes(entityManager)).contains(Country.class).doesNotContain(City.class); - }); + .withBean(PersistenceManagedTypes.class, () -> PersistenceManagedTypes.of(Country.class.getName())) + .run((context) -> { + assertThat(context).hasSingleBean(PersistenceManagedTypes.class); + EntityManager entityManager = context.getBean(EntityManagerFactory.class).createEntityManager(); + assertThat(getManagedJavaTypes(entityManager)).contains(Country.class).doesNotContain(City.class); + }); } @Test void customPersistenceUnitManager() { this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitManager.class) - .run((context) -> { - LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - assertThat(entityManagerFactoryBean).hasFieldOrPropertyWithValue("persistenceUnitManager", - context.getBean(PersistenceUnitManager.class)); - }); + .run((context) -> { + LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + assertThat(entityManagerFactoryBean).hasFieldOrPropertyWithValue("persistenceUnitManager", + context.getBean(PersistenceUnitManager.class)); + }); } @Test void customPersistenceUnitPostProcessors() { this.contextRunner.withUserConfiguration(TestConfigurationWithCustomPersistenceUnitPostProcessors.class) - .run((context) -> { - LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context - .getBean(LocalContainerEntityManagerFactoryBean.class); - PersistenceUnitInfo persistenceUnitInfo = entityManagerFactoryBean.getPersistenceUnitInfo(); - assertThat(persistenceUnitInfo).isNotNull(); - assertThat(persistenceUnitInfo.getManagedClassNames()) - .contains("customized.attribute.converter.class.name"); - }); + .run((context) -> { + LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = context + .getBean(LocalContainerEntityManagerFactoryBean.class); + PersistenceUnitInfo persistenceUnitInfo = entityManagerFactoryBean.getPersistenceUnitInfo(); + assertThat(persistenceUnitInfo).isNotNull(); + assertThat(persistenceUnitInfo.getManagedClassNames()) + .contains("customized.attribute.converter.class.name"); + }); } private Class[] getManagedJavaTypes(EntityManager entityManager) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java index 2b91165fe4..7d5fe8cdd7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/CustomHibernateJpaAutoConfigurationTests.java @@ -56,33 +56,37 @@ import static org.mockito.Mockito.mock; class CustomHibernateJpaAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") - .withUserConfiguration(TestConfiguration.class).withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .withUserConfiguration(TestConfiguration.class) + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)); @Test void namingStrategyDelegatorTakesPrecedence() { - this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" - + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator").run((context) -> { - JpaProperties jpaProperties = context.getBean(JpaProperties.class); - HibernateProperties hibernateProperties = context.getBean(HibernateProperties.class); - Map properties = hibernateProperties - .determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()); - assertThat(properties).doesNotContainKey("hibernate.ejb.naming_strategy"); - }); + this.contextRunner + .withPropertyValues("spring.jpa.properties.hibernate.ejb.naming_strategy_delegator:" + + "org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator") + .run((context) -> { + JpaProperties jpaProperties = context.getBean(JpaProperties.class); + HibernateProperties hibernateProperties = context.getBean(HibernateProperties.class); + Map properties = hibernateProperties + .determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()); + assertThat(properties).doesNotContainKey("hibernate.ejb.naming_strategy"); + }); } @Test void namingStrategyBeansAreUsed() { this.contextRunner.withUserConfiguration(NamingStrategyConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:h2:mem:naming-strategy-beans").run((context) -> { - HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); - Map hibernateProperties = jpaConfiguration.getVendorProperties(); - assertThat(hibernateProperties).containsEntry("hibernate.implicit_naming_strategy", - NamingStrategyConfiguration.implicitNamingStrategy); - assertThat(hibernateProperties).containsEntry("hibernate.physical_naming_strategy", - NamingStrategyConfiguration.physicalNamingStrategy); - }); + .withPropertyValues("spring.datasource.url:jdbc:h2:mem:naming-strategy-beans") + .run((context) -> { + HibernateJpaConfiguration jpaConfiguration = context.getBean(HibernateJpaConfiguration.class); + Map hibernateProperties = jpaConfiguration.getVendorProperties(); + assertThat(hibernateProperties).containsEntry("hibernate.implicit_naming_strategy", + NamingStrategyConfiguration.implicitNamingStrategy); + assertThat(hibernateProperties).containsEntry("hibernate.physical_naming_strategy", + NamingStrategyConfiguration.physicalNamingStrategy); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java index 51ec12e62f..f3b2ff2521 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/Hibernate2ndLevelCacheIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -36,21 +36,21 @@ import static org.assertj.core.api.Assertions.assertThat; class Hibernate2ndLevelCacheIntegrationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class)) - .withUserConfiguration(TestConfiguration.class); + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class, DataSourceAutoConfiguration.class, + HibernateJpaAutoConfiguration.class)) + .withUserConfiguration(TestConfiguration.class); @Test void hibernate2ndLevelCacheWithJCacheAndHazelcast() { String cachingProviderFqn = HazelcastServerCachingProvider.class.getName(); String configLocation = "classpath:hazelcast.xml"; this.contextRunner - .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, - "spring.cache.jcache.config=" + configLocation, - "spring.jpa.properties.hibernate.cache.region.factory_class=jcache", - "spring.jpa.properties.hibernate.cache.provider=" + cachingProviderFqn, - "spring.jpa.properties.hibernate.javax.cache.uri=" + configLocation) - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.cache.type=jcache", "spring.cache.jcache.provider=" + cachingProviderFqn, + "spring.cache.jcache.config=" + configLocation, + "spring.jpa.properties.hibernate.cache.region.factory_class=jcache", + "spring.jpa.properties.hibernate.cache.provider=" + cachingProviderFqn, + "spring.jpa.properties.hibernate.javax.cache.uri=" + configLocation) + .run((context) -> assertThat(context).hasNotFailed()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java index 0ad1ecb3ca..04fbda8350 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateDefaultDdlAutoProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,9 +40,9 @@ import static org.mockito.Mockito.mock; class HibernateDefaultDdlAutoProviderTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)) - .withPropertyValues("spring.sql.init.mode:never"); + .withConfiguration( + AutoConfigurations.of(DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class)) + .withPropertyValues("spring.sql.init.mode:never"); @Test void defaultDDlAutoForEmbedded() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java index c32afc3b80..7382ce3c80 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfigurationTests.java @@ -102,10 +102,11 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes void testDmlScriptWithMissingDdl() { contextRunner().withPropertyValues("spring.sql.init.data-locations:classpath:/city.sql", // Missing: - "spring.sql.init.schema-locations:classpath:/ddl.sql").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasMessageContaining("ddl.sql"); - }); + "spring.sql.init.schema-locations:classpath:/ddl.sql") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasMessageContaining("ddl.sql"); + }); } @Test @@ -121,35 +122,35 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void testDmlScriptRunsEarly() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) - .withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", - "spring.sql.init.data-locations:/city.sql", "spring.jpa.defer-datasource-initialization=true") - .run((context) -> assertThat(context.getBean(TestInitializedJpaConfiguration.class).called).isTrue()); + .withClassLoader(new HideDataScriptClassLoader()) + .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", + "spring.sql.init.data-locations:/city.sql", "spring.jpa.defer-datasource-initialization=true") + .run((context) -> assertThat(context.getBean(TestInitializedJpaConfiguration.class).called).isTrue()); } @Test void testFlywaySwitchOffDdlAuto() { contextRunner().withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void testFlywayPlusValidation() { contextRunner() - .withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city", - "spring.jpa.hibernate.ddl-auto:validate") - .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.sql.init.mode:never", "spring.flyway.locations:classpath:db/city", + "spring.jpa.hibernate.ddl-auto:validate") + .withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void testLiquibasePlusValidation() { contextRunner() - .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", - "spring.jpa.hibernate.ddl-auto:validate") - .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .run((context) -> assertThat(context).hasNotFailed()); + .withPropertyValues("spring.liquibase.changeLog:classpath:db/changelog/db.changelog-city.yaml", + "spring.jpa.hibernate.ddl-auto:validate") + .withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) + .run((context) -> assertThat(context).hasNotFailed()); } @Test @@ -161,16 +162,16 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void hibernateDialectIsSetWhenDatabaseIsSet() { contextRunner().withPropertyValues("spring.jpa.database=H2") - .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) - .contains(entry("hibernate.dialect", H2Dialect.class.getName())))); + .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) + .contains(entry("hibernate.dialect", H2Dialect.class.getName())))); } @Test void hibernateDialectIsSetWhenDatabasePlatformIsSet() { String databasePlatform = TestH2Dialect.class.getName(); contextRunner().withPropertyValues("spring.jpa.database-platform=" + databasePlatform) - .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) - .contains(entry("hibernate.dialect", databasePlatform)))); + .run(assertJpaVendorAdapter((adapter) -> assertThat(adapter.getJpaPropertyMap()) + .contains(entry("hibernate.dialect", databasePlatform)))); } private ContextConsumer assertJpaVendorAdapter( @@ -185,16 +186,16 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void jtaDefaultPlatform() { contextRunner().withUserConfiguration(JtaTransactionManagerConfiguration.class) - .run(assertJtaPlatform(SpringJtaPlatform.class)); + .run(assertJtaPlatform(SpringJtaPlatform.class)); } @Test void jtaCustomPlatform() { contextRunner() - .withPropertyValues( - "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()) - .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) - .run(assertJtaPlatform(TestJtaPlatform.class)); + .withPropertyValues( + "spring.jpa.properties.hibernate.transaction.jta.platform:" + TestJtaPlatform.class.getName()) + .withConfiguration(AutoConfigurations.of(JtaAutoConfiguration.class)) + .run(assertJtaPlatform(TestJtaPlatform.class)); } @Test @@ -205,100 +206,106 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes private ContextConsumer assertJtaPlatform(Class expectedType) { return (context) -> { SessionFactoryImpl sessionFactory = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getNativeEntityManagerFactory().unwrap(SessionFactoryImpl.class); + .getNativeEntityManagerFactory() + .unwrap(SessionFactoryImpl.class); assertThat(sessionFactory.getServiceRegistry().getService(JtaPlatform.class)).isInstanceOf(expectedType); }; } @Test void jtaCustomTransactionManagerUsingProperties() { - contextRunner().withPropertyValues("spring.transaction.default-timeout:30", - "spring.transaction.rollback-on-commit-failure:true").run((context) -> { - JpaTransactionManager transactionManager = context.getBean(JpaTransactionManager.class); - assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); - assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); - }); + contextRunner() + .withPropertyValues("spring.transaction.default-timeout:30", + "spring.transaction.rollback-on-commit-failure:true") + .run((context) -> { + JpaTransactionManager transactionManager = context.getBean(JpaTransactionManager.class); + assertThat(transactionManager.getDefaultTimeout()).isEqualTo(30); + assertThat(transactionManager.isRollbackOnCommitFailure()).isTrue(); + }); } @Test void autoConfigurationBacksOffWithSeveralDataSources() { contextRunner() - .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, - XADataSourceAutoConfiguration.class, JtaAutoConfiguration.class)) - .withUserConfiguration(TestTwoDataSourcesConfiguration.class).run((context) -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(EntityManagerFactory.class); - }); + .withConfiguration(AutoConfigurations.of(DataSourceTransactionManagerAutoConfiguration.class, + XADataSourceAutoConfiguration.class, JtaAutoConfiguration.class)) + .withUserConfiguration(TestTwoDataSourcesConfiguration.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(EntityManagerFactory.class); + }); } @Test void providerDisablesAutoCommitIsConfigured() { - contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:false").run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties) - .contains(entry("hibernate.connection.provider_disables_autocommit", "true")); - }); + contextRunner() + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:false") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).contains(entry("hibernate.connection.provider_disables_autocommit", "true")); + }); } @Test void providerDisablesAutoCommitIsNotConfiguredIfAutoCommitIsEnabled() { - contextRunner().withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:true").run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); - }); + contextRunner() + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:true") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); + }); } @Test void providerDisablesAutoCommitIsNotConfiguredIfPropertyIsSet() { contextRunner() - .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:false", - "spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false") - .run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties) - .contains(entry("hibernate.connection.provider_disables_autocommit", "false")); - }); + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:false", + "spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).contains(entry("hibernate.connection.provider_disables_autocommit", "false")); + }); } @Test void providerDisablesAutoCommitIsNotConfiguredWithJta() { contextRunner().withUserConfiguration(JtaTransactionManagerConfiguration.class) - .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), - "spring.datasource.hikari.auto-commit:false") - .run((context) -> { - Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) - .getJpaPropertyMap(); - assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); - }); + .withPropertyValues("spring.datasource.type:" + HikariDataSource.class.getName(), + "spring.datasource.hikari.auto-commit:false") + .run((context) -> { + Map jpaProperties = context.getBean(LocalContainerEntityManagerFactoryBean.class) + .getJpaPropertyMap(); + assertThat(jpaProperties).doesNotContainKeys("hibernate.connection.provider_disables_autocommit"); + }); } @Test void customResourceMapping() { contextRunner().withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.sql.init.data-locations:classpath:/db/non-annotated-data.sql", - "spring.jpa.mapping-resources=META-INF/mappings/non-annotated.xml", - "spring.jpa.defer-datasource-initialization=true") - .run((context) -> { - EntityManager em = context.getBean(EntityManagerFactory.class).createEntityManager(); - NonAnnotatedEntity found = em.find(NonAnnotatedEntity.class, 2000L); - assertThat(found).isNotNull(); - assertThat(found.getItem()).isEqualTo("Test"); - }); + .withPropertyValues("spring.sql.init.data-locations:classpath:/db/non-annotated-data.sql", + "spring.jpa.mapping-resources=META-INF/mappings/non-annotated.xml", + "spring.jpa.defer-datasource-initialization=true") + .run((context) -> { + EntityManager em = context.getBean(EntityManagerFactory.class).createEntityManager(); + NonAnnotatedEntity found = em.find(NonAnnotatedEntity.class, 2000L); + assertThat(found).isNotNull(); + assertThat(found.getItem()).isEqualTo("Test"); + }); } @Test void physicalNamingStrategyCanBeUsed() { contextRunner().withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class).run((context) -> { Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy"))); + .getVendorProperties(); + assertThat(hibernateProperties) + .contains(entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy"))); assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); }); } @@ -307,9 +314,9 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes void implicitNamingStrategyCanBeUsed() { contextRunner().withUserConfiguration(TestImplicitNamingStrategyConfiguration.class).run((context) -> { Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties).contains( - entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); + .getVendorProperties(); + assertThat(hibernateProperties) + .contains(entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); }); } @@ -317,57 +324,57 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void namingStrategyInstancesTakePrecedenceOverNamingStrategyProperties() { contextRunner() - .withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class, - TestImplicitNamingStrategyConfiguration.class) - .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", - "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") - .run((context) -> { - Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy")), - entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - }); + .withUserConfiguration(TestPhysicalNamingStrategyConfiguration.class, + TestImplicitNamingStrategyConfiguration.class) + .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", + "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") + .run((context) -> { + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) + .getVendorProperties(); + assertThat(hibernateProperties).contains( + entry("hibernate.physical_naming_strategy", context.getBean("testPhysicalNamingStrategy")), + entry("hibernate.implicit_naming_strategy", context.getBean("testImplicitNamingStrategy"))); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + }); } @Test void hibernatePropertiesCustomizerTakesPrecedenceOverStrategyInstancesAndNamingStrategyProperties() { contextRunner() - .withUserConfiguration(TestHibernatePropertiesCustomizerConfiguration.class, - TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) - .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", - "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") - .run((context) -> { - Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) - .getVendorProperties(); - TestHibernatePropertiesCustomizerConfiguration configuration = context - .getBean(TestHibernatePropertiesCustomizerConfiguration.class); - assertThat(hibernateProperties).contains( - entry("hibernate.physical_naming_strategy", configuration.physicalNamingStrategy), - entry("hibernate.implicit_naming_strategy", configuration.implicitNamingStrategy)); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - }); + .withUserConfiguration(TestHibernatePropertiesCustomizerConfiguration.class, + TestPhysicalNamingStrategyConfiguration.class, TestImplicitNamingStrategyConfiguration.class) + .withPropertyValues("spring.jpa.hibernate.naming.physical-strategy:com.example.Physical", + "spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit") + .run((context) -> { + Map hibernateProperties = context.getBean(HibernateJpaConfiguration.class) + .getVendorProperties(); + TestHibernatePropertiesCustomizerConfiguration configuration = context + .getBean(TestHibernatePropertiesCustomizerConfiguration.class); + assertThat(hibernateProperties).contains( + entry("hibernate.physical_naming_strategy", configuration.physicalNamingStrategy), + entry("hibernate.implicit_naming_strategy", configuration.implicitNamingStrategy)); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + }); } @Test void eventListenerCanBeRegisteredAsBeans() { contextRunner().withUserConfiguration(TestInitializedJpaConfiguration.class) - .withClassLoader(new HideDataScriptClassLoader()) - .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", - "spring.sql.init.data-locations:classpath:/city.sql", - "spring.jpa.defer-datasource-initialization=true") - .run((context) -> { - // See CityListener - assertThat(context).hasSingleBean(City.class); - assertThat(context.getBean(City.class).getName()).isEqualTo("Washington"); - }); + .withClassLoader(new HideDataScriptClassLoader()) + .withPropertyValues("spring.jpa.show-sql=true", "spring.jpa.hibernate.ddl-auto:create-drop", + "spring.sql.init.data-locations:classpath:/city.sql", + "spring.jpa.defer-datasource-initialization=true") + .run((context) -> { + // See CityListener + assertThat(context).hasSingleBean(City.class); + assertThat(context.getBean(City.class).getName()).isEqualTo("Washington"); + }); } @Test void hibernatePropertiesCustomizerCanDisableBeanContainer() { contextRunner().withUserConfiguration(DisableBeanContainerConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(City.class)); + .run((context) -> assertThat(context).doesNotHaveBean(City.class)); } @Test @@ -381,57 +388,55 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void vendorPropertiesWhenDdlAutoPropertyIsSet() { contextRunner().withPropertyValues("spring.jpa.hibernate.ddl-auto=update") - .run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION); - assertThat(vendorProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, "update"); - })); + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION); + assertThat(vendorProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, "update"); + })); } @Test void vendorPropertiesWhenDdlAutoPropertyAndHibernatePropertiesAreSet() { contextRunner() - .withPropertyValues("spring.jpa.hibernate.ddl-auto=update", - "spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop") - .run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION); - assertThat(vendorProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, "create-drop"); - })); + .withPropertyValues("spring.jpa.hibernate.ddl-auto=update", + "spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop") + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION); + assertThat(vendorProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, "create-drop"); + })); } @Test void vendorPropertiesWhenDdlAutoPropertyIsSetToNone() { contextRunner().withPropertyValues("spring.jpa.hibernate.ddl-auto=none") - .run(vendorProperties((vendorProperties) -> assertThat(vendorProperties).doesNotContainKeys( - AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, AvailableSettings.HBM2DDL_AUTO))); + .run(vendorProperties((vendorProperties) -> assertThat(vendorProperties).doesNotContainKeys( + AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, AvailableSettings.HBM2DDL_AUTO))); } @Test void vendorPropertiesWhenJpaDdlActionIsSet() { contextRunner() - .withPropertyValues( - "spring.jpa.properties.jakarta.persistence.schema-generation.database.action=create") - .run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties).containsEntry(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, - "create"); - assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_AUTO); - })); + .withPropertyValues("spring.jpa.properties.jakarta.persistence.schema-generation.database.action=create") + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties).containsEntry(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, "create"); + assertThat(vendorProperties).doesNotContainKeys(AvailableSettings.HBM2DDL_AUTO); + })); } @Test void vendorPropertiesWhenBothDdlAutoPropertiesAreSet() { - contextRunner().withPropertyValues( - "spring.jpa.properties.jakarta.persistence.schema-generation.database.action=create", - "spring.jpa.hibernate.ddl-auto=create-only").run(vendorProperties((vendorProperties) -> { - assertThat(vendorProperties).containsEntry(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, - "create"); - assertThat(vendorProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, "create-only"); - })); + contextRunner() + .withPropertyValues("spring.jpa.properties.jakarta.persistence.schema-generation.database.action=create", + "spring.jpa.hibernate.ddl-auto=create-only") + .run(vendorProperties((vendorProperties) -> { + assertThat(vendorProperties).containsEntry(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, "create"); + assertThat(vendorProperties).containsEntry(AvailableSettings.HBM2DDL_AUTO, "create-only"); + })); } private ContextConsumer vendorProperties( Consumer> vendorProperties) { return (context) -> vendorProperties - .accept(context.getBean(HibernateJpaConfiguration.class).getVendorProperties()); + .accept(context.getBean(HibernateJpaConfiguration.class).getVendorProperties()); } @Test @@ -446,29 +451,30 @@ class HibernateJpaAutoConfigurationTests extends AbstractJpaAutoConfigurationTes @Test void withAsyncBootstrappingAnApplicationListenerThatUsesJpaDoesNotTriggerABeanCurrentlyInCreationException() { - contextRunner().withUserConfiguration(AsyncBootstrappingConfiguration.class, - JpaUsingApplicationListenerConfiguration.class).run((context) -> { - assertThat(context).hasNotFailed(); - EventCapturingApplicationListener listener = context - .getBean(EventCapturingApplicationListener.class); - assertThat(listener.events).hasSize(1); - assertThat(listener.events).hasOnlyElementsOfType(ContextRefreshedEvent.class); - // createEntityManager requires Hibernate bootstrapping to be complete - assertThatNoException() - .isThrownBy(() -> context.getBean(EntityManagerFactory.class).createEntityManager()); - }); + contextRunner() + .withUserConfiguration(AsyncBootstrappingConfiguration.class, + JpaUsingApplicationListenerConfiguration.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + EventCapturingApplicationListener listener = context.getBean(EventCapturingApplicationListener.class); + assertThat(listener.events).hasSize(1); + assertThat(listener.events).hasOnlyElementsOfType(ContextRefreshedEvent.class); + // createEntityManager requires Hibernate bootstrapping to be complete + assertThatNoException() + .isThrownBy(() -> context.getBean(EntityManagerFactory.class).createEntityManager()); + }); } @Test void whenLocalContainerEntityManagerFactoryBeanHasNoJpaVendorAdapterAutoConfigurationSucceeds() { contextRunner() - .withUserConfiguration( - TestConfigurationWithLocalContainerEntityManagerFactoryBeanWithNoJpaVendorAdapter.class) - .run((context) -> { - EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); - Map map = factoryBean.getProperties(); - assertThat(map).containsEntry("configured", "manually"); - }); + .withUserConfiguration( + TestConfigurationWithLocalContainerEntityManagerFactoryBeanWithNoJpaVendorAdapter.class) + .run((context) -> { + EntityManagerFactory factoryBean = context.getBean(EntityManagerFactory.class); + Map map = factoryBean.getProperties(); + assertThat(map).containsEntry("configured", "manually"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java index 9114188f18..1e67d73cac 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/orm/jpa/HibernatePropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ import static org.mockito.Mockito.never; class HibernatePropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class); + .withUserConfiguration(TestConfiguration.class); @Mock private Supplier ddlAutoSupplier; @@ -69,67 +69,67 @@ class HibernatePropertiesTests { @Test void hibernate5CustomNamingStrategies() { this.contextRunner - .withPropertyValues("spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", - "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical") - .run(assertHibernateProperties((hibernateProperties) -> { - assertThat(hibernateProperties).contains( - entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), - entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - })); + .withPropertyValues("spring.jpa.hibernate.naming.implicit-strategy:com.example.Implicit", + "spring.jpa.hibernate.naming.physical-strategy:com.example.Physical") + .run(assertHibernateProperties((hibernateProperties) -> { + assertThat(hibernateProperties).contains( + entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), + entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + })); } @Test void hibernate5CustomNamingStrategiesViaJpaProperties() { this.contextRunner - .withPropertyValues("spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", - "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical") - .run(assertHibernateProperties((hibernateProperties) -> { - // You can override them as we don't provide any default - assertThat(hibernateProperties).contains( - entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), - entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); - assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); - })); + .withPropertyValues("spring.jpa.properties.hibernate.implicit_naming_strategy:com.example.Implicit", + "spring.jpa.properties.hibernate.physical_naming_strategy:com.example.Physical") + .run(assertHibernateProperties((hibernateProperties) -> { + // You can override them as we don't provide any default + assertThat(hibernateProperties).contains( + entry(AvailableSettings.IMPLICIT_NAMING_STRATEGY, "com.example.Implicit"), + entry(AvailableSettings.PHYSICAL_NAMING_STRATEGY, "com.example.Physical")); + assertThat(hibernateProperties).doesNotContainKeys("hibernate.ejb.naming_strategy"); + })); } @Test void scannerUsesDisabledScannerByDefault() { this.contextRunner.run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) - .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner"))); + .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.DisabledScanner"))); } @Test void scannerCanBeCustomized() { this.contextRunner.withPropertyValues( "spring.jpa.properties.hibernate.archive.scanner:org.hibernate.boot.archive.scan.internal.StandardScanner") - .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties).containsEntry( - AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.StandardScanner"))); + .run(assertHibernateProperties((hibernateProperties) -> assertThat(hibernateProperties) + .containsEntry(AvailableSettings.SCANNER, "org.hibernate.boot.archive.scan.internal.StandardScanner"))); } @Test void defaultDdlAutoIsNotInvokedIfPropertyIsSet() { this.contextRunner.withPropertyValues("spring.jpa.hibernate.ddl-auto=validate") - .run(assertDefaultDdlAutoNotInvoked("validate")); + .run(assertDefaultDdlAutoNotInvoked("validate")); } @Test void defaultDdlAutoIsNotInvokedIfHibernateSpecificPropertyIsSet() { this.contextRunner.withPropertyValues("spring.jpa.properties.hibernate.hbm2ddl.auto=create") - .run(assertDefaultDdlAutoNotInvoked("create")); + .run(assertDefaultDdlAutoNotInvoked("create")); } @Test void defaultDdlAutoIsNotInvokedAndDdlAutoIsNotSetIfJpaDbActionPropertyIsSet() { this.contextRunner - .withPropertyValues( - "spring.jpa.properties.jakarta.persistence.schema-generation.database.action=drop-and-create") - .run(assertHibernateProperties((hibernateProperties) -> { - assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.HBM2DDL_AUTO); - assertThat(hibernateProperties).containsEntry(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, - "drop-and-create"); - then(this.ddlAutoSupplier).should(never()).get(); - })); + .withPropertyValues( + "spring.jpa.properties.jakarta.persistence.schema-generation.database.action=drop-and-create") + .run(assertHibernateProperties((hibernateProperties) -> { + assertThat(hibernateProperties).doesNotContainKey(AvailableSettings.HBM2DDL_AUTO); + assertThat(hibernateProperties).containsEntry(AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, + "drop-and-create"); + then(this.ddlAutoSupplier).should(never()).get(); + })); } private ContextConsumer assertDefaultDdlAutoNotInvoked(String expectedDdlAuto) { @@ -145,8 +145,8 @@ class HibernatePropertiesTests { assertThat(context).hasSingleBean(JpaProperties.class); assertThat(context).hasSingleBean(HibernateProperties.class); Map hibernateProperties = context.getBean(HibernateProperties.class) - .determineHibernateProperties(context.getBean(JpaProperties.class).getProperties(), - new HibernateSettings().ddlAuto(this.ddlAutoSupplier)); + .determineHibernateProperties(context.getBean(JpaProperties.class).getProperties(), + new HibernateSettings().ddlAuto(this.ddlAutoSupplier)); consumer.accept(hibernateProperties); }; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java index 82867eda98..23aabcf577 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzAutoConfigurationTests.java @@ -86,8 +86,8 @@ import static org.mockito.Mockito.mock; class QuartzAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withPropertyValues("spring.datasource.generate-unique-name=true") - .withConfiguration(AutoConfigurations.of(QuartzAutoConfiguration.class)); + .withPropertyValues("spring.datasource.generate-unique-name=true") + .withConfiguration(AutoConfigurations.of(QuartzAutoConfiguration.class)); @Test void withNoDataSource() { @@ -100,97 +100,105 @@ class QuartzAutoConfigurationTests { @Test void withDataSourceUseMemoryByDefault() { - this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)).run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(RAMJobStore.class); - }); + this.contextRunner + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(RAMJobStore.class); + }); } @Test void withDataSource() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); } @Test void withDataSourceAndInMemoryStoreDoesNotInitializeDataSource() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=memory").run((context) -> { - JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean("dataSource", DataSource.class)); - assertThat(jdbcTemplate.queryForList("SHOW TABLES").stream() - .map((table) -> (String) table.get("TABLE_NAME"))) - .noneMatch((name) -> name.startsWith("QRTZ")); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=memory") + .run((context) -> { + JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean("dataSource", DataSource.class)); + assertThat(jdbcTemplate.queryForList("SHOW TABLES") + .stream() + .map((table) -> (String) table.get("TABLE_NAME"))).noneMatch((name) -> name.startsWith("QRTZ")); + }); } @Test void withDataSourceNoTransactionManager() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("dataSource")); } @Test void dataSourceWithQuartzDataSourceQualifierUsedWhenMultiplePresent() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class, MultipleDataSourceConfiguration.class) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("quartzDataSource")); + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run(assertDataSourceInitializedByDataSourceDatabaseScriptInitializer("quartzDataSource")); } @Test void transactionManagerWithQuartzTransactionManagerUsedWhenMultiplePresent() { this.contextRunner - .withUserConfiguration(QuartzJobsConfiguration.class, MultipleTransactionManagersConfiguration.class) - .withPropertyValues("spring.quartz.job-store-type=jdbc").run((context) -> { - SchedulerFactoryBean schedulerFactoryBean = context.getBean(SchedulerFactoryBean.class); - assertThat(schedulerFactoryBean).extracting("transactionManager") - .isEqualTo(context.getBean("quartzTransactionManager")); - }); + .withUserConfiguration(QuartzJobsConfiguration.class, MultipleTransactionManagersConfiguration.class) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run((context) -> { + SchedulerFactoryBean schedulerFactoryBean = context.getBean(SchedulerFactoryBean.class); + assertThat(schedulerFactoryBean).extracting("transactionManager") + .isEqualTo(context.getBean("quartzTransactionManager")); + }); } @Test void withTaskExecutor() { this.contextRunner.withUserConfiguration(MockExecutorConfiguration.class) - .withPropertyValues("spring.quartz.properties.org.quartz.threadPool.threadCount=50").run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getMetaData().getThreadPoolSize()).isEqualTo(50); - Executor executor = context.getBean(Executor.class); - then(executor).shouldHaveNoInteractions(); - }); + .withPropertyValues("spring.quartz.properties.org.quartz.threadPool.threadCount=50") + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getMetaData().getThreadPoolSize()).isEqualTo(50); + Executor executor = context.getBean(Executor.class); + then(executor).shouldHaveNoInteractions(); + }); } @Test void withOverwriteExistingJobs() { this.contextRunner.withUserConfiguration(OverwriteTriggerConfiguration.class) - .withPropertyValues("spring.quartz.overwrite-existing-jobs=true").run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - Trigger fooTrigger = scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger")); - assertThat(fooTrigger).isNotNull(); - assertThat(((SimpleTrigger) fooTrigger).getRepeatInterval()).isEqualTo(30000); - }); + .withPropertyValues("spring.quartz.overwrite-existing-jobs=true") + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + Trigger fooTrigger = scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger")); + assertThat(fooTrigger).isNotNull(); + assertThat(((SimpleTrigger) fooTrigger).getRepeatInterval()).isEqualTo(30000); + }); } @Test void withConfiguredJobAndTrigger(CapturedOutput output) { this.contextRunner.withUserConfiguration(QuartzFullConfiguration.class) - .withPropertyValues("test-name=withConfiguredJobAndTrigger").run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))).isNotNull(); - assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))).isNotNull(); - Awaitility.waitAtMost(Duration.ofSeconds(5)).untilAsserted( + .withPropertyValues("test-name=withConfiguredJobAndTrigger") + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getJobDetail(JobKey.jobKey("fooJob"))).isNotNull(); + assertThat(scheduler.getTrigger(TriggerKey.triggerKey("fooTrigger"))).isNotNull(); + Awaitility.waitAtMost(Duration.ofSeconds(5)) + .untilAsserted( () -> assertThat(output).contains("withConfiguredJobAndTrigger").contains("jobDataValue")); - }); + }); } @Test @@ -206,11 +214,11 @@ class QuartzAutoConfigurationTests { @Test void withQuartzProperties() { this.contextRunner.withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceId=FOO") - .run((context) -> { - assertThat(context).hasSingleBean(Scheduler.class); - Scheduler scheduler = context.getBean(Scheduler.class); - assertThat(scheduler.getSchedulerInstanceId()).isEqualTo("FOO"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(Scheduler.class); + Scheduler scheduler = context.getBean(Scheduler.class); + assertThat(scheduler.getSchedulerInstanceId()).isEqualTo("FOO"); + }); } @Test @@ -242,27 +250,29 @@ class QuartzAutoConfigurationTests { @Test void withCustomConfiguration() { - this.contextRunner.withPropertyValues("spring.quartz.auto-startup=false", "spring.quartz.startup-delay=1m", - "spring.quartz.wait-for-jobs-to-complete-on-shutdown=true", - "spring.quartz.overwrite-existing-jobs=true").run((context) -> { - assertThat(context).hasSingleBean(SchedulerFactoryBean.class); - SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); - assertThat(schedulerFactory.isAutoStartup()).isFalse(); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue("startupDelay", 60); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue("waitForJobsToCompleteOnShutdown", true); - assertThat(schedulerFactory).hasFieldOrPropertyWithValue("overwriteExistingJobs", true); - }); + this.contextRunner + .withPropertyValues("spring.quartz.auto-startup=false", "spring.quartz.startup-delay=1m", + "spring.quartz.wait-for-jobs-to-complete-on-shutdown=true", + "spring.quartz.overwrite-existing-jobs=true") + .run((context) -> { + assertThat(context).hasSingleBean(SchedulerFactoryBean.class); + SchedulerFactoryBean schedulerFactory = context.getBean(SchedulerFactoryBean.class); + assertThat(schedulerFactory.isAutoStartup()).isFalse(); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("startupDelay", 60); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("waitForJobsToCompleteOnShutdown", true); + assertThat(schedulerFactory).hasFieldOrPropertyWithValue("overwriteExistingJobs", true); + }); } @Test void withLiquibase() { this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", - "spring.liquibase.change-log=classpath:org/quartz/impl/jdbcjobstore/liquibase.quartz.init.xml") - .run(assertDataSourceInitialized("dataSource").andThen((context) -> assertThat(context) - .doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, LiquibaseAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", + "spring.liquibase.change-log=classpath:org/quartz/impl/jdbcjobstore/liquibase.quartz.init.xml") + .run(assertDataSourceInitialized("dataSource").andThen( + (context) -> assertThat(context).doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); } @Test @@ -272,34 +282,33 @@ class QuartzAutoConfigurationTests { Files.copy(stream, flywayLocation.resolve("V2__quartz.sql")); } this.contextRunner.withUserConfiguration(QuartzJobsConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, FlywayAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", - "spring.flyway.locations=filesystem:" + flywayLocation, - "spring.flyway.baseline-on-migrate=true") - .run(assertDataSourceInitialized("dataSource").andThen((context) -> assertThat(context) - .doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, FlywayAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc", "spring.quartz.jdbc.initialize-schema=never", + "spring.flyway.locations=filesystem:" + flywayLocation, "spring.flyway.baseline-on-migrate=true") + .run(assertDataSourceInitialized("dataSource").andThen( + (context) -> assertThat(context).doesNotHaveBean(QuartzDataSourceScriptDatabaseInitializer.class))); } @Test void schedulerNameWithDedicatedProperty() { this.contextRunner.withPropertyValues("spring.quartz.scheduler-name=testScheduler") - .run(assertSchedulerName("testScheduler")); + .run(assertSchedulerName("testScheduler")); } @Test void schedulerNameWithQuartzProperty() { this.contextRunner - .withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") - .run(assertSchedulerName("testScheduler")); + .withPropertyValues("spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") + .run(assertSchedulerName("testScheduler")); } @Test void schedulerNameWithDedicatedPropertyTakesPrecedence() { this.contextRunner - .withPropertyValues("spring.quartz.scheduler-name=specificTestScheduler", - "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") - .run(assertSchedulerName("specificTestScheduler")); + .withPropertyValues("spring.quartz.scheduler-name=specificTestScheduler", + "spring.quartz.properties.org.quartz.scheduler.instanceName=testScheduler") + .run(assertSchedulerName("specificTestScheduler")); } @Test @@ -310,20 +319,22 @@ class QuartzAutoConfigurationTests { @Test void whenTheUserDefinesTheirOwnQuartzDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomQuartzDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc") - .run((context) -> assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("quartzDataSourceScriptDatabaseInitializer").hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run((context) -> assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("quartzDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredQuartzInitializerRemains() { this.contextRunner.withUserConfiguration(CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withPropertyValues("spring.quartz.job-store-type=jdbc").run((context) -> assertThat(context) - .hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class).hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withPropertyValues("spring.quartz.job-store-type=jdbc") + .run((context) -> assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } private ContextConsumer assertDataSourceInitialized(String dataSourceName) { @@ -333,9 +344,9 @@ class QuartzAutoConfigurationTests { assertThat(scheduler.getMetaData().getJobStoreClass()).isAssignableFrom(LocalDataSourceJobStore.class); JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getBean(dataSourceName, DataSource.class)); assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM QRTZ_JOB_DETAILS", Integer.class)) - .isEqualTo(2); + .isEqualTo(2); assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM QRTZ_SIMPLE_TRIGGERS", Integer.class)) - .isZero(); + .isZero(); }; } @@ -344,7 +355,7 @@ class QuartzAutoConfigurationTests { return assertDataSourceInitialized(dataSourceName).andThen((context) -> { assertThat(context).hasSingleBean(QuartzDataSourceScriptDatabaseInitializer.class); QuartzDataSourceScriptDatabaseInitializer initializer = context - .getBean(QuartzDataSourceScriptDatabaseInitializer.class); + .getBean(QuartzDataSourceScriptDatabaseInitializer.class); assertThat(initializer).hasFieldOrPropertyWithValue("dataSource", context.getBean(dataSourceName)); }); } @@ -383,17 +394,25 @@ class QuartzAutoConfigurationTests { @Bean JobDetail fooJob() { - return JobBuilder.newJob().ofType(FooJob.class).withIdentity("fooJob") - .usingJobData("jobDataKey", "jobDataValue").storeDurably().build(); + return JobBuilder.newJob() + .ofType(FooJob.class) + .withIdentity("fooJob") + .usingJobData("jobDataKey", "jobDataValue") + .storeDurably() + .build(); } @Bean Trigger fooTrigger(JobDetail jobDetail) { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10) - .repeatForever(); - - return TriggerBuilder.newTrigger().forJob(jobDetail).withIdentity("fooTrigger") - .withSchedule(scheduleBuilder).build(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(10) + .repeatForever(); + + return TriggerBuilder.newTrigger() + .forJob(jobDetail) + .withIdentity("fooTrigger") + .withSchedule(scheduleBuilder) + .build(); } } @@ -404,11 +423,15 @@ class QuartzAutoConfigurationTests { @Bean Trigger anotherFooTrigger(JobDetail fooJob) { - SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(30) - .repeatForever(); - - return TriggerBuilder.newTrigger().forJob(fooJob).withIdentity("fooTrigger").withSchedule(scheduleBuilder) - .build(); + SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() + .withIntervalInSeconds(30) + .repeatForever(); + + return TriggerBuilder.newTrigger() + .forJob(fooJob) + .withIdentity("fooTrigger") + .withSchedule(scheduleBuilder) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java index c1408c97f5..6ed299543d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/quartz/QuartzDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class QuartzDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = QuartzDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/quartz/impl/jdbcjobstore/tables_test.sql"); + .containsOnly("classpath:org/quartz/impl/jdbcjobstore/tables_test.sql"); then(dataSource).shouldHaveNoInteractions(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java index 8407735a94..4b45915fc4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/NoConnectionFactoryBeanFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -41,20 +41,20 @@ class NoConnectionFactoryBeanFailureAnalyzerTests { void analyzeWhenNoSuchBeanDefinitionExceptionForDifferentTypeShouldReturnNull() { assertThat( new NoConnectionFactoryBeanFailureAnalyzer().analyze(new NoSuchBeanDefinitionException(String.class))) - .isNull(); + .isNull(); } @Test void analyzeWhenNoSuchBeanDefinitionExceptionButProviderIsAvailableShouldReturnNull() { assertThat(new NoConnectionFactoryBeanFailureAnalyzer() - .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNull(); + .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNull(); } @Test void analyzeWhenNoSuchBeanDefinitionExceptionAndNoProviderShouldAnalyze() { assertThat(new NoConnectionFactoryBeanFailureAnalyzer( new FilteredClassLoader(("META-INF/services/" + ConnectionFactoryProvider.class.getName())::equals)) - .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNotNull(); + .analyze(new NoSuchBeanDefinitionException(ConnectionFactory.class))).isNotNull(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java index b26b3d4fb7..ee564a8954 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,173 +58,191 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); @Test void configureWithUrlCreateConnectionPoolByDefault() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - assertThat(context.getBean(ConnectionPool.class)).extracting(ConnectionPool::unwrap) - .satisfies((connectionFactory) -> assertThat(connectionFactory) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(H2ConnectionFactory.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + assertThat(context.getBean(ConnectionPool.class)).extracting(ConnectionPool::unwrap) + .satisfies((connectionFactory) -> assertThat(connectionFactory) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class)); + }); } @Test void configureWithUrlAndPoolPropertiesApplyProperties() { - this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName(), - "spring.r2dbc.pool.max-size=15", "spring.r2dbc.pool.max-acquire-time=3m").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class) - .hasSingleBean(R2dbcProperties.class); - ConnectionPool connectionPool = context.getBean(ConnectionPool.class); - PoolMetrics poolMetrics = connectionPool.getMetrics().get(); - assertThat(poolMetrics.getMaxAllocatedSize()).isEqualTo(15); - assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMinutes(3)); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName(), + "spring.r2dbc.pool.max-size=15", "spring.r2dbc.pool.max-acquire-time=3m") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class) + .hasSingleBean(R2dbcProperties.class); + ConnectionPool connectionPool = context.getBean(ConnectionPool.class); + PoolMetrics poolMetrics = connectionPool.getMetrics().get(); + assertThat(poolMetrics.getMaxAllocatedSize()).isEqualTo(15); + assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMinutes(3)); + }); } @Test void configureWithUrlAndDefaultDoNotOverrideDefaultTimeouts() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class) - .hasSingleBean(R2dbcProperties.class); - ConnectionPool connectionPool = context.getBean(ConnectionPool.class); - assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMillis(-1)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class) + .hasSingleBean(R2dbcProperties.class); + ConnectionPool connectionPool = context.getBean(ConnectionPool.class); + assertThat(connectionPool).hasFieldOrPropertyWithValue("maxAcquireTime", Duration.ofMillis(-1)); + }); } @Test void configureWithUrlPoolAndPoolPropertiesFails() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", - "spring.r2dbc.pool.max-size=15") - .run((context) -> assertThat(context).getFailure().rootCause() - .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", + "spring.r2dbc.pool.max-size=15") + .run((context) -> assertThat(context).getFailure() + .rootCause() + .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); } @Test void configureWithUrlPoolAndPropertyBasedPoolingDisabledFails() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", - "spring.r2dbc.pool.enabled=false") - .run((context) -> assertThat(context).getFailure().rootCause() - .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12", + "spring.r2dbc.pool.enabled=false") + .run((context) -> assertThat(context).getFailure() + .rootCause() + .isInstanceOf(MultipleConnectionPoolConfigurationsException.class)); } @Test void configureWithUrlPoolAndNoPoolPropertiesCreatesPool() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12") - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - ConnectionPool connectionPool = context.getBean(ConnectionPool.class); - assertThat(connectionPool.getMetrics().get().getMaxAllocatedSize()).isEqualTo(12); - }); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + "?maxSize=12") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + ConnectionPool connectionPool = context.getBean(ConnectionPool.class); + assertThat(connectionPool.getMetrics().get().getMaxAllocatedSize()).isEqualTo(12); + }); } @Test void configureWithPoolEnabledCreateConnectionPool() { this.contextRunner - .withPropertyValues("spring.r2dbc.pool.enabled=true", - "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ConnectionPool.class)); + .withPropertyValues("spring.r2dbc.pool.enabled=true", + "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class)); } @Test void configureWithPoolDisabledCreateGenericConnectionFactory() { - this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:h2:mem:///" - + randomDatabaseName() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); - assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(H2ConnectionFactory.class); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.pool.enabled=false", + "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); + assertThat(context.getBean(ConnectionFactory.class)) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class); + }); } @Test void configureWithoutPoolInvokeOptionCustomizer() { this.contextRunner - .withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://host/database") - .withUserConfiguration(CustomizerConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); - ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions) - .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) - .isEqualTo(Boolean.TRUE)); - }); + .withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://host/database") + .withUserConfiguration(CustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); + ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) + .isEqualTo(Boolean.TRUE)); + }); } @Test void configureWithPoolInvokeOptionCustomizer() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:simple://host/database") - .withUserConfiguration(CustomizerConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - ConnectionFactory pool = context.getBean(ConnectionFactory.class); - ConnectionFactory connectionFactory = ((ConnectionPool) pool).unwrap(); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions) - .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) - .isEqualTo(Boolean.TRUE)); - }); + .withUserConfiguration(CustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + ConnectionFactory pool = context.getBean(ConnectionFactory.class); + ConnectionFactory connectionFactory = ((ConnectionPool) pool).unwrap(); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> assertThat(options.getRequiredValue(Option.valueOf("customized"))) + .isEqualTo(Boolean.TRUE)); + }); } @Test void configureWithInvalidUrlThrowsAppropriateException() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:not-going-to-work") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); + .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class)); } @Test void configureWithoutSpringJdbcCreateConnectionFactory() { this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://foo") - .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")).run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(SimpleTestConnectionFactory.class); - }); + .withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context.getBean(ConnectionFactory.class)) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(SimpleTestConnectionFactory.class); + }); } @Test void configureWithoutPoolShouldApplyAdditionalProperties() { - this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://foo", - "spring.r2dbc.properties.test=value", "spring.r2dbc.properties.another=2").run((context) -> { - ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions).satisfies((options) -> { - assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); - assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); - }); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.pool.enabled=false", "spring.r2dbc.url:r2dbc:simple://foo", + "spring.r2dbc.properties.test=value", "spring.r2dbc.properties.another=2") + .run((context) -> { + ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> { + assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); + assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); + }); + }); } @Test void configureWithPoolShouldApplyAdditionalProperties() { - this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:simple://foo", - "spring.r2dbc.properties.test=value", "spring.r2dbc.properties.another=2").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); - ConnectionFactory connectionFactory = context.getBean(ConnectionPool.class).unwrap(); - assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(OptionsCapableConnectionFactory::getOptions).satisfies((options) -> { - assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); - assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); - }); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.url:r2dbc:simple://foo", "spring.r2dbc.properties.test=value", + "spring.r2dbc.properties.another=2") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(ConnectionPool.class); + ConnectionFactory connectionFactory = context.getBean(ConnectionPool.class).unwrap(); + assertThat(connectionFactory).asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(OptionsCapableConnectionFactory::getOptions) + .satisfies((options) -> { + assertThat(options.getRequiredValue(Option.valueOf("test"))).isEqualTo("value"); + assertThat(options.getRequiredValue(Option.valueOf("another"))).isEqualTo("2"); + }); + }); } @Test void configureWithoutUrlShouldCreateEmbeddedConnectionPoolByDefault() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ConnectionPool.class)); + .hasSingleBean(ConnectionPool.class)); } @Test @@ -232,58 +250,60 @@ class R2dbcAutoConfigurationTests { this.contextRunner.withPropertyValues("spring.r2dbc.pool.enabled=false").run((context) -> { assertThat(context).hasSingleBean(ConnectionFactory.class).doesNotHaveBean(ConnectionPool.class); assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap).isExactlyInstanceOf(H2ConnectionFactory.class); + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class); }); } @Test void configureWithoutUrlAndSprigJdbcCreateEmbeddedConnectionFactory() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.jdbc")) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(ConnectionPool.class)); + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(ConnectionPool.class)); } @Test void configureWithoutUrlAndEmbeddedCandidateFails() { this.contextRunner.withClassLoader(new DisableEmbeddedDatabaseClassLoader()).run((context) -> { assertThat(context).hasFailed(); - assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Failed to determine a suitable R2DBC Connection URL"); + assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to determine a suitable R2DBC Connection URL"); }); } @Test void configureWithoutUrlAndNoConnectionFactoryProviderBacksOff() { this.contextRunner - .withClassLoader(new FilteredClassLoader( - ("META-INF/services/" + ConnectionFactoryProvider.class.getName())::equals)) - .run((context) -> assertThat(context).doesNotHaveBean(R2dbcAutoConfiguration.class)); + .withClassLoader( + new FilteredClassLoader(("META-INF/services/" + ConnectionFactoryProvider.class.getName())::equals)) + .run((context) -> assertThat(context).doesNotHaveBean(R2dbcAutoConfiguration.class)); } @Test void configureWithDataSourceAutoConfigurationDoesNotCreateDataSource() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .doesNotHaveBean(DataSource.class)); + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .doesNotHaveBean(DataSource.class)); } @Test void databaseClientIsConfigured() { this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(DatabaseClient.class); - assertThat(context.getBean(DatabaseClient.class).getConnectionFactory()) - .isSameAs(context.getBean(ConnectionFactory.class)); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class).hasSingleBean(DatabaseClient.class); + assertThat(context.getBean(DatabaseClient.class).getConnectionFactory()) + .isSameAs(context.getBean(ConnectionFactory.class)); + }); } @Test void databaseClientBacksOffIfSpringR2dbcIsNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.r2dbc")) - .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .doesNotHaveBean(DatabaseClient.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName()) + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .doesNotHaveBean(DatabaseClient.class)); } private InstanceOfAssertFactory> type(Class type) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java index 5508ad03f0..fbdf230bc6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcAutoConfigurationWithoutConnectionPoolTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,37 +43,41 @@ import static org.assertj.core.api.Assertions.assertThat; class R2dbcAutoConfigurationWithoutConnectionPoolTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)); @Test void configureWithoutR2dbcPoolCreateGenericConnectionFactory() { - this.contextRunner.withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE").run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context.getBean(ConnectionFactory.class)) - .asInstanceOf(type(OptionsCapableConnectionFactory.class)) - .extracting(Wrapped::unwrap) - .isExactlyInstanceOf(H2ConnectionFactory.class); - }); + this.contextRunner + .withPropertyValues("spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context.getBean(ConnectionFactory.class)) + .asInstanceOf(type(OptionsCapableConnectionFactory.class)) + .extracting(Wrapped::unwrap) + .isExactlyInstanceOf(H2ConnectionFactory.class); + }); } @Test void configureWithoutR2dbcPoolAndPoolEnabledShouldFail() { this.contextRunner - .withPropertyValues("spring.r2dbc.pool.enabled=true", - "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .run((context) -> assertThat(context).getFailure().rootCause() - .isInstanceOf(MissingR2dbcPoolDependencyException.class)); + .withPropertyValues("spring.r2dbc.pool.enabled=true", + "spring.r2dbc.url:r2dbc:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> assertThat(context).getFailure() + .rootCause() + .isInstanceOf(MissingR2dbcPoolDependencyException.class)); } @Test void configureWithoutR2dbcPoolAndPoolUrlShouldFail() { this.contextRunner - .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() - + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .run((context) -> assertThat(context).getFailure().rootCause() - .isInstanceOf(MissingR2dbcPoolDependencyException.class)); + .withPropertyValues("spring.r2dbc.url:r2dbc:pool:h2:mem:///" + randomDatabaseName() + + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .run((context) -> assertThat(context).getFailure() + .rootCause() + .isInstanceOf(MissingR2dbcPoolDependencyException.class)); } private InstanceOfAssertFactory> type(Class type) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java index 1453a58a2d..f7fdfcf1f0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/r2dbc/R2dbcTransactionManagerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,17 +58,17 @@ class R2dbcTransactionManagerAutoConfigurationTests { @Test void singleTransactionManager() { this.contextRunner.withUserConfiguration(SingleConnectionFactoryConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(TransactionalOperator.class) - .hasSingleBean(ReactiveTransactionManager.class)); + .run((context) -> assertThat(context).hasSingleBean(TransactionalOperator.class) + .hasSingleBean(ReactiveTransactionManager.class)); } @Test void transactionManagerEnabled() { this.contextRunner.withUserConfiguration(SingleConnectionFactoryConfiguration.class, BaseConfiguration.class) - .run((context) -> { - TransactionalService bean = context.getBean(TransactionalService.class); - bean.isTransactionActive().as(StepVerifier::create).expectNext(true).verifyComplete(); - }); + .run((context) -> { + TransactionalService bean = context.getBean(TransactionalService.class); + bean.isTransactionActive().as(StepVerifier::create).expectNext(true).verifyComplete(); + }); } @Configuration(proxyBeanMethods = false) @@ -110,7 +110,7 @@ class R2dbcTransactionManagerAutoConfigurationTests { @Override public Mono isTransactionActive() { return TransactionSynchronizationManager.forCurrentTransaction() - .map(TransactionSynchronizationManager::isActualTransactionActive); + .map(TransactionSynchronizationManager::isActualTransactionActive); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java index cfdc4e05de..73642c5883 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/reactor/ReactorAutoConfigurationTests.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ReactorAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactorAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactorAutoConfiguration.class)); private static final String THREADLOCAL_KEY = "ReactorAutoConfigurationTests"; @@ -53,8 +53,10 @@ class ReactorAutoConfigurationTests { void shouldConfigureAutomaticContextPropagation() { AtomicReference threadLocalValue = new AtomicReference<>(); this.contextRunner.run((applicationContext) -> { - Mono.just("test").doOnNext((element) -> threadLocalValue.set(THREADLOCAL_VALUE.get())) - .contextWrite(Context.of(THREADLOCAL_KEY, "success")).block(); + Mono.just("test") + .doOnNext((element) -> threadLocalValue.set(THREADLOCAL_VALUE.get())) + .contextWrite(Context.of(THREADLOCAL_KEY, "success")) + .block(); assertThat(threadLocalValue.get()).isEqualTo("success"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java index aee5e0f705..5040842595 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketMessagingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat; class RSocketMessagingAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) - .withUserConfiguration(BaseConfiguration.class); + .withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) + .withUserConfiguration(BaseConfiguration.class); @Test void shouldCreateDefaultBeans() { @@ -50,17 +50,18 @@ class RSocketMessagingAutoConfigurationTests { @Test void shouldFailOnMissingStrategies() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(RSocketMessagingAutoConfiguration.class)) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure().getMessage()).contains("No qualifying bean of type " - + "'org.springframework.messaging.rsocket.RSocketStrategies' available"); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure().getMessage()).contains("No qualifying bean of type " + + "'org.springframework.messaging.rsocket.RSocketStrategies' available"); + }); } @Test void shouldUseCustomSocketAcceptor() { - this.contextRunner.withUserConfiguration(CustomMessageHandler.class).run((context) -> assertThat(context) - .getBeanNames(RSocketMessageHandler.class).containsOnly("customMessageHandler")); + this.contextRunner.withUserConfiguration(CustomMessageHandler.class) + .run((context) -> assertThat(context).getBeanNames(RSocketMessageHandler.class) + .containsOnly("customMessageHandler")); } @Test @@ -76,8 +77,10 @@ class RSocketMessagingAutoConfigurationTests { @Bean RSocketStrategies rSocketStrategies() { - return RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.allMimeTypes()).build(); + return RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.allMimeTypes()) + .build(); } } @@ -88,8 +91,10 @@ class RSocketMessagingAutoConfigurationTests { @Bean RSocketMessageHandler customMessageHandler() { RSocketMessageHandler messageHandler = new RSocketMessageHandler(); - RSocketStrategies strategies = RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.allMimeTypes()).build(); + RSocketStrategies strategies = RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.allMimeTypes()) + .build(); messageHandler.setRSocketStrategies(strategies); return messageHandler; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java index 46971f1e49..d675d51286 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketRequesterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -68,12 +68,13 @@ class RSocketRequesterAutoConfigurationTests { RSocketConnectorConfigurer first = mock(RSocketConnectorConfigurer.class); RSocketConnectorConfigurer second = mock(RSocketConnectorConfigurer.class); this.contextRunner.withBean("first", RSocketConnectorConfigurer.class, () -> first) - .withBean("second", RSocketConnectorConfigurer.class, () -> second).run((context) -> { - assertThat(context).getBeans(RSocketConnectorConfigurer.class).hasSize(2); - RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); - assertThat(builder).extracting("rsocketConnectorConfigurers", as(InstanceOfAssertFactories.LIST)) - .containsExactly(first, second); - }); + .withBean("second", RSocketConnectorConfigurer.class, () -> second) + .run((context) -> { + assertThat(context).getBeans(RSocketConnectorConfigurer.class).hasSize(2); + RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); + assertThat(builder).extracting("rsocketConnectorConfigurers", as(InstanceOfAssertFactories.LIST)) + .containsExactly(first, second); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java index 91bbe8a37d..ace10a95e7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -50,114 +50,121 @@ class RSocketServerAutoConfigurationTests { @Test void shouldNotCreateBeansByDefault() { contextRunner().run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); + .doesNotHaveBean(RSocketServerFactory.class) + .doesNotHaveBean(RSocketServerBootstrap.class)); } @Test void shouldNotCreateDefaultBeansForReactiveWebAppWithoutMapping() { reactiveWebContextRunner() - .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); + .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) + .doesNotHaveBean(RSocketServerFactory.class) + .doesNotHaveBean(RSocketServerBootstrap.class)); } @Test void shouldNotCreateDefaultBeansForReactiveWebAppWithWrongTransport() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.transport=tcp", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) - .doesNotHaveBean(RSocketServerFactory.class).doesNotHaveBean(RSocketServerBootstrap.class)); + .withPropertyValues("spring.rsocket.server.transport=tcp", "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> assertThat(context).doesNotHaveBean(WebServerFactoryCustomizer.class) + .doesNotHaveBean(RSocketServerFactory.class) + .doesNotHaveBean(RSocketServerBootstrap.class)); } @Test void shouldCreateDefaultBeansForReactiveWebApp() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context).hasSingleBean(RSocketWebSocketNettyRouteProvider.class)); + .withPropertyValues("spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> assertThat(context).hasSingleBean(RSocketWebSocketNettyRouteProvider.class)); } @Test void shouldCreateDefaultBeansForRSocketServerWhenPortIsSet() { reactiveWebContextRunner().withPropertyValues("spring.rsocket.server.port=0") - .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) - .hasSingleBean(RSocketServerBootstrap.class).hasSingleBean(RSocketServerCustomizer.class)); + .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) + .hasSingleBean(RSocketServerBootstrap.class) + .hasSingleBean(RSocketServerCustomizer.class)); } @Test void shouldSetLocalServerPortWhenRSocketServerPortIsSet() { reactiveWebContextRunner().withPropertyValues("spring.rsocket.server.port=0") - .withInitializer(new RSocketPortInfoApplicationContextInitializer()).run((context) -> { - assertThat(context).hasSingleBean(RSocketServerFactory.class) - .hasSingleBean(RSocketServerBootstrap.class).hasSingleBean(RSocketServerCustomizer.class); - assertThat(context.getEnvironment().getProperty("local.rsocket.server.port")).isNotNull(); - }); + .withInitializer(new RSocketPortInfoApplicationContextInitializer()) + .run((context) -> { + assertThat(context).hasSingleBean(RSocketServerFactory.class) + .hasSingleBean(RSocketServerBootstrap.class) + .hasSingleBean(RSocketServerCustomizer.class); + assertThat(context.getEnvironment().getProperty("local.rsocket.server.port")).isNotNull(); + }); } @Test void shouldSetFragmentWhenRSocketServerFragmentSizeIsSet() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=12KB") - .run((context) -> { - assertThat(context).hasSingleBean(RSocketServerFactory.class); - RSocketServerFactory factory = context.getBean(RSocketServerFactory.class); - assertThat(factory).hasFieldOrPropertyWithValue("fragmentSize", DataSize.ofKilobytes(12)); - }); + .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=12KB") + .run((context) -> { + assertThat(context).hasSingleBean(RSocketServerFactory.class); + RSocketServerFactory factory = context.getBean(RSocketServerFactory.class); + assertThat(factory).hasFieldOrPropertyWithValue("fragmentSize", DataSize.ofKilobytes(12)); + }); } @Test void shouldFailToSetFragmentWhenRSocketServerFragmentSizeIsBelow64() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=60B") - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessageContaining("The smallest allowed mtu size is 64 bytes, provided: 60"); - }); + .withPropertyValues("spring.rsocket.server.port=0", "spring.rsocket.server.fragment-size=60B") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasMessageContaining("The smallest allowed mtu size is 64 bytes, provided: 60"); + }); } @Test void shouldUseSslWhenRocketServerSslIsConfigured() { reactiveWebContextRunner() - .withPropertyValues("spring.rsocket.server.ssl.keyStore=classpath:rsocket/test.jks", - "spring.rsocket.server.ssl.keyPassword=password", "spring.rsocket.server.port=0") - .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) - .hasSingleBean(RSocketServerBootstrap.class).hasSingleBean(RSocketServerCustomizer.class) - .getBean(RSocketServerFactory.class) - .hasFieldOrPropertyWithValue("ssl.keyStore", "classpath:rsocket/test.jks") - .hasFieldOrPropertyWithValue("ssl.keyPassword", "password")); + .withPropertyValues("spring.rsocket.server.ssl.keyStore=classpath:rsocket/test.jks", + "spring.rsocket.server.ssl.keyPassword=password", "spring.rsocket.server.port=0") + .run((context) -> assertThat(context).hasSingleBean(RSocketServerFactory.class) + .hasSingleBean(RSocketServerBootstrap.class) + .hasSingleBean(RSocketServerCustomizer.class) + .getBean(RSocketServerFactory.class) + .hasFieldOrPropertyWithValue("ssl.keyStore", "classpath:rsocket/test.jks") + .hasFieldOrPropertyWithValue("ssl.keyPassword", "password")); } @Test void shouldUseCustomServerBootstrap() { - contextRunner().withUserConfiguration(CustomServerBootstrapConfig.class).run((context) -> assertThat(context) - .getBeanNames(RSocketServerBootstrap.class).containsExactly("customServerBootstrap")); + contextRunner().withUserConfiguration(CustomServerBootstrapConfig.class) + .run((context) -> assertThat(context).getBeanNames(RSocketServerBootstrap.class) + .containsExactly("customServerBootstrap")); } @Test void shouldUseCustomNettyRouteProvider() { reactiveWebContextRunner().withUserConfiguration(CustomNettyRouteProviderConfig.class) - .withPropertyValues("spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> assertThat(context).getBeanNames(RSocketWebSocketNettyRouteProvider.class) - .containsExactly("customNettyRouteProvider")); + .withPropertyValues("spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> assertThat(context).getBeanNames(RSocketWebSocketNettyRouteProvider.class) + .containsExactly("customNettyRouteProvider")); } @Test void whenSpringWebIsNotPresentThenEmbeddedServerConfigurationBacksOff() { contextRunner().withClassLoader(new FilteredClassLoader(ReactorResourceFactory.class)) - .withPropertyValues("spring.rsocket.server.port=0") - .run((context) -> assertThat(context).doesNotHaveBean(RSocketServerFactory.class)); + .withPropertyValues("spring.rsocket.server.port=0") + .run((context) -> assertThat(context).doesNotHaveBean(RSocketServerFactory.class)); } private ApplicationContextRunner contextRunner() { return new ApplicationContextRunner().withUserConfiguration(BaseConfiguration.class) - .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); } private ReactiveWebApplicationContextRunner reactiveWebContextRunner() { return new ReactiveWebApplicationContextRunner().withUserConfiguration(BaseConfiguration.class) - .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RSocketServerAutoConfiguration.class)); } @Configuration(proxyBeanMethods = false) @@ -166,8 +173,10 @@ class RSocketServerAutoConfigurationTests { @Bean RSocketMessageHandler messageHandler() { RSocketMessageHandler messageHandler = new RSocketMessageHandler(); - messageHandler.setRSocketStrategies(RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.allMimeTypes()).build()); + messageHandler.setRSocketStrategies(RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.allMimeTypes()) + .build()); return messageHandler; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java index 3973470510..e2cb73b1a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketStrategiesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -54,9 +54,9 @@ class RSocketStrategiesAutoConfigurationTests { assertThat(context).getBeans(RSocketStrategies.class).hasSize(1); RSocketStrategies strategies = context.getBean(RSocketStrategies.class); assertThat(strategies.decoders()).hasAtLeastOneElementOfType(Jackson2CborDecoder.class) - .hasAtLeastOneElementOfType(Jackson2JsonDecoder.class); + .hasAtLeastOneElementOfType(Jackson2JsonDecoder.class); assertThat(strategies.encoders()).hasAtLeastOneElementOfType(Jackson2CborEncoder.class) - .hasAtLeastOneElementOfType(Jackson2JsonEncoder.class); + .hasAtLeastOneElementOfType(Jackson2JsonEncoder.class); assertThat(strategies.routeMatcher()).isInstanceOf(PathPatternRouteMatcher.class); }); } @@ -84,8 +84,10 @@ class RSocketStrategiesAutoConfigurationTests { @Bean RSocketStrategies customRSocketStrategies() { - return RSocketStrategies.builder().encoder(CharSequenceEncoder.textPlainOnly()) - .decoder(StringDecoder.textPlainOnly()).build(); + return RSocketStrategies.builder() + .encoder(CharSequenceEncoder.textPlainOnly()) + .decoder(StringDecoder.textPlainOnly()) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java index e5272b4ef3..a16517fe97 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/rsocket/RSocketWebSocketNettyRouteProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -56,38 +56,40 @@ class RSocketWebSocketNettyRouteProviderTests { @Test void webEndpointsShouldWork() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration( - AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, - RSocketStrategiesAutoConfiguration.class, RSocketServerAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketRequesterAutoConfiguration.class)) - .withUserConfiguration(WebConfiguration.class) - .withPropertyValues("spring.rsocket.server.transport=websocket", - "spring.rsocket.server.mapping-path=/rsocket") - .run((context) -> { - ReactiveWebServerApplicationContext serverContext = (ReactiveWebServerApplicationContext) context - .getSourceApplicationContext(); - RSocketRequester requester = createRSocketRequester(context, serverContext.getWebServer()); - TestProtocol rsocketResponse = requester.route("websocket").data(new TestProtocol("rsocket")) - .retrieveMono(TestProtocol.class).block(Duration.ofSeconds(3)); - assertThat(rsocketResponse.getName()).isEqualTo("rsocket"); - WebTestClient client = createWebTestClient(serverContext.getWebServer()); - client.get().uri("/protocol").exchange().expectStatus().isOk().expectBody().jsonPath("name", - "http"); - }); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, + ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + JacksonAutoConfiguration.class, CodecsAutoConfiguration.class, + RSocketStrategiesAutoConfiguration.class, RSocketServerAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketRequesterAutoConfiguration.class)) + .withUserConfiguration(WebConfiguration.class) + .withPropertyValues("spring.rsocket.server.transport=websocket", + "spring.rsocket.server.mapping-path=/rsocket") + .run((context) -> { + ReactiveWebServerApplicationContext serverContext = (ReactiveWebServerApplicationContext) context + .getSourceApplicationContext(); + RSocketRequester requester = createRSocketRequester(context, serverContext.getWebServer()); + TestProtocol rsocketResponse = requester.route("websocket") + .data(new TestProtocol("rsocket")) + .retrieveMono(TestProtocol.class) + .block(Duration.ofSeconds(3)); + assertThat(rsocketResponse.getName()).isEqualTo("rsocket"); + WebTestClient client = createWebTestClient(serverContext.getWebServer()); + client.get().uri("/protocol").exchange().expectStatus().isOk().expectBody().jsonPath("name", "http"); + }); } private WebTestClient createWebTestClient(WebServer server) { - return WebTestClient.bindToServer().baseUrl("http://localhost:" + server.getPort()) - .responseTimeout(Duration.ofMinutes(5)).build(); + return WebTestClient.bindToServer() + .baseUrl("http://localhost:" + server.getPort()) + .responseTimeout(Duration.ofMinutes(5)) + .build(); } private RSocketRequester createRSocketRequester(ApplicationContext context, WebServer server) { int port = server.getPort(); RSocketRequester.Builder builder = context.getBean(RSocketRequester.Builder.class); return builder.dataMimeType(MediaType.APPLICATION_CBOR) - .websocket(URI.create("ws://localhost:" + port + "/rsocket")); + .websocket(URI.create("ws://localhost:" + port + "/rsocket")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java index ec888e0c6e..cb629a67b9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { properties.getRegistration().put("registration", registration); properties.getProvider().put("provider", provider); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://example.com/auth"); @@ -79,16 +79,16 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); assertThat(userInfoEndpoint.getUri()).isEqualTo("https://example.com/info"); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.FORM); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.FORM); assertThat(userInfoEndpoint.getUserNameAttributeName()).isEqualTo("sub"); assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://example.com/jwk"); assertThat(adapted.getRegistrationId()).isEqualTo("registration"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("https://example.com/redirect"); assertThat(adapted.getScopes()).containsExactly("user"); assertThat(adapted.getClientName()).isEqualTo("clientName"); @@ -103,7 +103,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setClientSecret("clientSecret"); properties.getRegistration().put("registration", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); @@ -116,9 +116,9 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); @@ -131,7 +131,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setClientName("clientName"); properties.getRegistration().put("registration", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("registration"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); @@ -140,15 +140,15 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { assertThat(userInfoEndpoint.getUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); assertThat(userInfoEndpoint.getUserNameAttributeName()).isEqualTo(IdTokenClaimNames.SUB); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); assertThat(adapted.getRegistrationId()).isEqualTo("registration"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_POST); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("https://example.com/redirect"); assertThat(adapted.getScopes()).containsExactly("user"); assertThat(adapted.getClientName()).isEqualTo("clientName"); @@ -161,8 +161,8 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setProvider("missing"); properties.getRegistration().put("registration", registration); assertThatIllegalStateException() - .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) - .withMessageContaining("Unknown provider ID 'missing'"); + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) + .withMessageContaining("Unknown provider ID 'missing'"); } @Test @@ -173,7 +173,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { registration.setClientSecret("clientSecret"); properties.getRegistration().put("google", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("google"); ProviderDetails adaptedProvider = adapted.getProviderDetails(); assertThat(adaptedProvider.getAuthorizationUri()).isEqualTo("https://accounts.google.com/o/oauth2/v2/auth"); @@ -181,15 +181,15 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { UserInfoEndpoint userInfoEndpoint = adaptedProvider.getUserInfoEndpoint(); assertThat(userInfoEndpoint.getUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/userinfo"); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); assertThat(adaptedProvider.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs"); assertThat(adapted.getRegistrationId()).isEqualTo("google"); assertThat(adapted.getClientId()).isEqualTo("clientId"); assertThat(adapted.getClientSecret()).isEqualTo("clientSecret"); assertThat(adapted.getClientAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); + .isEqualTo(org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC); assertThat(adapted.getAuthorizationGrantType()) - .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); + .isEqualTo(org.springframework.security.oauth2.core.AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(adapted.getRedirectUri()).isEqualTo("{baseUrl}/{action}/oauth2/code/{registrationId}"); assertThat(adapted.getScopes()).containsExactly("openid", "profile", "email"); assertThat(adapted.getClientName()).isEqualTo("Google"); @@ -201,8 +201,8 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { OAuth2ClientProperties.Registration registration = new OAuth2ClientProperties.Registration(); properties.getRegistration().put("missing", registration); assertThatIllegalStateException() - .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) - .withMessageContaining("Provider ID must be specified for client registration 'missing'"); + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties)) + .withMessageContaining("Provider ID must be specified for client registration 'missing'"); } @Test @@ -251,7 +251,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { properties.getProvider().put("okta-oidc", provider); properties.getRegistration().put("okta", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("okta"); ProviderDetails providerDetails = adapted.getProviderDetails(); assertThat(adapted.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_POST); @@ -302,7 +302,7 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { properties.getProvider().put(providerId, provider); properties.getRegistration().put("okta", registration); Map registrations = OAuth2ClientPropertiesRegistrationAdapter - .getClientRegistrations(properties); + .getClientRegistrations(properties); ClientRegistration adapted = registrations.get("okta"); ProviderDetails providerDetails = adapted.getProviderDetails(); assertThat(adapted.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC); @@ -316,14 +316,14 @@ class OAuth2ClientPropertiesRegistrationAdapterTests { UserInfoEndpoint userInfoEndpoint = providerDetails.getUserInfoEndpoint(); assertThat(userInfoEndpoint.getUri()).isEqualTo("https://example.com/oauth2/v3/userinfo"); assertThat(userInfoEndpoint.getAuthenticationMethod()) - .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); + .isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER); assertThat(this.server.getRequestCount()).isEqualTo(numberOfRequests); } private void setupMockResponse(String issuer) throws JsonProcessingException { MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) - .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java index 7629395b6a..fd04c1b14f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class OAuth2ClientPropertiesTests { registration.setProvider("google"); this.properties.getRegistration().put("foo", registration); assertThatIllegalStateException().isThrownBy(this.properties::validate) - .withMessageContaining("Client id must not be empty."); + .withMessageContaining("Client id must not be empty."); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java index 684d46f06c..270ac7029a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/reactive/ReactiveOAuth2ClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -63,16 +63,16 @@ import static org.assertj.core.api.Assertions.assertThat; class ReactiveOAuth2ClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class, - ReactiveSecurityAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class, + ReactiveSecurityAutoConfiguration.class)); private static final String REGISTRATION_PREFIX = "spring.security.oauth2.client.registration"; @Test void autoConfigurationShouldBackOffForServletEnvironments() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); } @Test @@ -83,16 +83,15 @@ class ReactiveOAuth2ClientAutoConfigurationTests { @Test void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner - .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") - .run((context) -> { - ReactiveClientRegistrationRepository repository = context - .getBean(ReactiveClientRegistrationRepository.class); - ClientRegistration registration = repository.findByRegistrationId("foo") - .block(Duration.ofSeconds(30)); - assertThat(registration).isNotNull(); - assertThat(registration.getClientSecret()).isEqualTo("secret"); - }); + .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> { + ReactiveClientRegistrationRepository repository = context + .getBean(ReactiveClientRegistrationRepository.class); + ClientRegistration registration = repository.findByRegistrationId("foo").block(Duration.ofSeconds(30)); + assertThat(registration).isNotNull(); + assertThat(registration.getClientSecret()).isEqualTo("secret"); + }); } @Test @@ -114,50 +113,50 @@ class ReactiveOAuth2ClientAutoConfigurationTests { @Test void authorizedClientServiceBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveOAuth2AuthorizedClientService.class); - assertThat(context).hasBean("testAuthorizedClientService"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveOAuth2AuthorizedClientService.class); + assertThat(context).hasBean("testAuthorizedClientService"); + }); } @Test void authorizedClientRepositoryBeanIsConditionalOnAuthorizedClientService() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ServerOAuth2AuthorizedClientRepository.class)); } @Test void configurationRegistersAuthorizedClientRepositoryBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class) - .run((context) -> assertThat(context) - .hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class)); + .run((context) -> assertThat(context) + .hasSingleBean(AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.class)); } @Test void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); - assertThat(context).hasBean("testAuthorizedClientRepository"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class); + assertThat(context).hasBean("testAuthorizedClientRepository"); + }); } @Test void securityWebFilterChainBeanConditionalOnWebApplication() { this.contextRunner.withUserConfiguration(ReactiveOAuth2AuthorizedClientRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(SecurityWebFilterChain.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SecurityWebFilterChain.class)); } @Test void configurationRegistersSecurityWebFilterChainBean() { // gh-17949 new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) - .withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class, - ServerHttpSecurityConfiguration.class) - .run((context) -> { - assertThat(hasFilter(context, OAuth2LoginAuthenticationWebFilter.class)).isTrue(); - assertThat(hasFilter(context, OAuth2AuthorizationCodeGrantWebFilter.class)).isTrue(); - }); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ClientAutoConfiguration.class)) + .withUserConfiguration(ReactiveOAuth2AuthorizedClientServiceConfiguration.class, + ServerHttpSecurityConfiguration.class) + .run((context) -> { + assertThat(hasFilter(context, OAuth2LoginAuthenticationWebFilter.class)).isTrue(); + assertThat(hasFilter(context, OAuth2AuthorizationCodeGrantWebFilter.class)).isTrue(); + }); } @Test @@ -178,15 +177,15 @@ class ReactiveOAuth2ClientAutoConfigurationTests { private void assertWhenClassNotPresent(Class classToFilter) { FilteredClassLoader classLoader = new FilteredClassLoader(classToFilter); this.contextRunner.withClassLoader(classLoader) - .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); + .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOAuth2ClientAutoConfiguration.class)); } @SuppressWarnings("unchecked") private boolean hasFilter(AssertableReactiveWebApplicationContext context, Class filter) { SecurityWebFilterChain filterChain = (SecurityWebFilterChain) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); List filters = (List) ReflectionTestUtils.getField(filterChain, "filters"); return filters.stream().anyMatch(filter::isInstance); } @@ -204,13 +203,18 @@ class ReactiveOAuth2ClientAutoConfigurationTests { private ClientRegistration getClientRegistration(String id, String userInfoUri) { ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(id); - builder.clientName("foo").clientId("foo") - .clientAuthenticationMethod( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).scope("read") - .clientSecret("secret").redirectUri("https://redirect-uri.com") - .authorizationUri("https://authorization-uri.com").tokenUri("https://token-uri.com") - .userInfoUri(userInfoUri).userNameAttributeName("login"); + builder.clientName("foo") + .clientId("foo") + .clientAuthenticationMethod( + org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .scope("read") + .clientSecret("secret") + .redirectUri("https://redirect-uri.com") + .authorizationUri("https://authorization-uri.com") + .tokenUri("https://token-uri.com") + .userInfoUri(userInfoUri) + .userNameAttributeName("login"); return builder.build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java index ddaf275d2c..ba567dbc58 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -38,20 +38,20 @@ class OAuth2ClientRegistrationRepositoryConfigurationTests { @Test void clientRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(ClientRegistrationRepository.class)); } @Test void clientRegistrationRepositoryBeanShouldBeCreatedWhenPropertiesPresent() { this.contextRunner.withUserConfiguration(OAuth2ClientRegistrationRepositoryConfiguration.class) - .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", - REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") - .run((context) -> { - ClientRegistrationRepository repository = context.getBean(ClientRegistrationRepository.class); - ClientRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration).isNotNull(); - assertThat(registration.getClientSecret()).isEqualTo("secret"); - }); + .withPropertyValues(REGISTRATION_PREFIX + ".foo.client-id=abcd", + REGISTRATION_PREFIX + ".foo.client-secret=secret", REGISTRATION_PREFIX + ".foo.provider=github") + .run((context) -> { + ClientRegistrationRepository repository = context.getBean(ClientRegistrationRepository.class); + ClientRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration).isNotNull(); + assertThat(registration.getClientSecret()).isEqualTo("secret"); + }); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java index 7597f09d70..190859e9f7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,97 +62,106 @@ class OAuth2WebSecurityConfigurationTests { @Test void securityConfigurerConfiguresOAuth2Login() { - this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); - ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( - getFilters(context, OAuth2LoginAuthenticationFilter.class).get(0), - "clientRegistrationRepository"); - assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) - .isTrue(); - assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) - .isTrue(); - }); + this.contextRunner + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); + ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( + getFilters(context, OAuth2LoginAuthenticationFilter.class).get(0), + "clientRegistrationRepository"); + assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) + .isTrue(); + assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) + .isTrue(); + }); } @Test void securityConfigurerConfiguresAuthorizationCode() { - this.contextRunner.withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); - ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( - getFilters(context, OAuth2AuthorizationCodeGrantFilter.class).get(0), - "clientRegistrationRepository"); - assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) - .isTrue(); - assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) - .isTrue(); - }); + this.contextRunner + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + ClientRegistrationRepository expected = context.getBean(ClientRegistrationRepository.class); + ClientRegistrationRepository actual = (ClientRegistrationRepository) ReflectionTestUtils.getField( + getFilters(context, OAuth2AuthorizationCodeGrantFilter.class).get(0), + "clientRegistrationRepository"); + assertThat(isEqual(expected.findByRegistrationId("first"), actual.findByRegistrationId("first"))) + .isTrue(); + assertThat(isEqual(expected.findByRegistrationId("second"), actual.findByRegistrationId("second"))) + .isTrue(); + }); } @Test void securityConfigurerBacksOffWhenClientRegistrationBeanAbsent() { this.contextRunner.withUserConfiguration(TestConfig.class, OAuth2WebSecurityConfiguration.class) - .run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); - assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); - }); + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + }); } @Test void configurationRegistersAuthorizedClientServiceBean() { this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class)); + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class)); } @Test void configurationRegistersAuthorizedClientRepositoryBean() { this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class)); + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class)); } @Test void securityFilterChainConfigBacksOffWhenOtherSecurityFilterChainBeanPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebMvcAutoConfiguration.class)) - .withUserConfiguration(TestSecurityFilterChainConfiguration.class, OAuth2WebSecurityConfiguration.class) - .run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); - assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); - assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); - }); + .withUserConfiguration(TestSecurityFilterChainConfiguration.class, OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + assertThat(context).getBean(OAuth2AuthorizedClientService.class).isNotNull(); + }); } @Test void securityFilterChainConfigConditionalOnSecurityFilterChainClass() { this.contextRunner - .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class) - .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { - assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); - assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); - }); + .withUserConfiguration(ClientRegistrationRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) + .run((context) -> { + assertThat(getFilters(context, OAuth2LoginAuthenticationFilter.class)).isEmpty(); + assertThat(getFilters(context, OAuth2AuthorizationCodeGrantFilter.class)).isEmpty(); + }); } @Test void authorizedClientServiceBeanIsConditionalOnMissingBean() { - this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class); - assertThat(context).hasBean("testAuthorizedClientService"); - }); + this.contextRunner + .withUserConfiguration(OAuth2AuthorizedClientServiceConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2AuthorizedClientService.class); + assertThat(context).hasBean("testAuthorizedClientService"); + }); } @Test void authorizedClientRepositoryBeanIsConditionalOnMissingBean() { - this.contextRunner.withUserConfiguration(OAuth2AuthorizedClientRepositoryConfiguration.class, - OAuth2WebSecurityConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); - assertThat(context).hasBean("testAuthorizedClientRepository"); - }); + this.contextRunner + .withUserConfiguration(OAuth2AuthorizedClientRepositoryConfiguration.class, + OAuth2WebSecurityConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class); + assertThat(context).hasBean("testAuthorizedClientRepository"); + }); } private List getFilters(AssertableWebApplicationContext context, Class filter) { @@ -205,13 +214,18 @@ class OAuth2WebSecurityConfigurationTests { private ClientRegistration getClientRegistration(String id, String userInfoUri) { ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(id); - builder.clientName("foo").clientId("foo") - .clientAuthenticationMethod( - org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).scope("read") - .clientSecret("secret").redirectUri("https://redirect-uri.com") - .authorizationUri("https://authorization-uri.com").tokenUri("https://token-uri.com") - .userInfoUri(userInfoUri).userNameAttributeName("login"); + builder.clientName("foo") + .clientId("foo") + .clientAuthenticationMethod( + org.springframework.security.oauth2.core.ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .scope("read") + .clientSecret("secret") + .redirectUri("https://redirect-uri.com") + .authorizationUri("https://authorization-uri.com") + .tokenUri("https://token-uri.com") + .userInfoUri(userInfoUri) + .userNameAttributeName("login"); return builder.build(); } @@ -224,7 +238,8 @@ class OAuth2WebSecurityConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { return http.securityMatcher("/**") - .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()).build(); + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java index b56cc414b5..7b94ad1617 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java @@ -85,8 +85,8 @@ import static org.mockito.Mockito.mock; class ReactiveOAuth2ResourceServerAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) - .withUserConfiguration(TestConfig.class); + .withConfiguration(AutoConfigurations.of(ReactiveOAuth2ResourceServerAutoConfiguration.class)) + .withUserConfiguration(TestConfig.class); private MockWebServer server; @@ -108,60 +108,64 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test void autoConfigurationShouldConfigureResourceServer() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + }); } @Test void autoConfigurationUsingJwkSetUriShouldConfigureResourceServerUsingSingleJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS512") - .run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS512); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS512") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS512); + }); } @Test void autoConfigurationUsingJwkSetUriShouldConfigureResourceServerUsingMultipleJwsAlgorithms() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") - .run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$2.arg$1.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); + }); } @Test void autoConfigurationUsingPublicKeyValueShouldConfigureResourceServerUsingSingleJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384").run((context) -> { - NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); - assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$1.jwsKeySelector.expectedJWSAlg") - .isEqualTo(JWSAlgorithm.RS384); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") + .run((context) -> { + NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder = context.getBean(NimbusReactiveJwtDecoder.class); + assertThat(nimbusReactiveJwtDecoder).extracting("jwtProcessor.arg$1.jwsKeySelector.expectedJWSAlg") + .isEqualTo(JWSAlgorithm.RS384); + }); } @Test void autoConfigurationUsingPublicKeyValueWithMultipleJwsAlgorithmsShouldFail() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasRootCauseMessage( - "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " - + "configured"); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasRootCauseMessage( + "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " + + "configured"); + }); } @Test @@ -173,17 +177,19 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); - reactiveJwtDecoderSupplier.block(TIMEOUT); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context + .getBean(SupplierReactiveJwtDecoder.class); + Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); + reactiveJwtDecoderSupplier.block(TIMEOUT); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isOne(); } @@ -196,17 +202,19 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 1); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort()).run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); - reactiveJwtDecoderSupplier.block(TIMEOUT); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort()) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context + .getBean(SupplierReactiveJwtDecoder.class); + Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); + reactiveJwtDecoderSupplier.block(TIMEOUT); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(2); } @@ -219,17 +227,19 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url("").toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 2); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort()).run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); - reactiveJwtDecoderSupplier.block(TIMEOUT); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort()) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = context + .getBean(SupplierReactiveJwtDecoder.class); + Mono reactiveJwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierReactiveJwtDecoder, "jwtDecoderMono"); + reactiveJwtDecoderSupplier.block(TIMEOUT); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(3); } @@ -237,36 +247,37 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test void autoConfigurationShouldConfigureResourceServerUsingPublicKeyValue() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + }); } @Test void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining("class path resource [does-not-exist]") - .hasMessageContaining("Public key location does not exist")); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasMessageContaining("class path resource [does-not-exist]") + .hasMessageContaining("Public key location does not exist")); } @Test void autoConfigurationWhenSetUriKeyLocationIssuerUriPresentShouldUseSetUri() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") - .run((context) -> { - assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoder")).isTrue(); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + .run((context) -> { + assertThat(context).hasSingleBean(NimbusReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoder")).isTrue(); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); + }); } @Test @@ -277,15 +288,15 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort(), - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort(), + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(SupplierReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + }); } @Test @@ -296,105 +307,107 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { @Test void jwtDecoderBeanIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); } @Test void jwtDecoderByIssuerUriBeanIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((this::assertFilterConfiguredWithJwtAuthenticationManager)); } @Test void autoConfigurationShouldBeConditionalOnBearerTokenAuthenticationTokenClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) - .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) + .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test void autoConfigurationShouldBeConditionalOnReactiveJwtDecoderClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(ReactiveJwtDecoder.class)) - .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(ReactiveJwtDecoder.class)) + .run((context) -> assertThat(context).doesNotHaveBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)); } @Test void autoConfigurationWhenSecurityWebFilterChainConfigPresentShouldNotAddOne() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(SecurityWebFilterChainConfig.class).run((context) -> { - assertThat(context).hasSingleBean(SecurityWebFilterChain.class); - assertThat(context).hasBean("testSpringSecurityFilterChain"); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(SecurityWebFilterChainConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(SecurityWebFilterChain.class); + assertThat(context).hasBean("testSpringSecurityFilterChain"); + }); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldConfigureIntrospectionClient() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); - assertFilterConfiguredWithOpaqueTokenAuthenticationManager(context); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); + assertFilterConfiguredWithOpaqueTokenAuthenticationManager(context); + }); } @Test void autoConfigurationWhenJwkSetUriAndIntrospectionUriAvailable() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - assertFilterConfiguredWithJwtAuthenticationManager(context); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveOpaqueTokenIntrospector.class); + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + assertFilterConfiguredWithJwtAuthenticationManager(context); + }); } @Test void opaqueTokenIntrospectorIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") - .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) - .run((this::assertFilterConfiguredWithOpaqueTokenAuthenticationManager)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") + .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) + .run((this::assertFilterConfiguredWithOpaqueTokenAuthenticationManager)); } @Test void autoConfigurationForOpaqueTokenWhenSecurityWebFilterChainConfigPresentShouldNotAddOne() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .withUserConfiguration(SecurityWebFilterChainConfig.class).run((context) -> { - assertThat(context).hasSingleBean(SecurityWebFilterChain.class); - assertThat(context).hasBean("testSpringSecurityFilterChain"); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .withUserConfiguration(SecurityWebFilterChainConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(SecurityWebFilterChain.class); + assertThat(context).hasBean("testSpringSecurityFilterChain"); + }); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldBeConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOpaqueTokenIntrospector.class)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> assertThat(context).doesNotHaveBean(ReactiveOpaqueTokenIntrospector.class)); } @SuppressWarnings("unchecked") @@ -407,18 +420,18 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort() + "/" + path) - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(reactiveJwtDecoder, "jwtValidator"); - Collection> tokenValidators = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); - assertThat(tokenValidators).hasAtLeastOneElementOfType(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(reactiveJwtDecoder, "jwtValidator"); + Collection> tokenValidators = (Collection>) ReflectionTestUtils + .getField(jwtValidator, "tokenValidators"); + assertThat(tokenValidators).hasAtLeastOneElementOfType(JwtIssuerValidator.class); + }); } @SuppressWarnings("unchecked") @@ -431,18 +444,18 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(reactiveJwtDecoder, "jwtValidator"); - Collection> tokenValidators = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); - assertThat(tokenValidators).hasExactlyElementsOfTypes(JwtTimestampValidator.class); - assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class); - assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(reactiveJwtDecoder, "jwtValidator"); + Collection> tokenValidators = (Collection>) ReflectionTestUtils + .getField(jwtValidator, "tokenValidators"); + assertThat(tokenValidators).hasExactlyElementsOfTypes(JwtTimestampValidator.class); + assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class); + assertThat(tokenValidators).doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); + }); } @Test @@ -458,17 +471,17 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); - validate(issuerUri, reactiveJwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder reactiveJwtDecoder = context.getBean(ReactiveJwtDecoder.class); + validate(issuerUri, reactiveJwtDecoder); + }); } @SuppressWarnings("unchecked") private void validate(String issuerUri, ReactiveJwtDecoder jwtDecoder) throws MalformedURLException { DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); + .getField(jwtDecoder, "jwtValidator"); Jwt.Builder builder = jwt().claim("aud", Collections.singletonList("https://test-audience.com")); if (issuerUri != null) { builder.claim("iss", new URL(issuerUri)); @@ -476,7 +489,7 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { Jwt jwt = builder.build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); Collection> delegates = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); + .getField(jwtValidator, "tokenValidators"); validateDelegates(issuerUri, delegates); } @@ -484,9 +497,11 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { private void validateDelegates(String issuerUri, Collection> delegates) { assertThat(delegates).hasAtLeastOneElementOfType(JwtClaimValidator.class); OAuth2TokenValidator delegatingValidator = delegates.stream() - .filter((v) -> v instanceof DelegatingOAuth2TokenValidator).findFirst().get(); + .filter((v) -> v instanceof DelegatingOAuth2TokenValidator) + .findFirst() + .get(); Collection> nestedDelegates = (Collection>) ReflectionTestUtils - .getField(delegatingValidator, "tokenValidators"); + .getField(delegatingValidator, "tokenValidators"); if (issuerUri != null) { assertThat(nestedDelegates).hasAtLeastOneElementOfType(JwtIssuerValidator.class); } @@ -504,14 +519,13 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path; this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - SupplierReactiveJwtDecoder supplierJwtDecoderBean = context - .getBean(SupplierReactiveJwtDecoder.class); - Mono jwtDecoderSupplier = (Mono) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderMono"); - ReactiveJwtDecoder jwtDecoder = jwtDecoderSupplier.block(); - validate(issuerUri, jwtDecoder); - }); + .run((context) -> { + SupplierReactiveJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierReactiveJwtDecoder.class); + Mono jwtDecoderSupplier = (Mono) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderMono"); + ReactiveJwtDecoder jwtDecoder = jwtDecoderSupplier.block(); + validate(issuerUri, jwtDecoder); + }); } @Test @@ -525,11 +539,11 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { this.contextRunner.withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); - validate(null, jwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); + validate(null, jwtDecoder); + }); } @SuppressWarnings("unchecked") @@ -546,25 +560,28 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); - ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); - Jwt jwt = jwt().claim("iss", new URL(issuerUri)) - .claim("aud", Collections.singletonList("https://other-audience.com")).build(); - assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(ReactiveJwtDecoder.class); + ReactiveJwtDecoder jwtDecoder = context.getBean(ReactiveJwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(jwtDecoder, "jwtValidator"); + Jwt jwt = jwt().claim("iss", new URL(issuerUri)) + .claim("aud", Collections.singletonList("https://other-audience.com")) + .build(); + assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); + }); } private void assertFilterConfiguredWithJwtAuthenticationManager(AssertableReactiveWebApplicationContext context) { MatcherSecurityWebFilterChain filterChain = (MatcherSecurityWebFilterChain) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); Stream filters = filterChain.getWebFilters().toStream(); AuthenticationWebFilter webFilter = (AuthenticationWebFilter) filters - .filter((f) -> f instanceof AuthenticationWebFilter).findFirst().orElse(null); + .filter((f) -> f instanceof AuthenticationWebFilter) + .findFirst() + .orElse(null); ReactiveAuthenticationManagerResolver authenticationManagerResolver = (ReactiveAuthenticationManagerResolver) ReflectionTestUtils - .getField(webFilter, "authenticationManagerResolver"); + .getField(webFilter, "authenticationManagerResolver"); Object authenticationManager = authenticationManagerResolver.resolve(null).block(TIMEOUT); assertThat(authenticationManager).isInstanceOf(JwtReactiveAuthenticationManager.class); } @@ -572,12 +589,14 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { private void assertFilterConfiguredWithOpaqueTokenAuthenticationManager( AssertableReactiveWebApplicationContext context) { MatcherSecurityWebFilterChain filterChain = (MatcherSecurityWebFilterChain) context - .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); + .getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN); Stream filters = filterChain.getWebFilters().toStream(); AuthenticationWebFilter webFilter = (AuthenticationWebFilter) filters - .filter((f) -> f instanceof AuthenticationWebFilter).findFirst().orElse(null); + .filter((f) -> f instanceof AuthenticationWebFilter) + .findFirst() + .orElse(null); ReactiveAuthenticationManagerResolver authenticationManagerResolver = (ReactiveAuthenticationManagerResolver) ReflectionTestUtils - .getField(webFilter, "authenticationManagerResolver"); + .getField(webFilter, "authenticationManagerResolver"); Object authenticationManager = authenticationManagerResolver.resolve(null).block(TIMEOUT); assertThat(authenticationManager).isInstanceOf(OpaqueTokenReactiveAuthenticationManager.class); } @@ -591,8 +610,8 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { private void setupMockResponse(String issuer) throws JsonProcessingException { MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) - .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); this.server.enqueue( new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java index 4b535fccd6..bcd7e7e973 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/resource/servlet/OAuth2ResourceServerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -80,8 +80,8 @@ import static org.mockito.Mockito.mock; class OAuth2ResourceServerAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) - .withUserConfiguration(TestConfig.class); + .withConfiguration(AutoConfigurations.of(OAuth2ResourceServerAutoConfiguration.class)) + .withUserConfiguration(TestConfig.class); private MockWebServer server; @@ -101,74 +101,78 @@ class OAuth2ResourceServerAutoConfigurationTests { @Test void autoConfigurationShouldConfigureResourceServer() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationShouldMatchDefaultJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS256); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS256); + }); } @Test void autoConfigurationShouldConfigureResourceServerWithSingleJwsAlgorithm() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") - .run((context) -> { - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS384); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") + .run((context) -> { + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS384); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationShouldConfigureResourceServerWithMultipleJwsAlgorithms() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") - .run((context) -> { - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") - .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) - .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS256, RS384, RS512") + .run((context) -> { + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtProcessor.jwsKeySelector.jwsAlgs") + .asInstanceOf(InstanceOfAssertFactories.collection(JWSAlgorithm.class)) + .containsExactlyInAnyOrder(JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationUsingPublicKeyValueShouldConfigureResourceServerUsingSingleJwsAlgorithm() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384").run((context) -> { - NimbusJwtDecoder nimbusJwtDecoder = context.getBean(NimbusJwtDecoder.class); - assertThat(nimbusJwtDecoder).extracting("jwtProcessor.jwsKeySelector.expectedJWSAlg") - .isEqualTo(JWSAlgorithm.RS384); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RS384") + .run((context) -> { + NimbusJwtDecoder nimbusJwtDecoder = context.getBean(NimbusJwtDecoder.class); + assertThat(nimbusJwtDecoder).extracting("jwtProcessor.jwsKeySelector.expectedJWSAlg") + .isEqualTo(JWSAlgorithm.RS384); + }); } @Test void autoConfigurationUsingPublicKeyValueWithMultipleJwsAlgorithmsShouldFail() { - this.contextRunner.withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384").run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasRootCauseMessage( - "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " - + "configured"); - }); + this.contextRunner + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=RSA256,RS384") + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()).hasRootCauseMessage( + "Creating a JWT decoder using a public key requires exactly one JWS algorithm but 2 were " + + "configured"); + }); } @Test @@ -180,15 +184,17 @@ class OAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierJwtDecoder.class); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - jwtDecoderSupplier.get(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierJwtDecoder.class); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + jwtDecoderSupplier.get(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(2); } @@ -202,15 +208,17 @@ class OAuth2ResourceServerAutoConfigurationTests { String issuer = this.server.url(path).toString(); String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 1); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierJwtDecoder.class); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - jwtDecoderSupplier.get(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierJwtDecoder.class); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + jwtDecoderSupplier.get(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(3); } @@ -225,15 +233,17 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponsesWithErrors(cleanIssuerPath, 2); - this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" - + this.server.getHostName() + ":" + this.server.getPort() + "/" + path).run((context) -> { - assertThat(context).hasSingleBean(SupplierJwtDecoder.class); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - jwtDecoderSupplier.get(); - }); + this.contextRunner + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + + this.server.getHostName() + ":" + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(SupplierJwtDecoder.class); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + jwtDecoderSupplier.get(); + }); // The last request is to the JWK Set endpoint to look up the algorithm assertThat(this.server.getRequestCount()).isEqualTo(4); } @@ -246,46 +256,48 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void autoConfigurationShouldFailIfPublicKeyLocationDoesNotExist() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining("class path resource [does-not-exist]") - .hasMessageContaining("Public key location does not exist")); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:does-not-exist") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasMessageContaining("class path resource [does-not-exist]") + .hasMessageContaining("Public key location does not exist")); } @Test void autoConfigurationShouldFailIfAlgorithmIsInvalid() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jws-algorithms=NOT_VALID") - .run((context) -> assertThat(context).hasFailed().getFailure() - .hasMessageContaining("signatureAlgorithm cannot be null")); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jws-algorithms=NOT_VALID") + .run((context) -> assertThat(context).hasFailed() + .getFailure() + .hasMessageContaining("signatureAlgorithm cannot be null")); } @Test void autoConfigurationWhenSetUriKeyLocationAndIssuerUriPresentShouldUseSetUri() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", - "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - assertThat(context.containsBean("jwtDecoderByJwkKeySetUri")).isTrue(); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=https://issuer-uri.com", + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", + "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + assertThat(context.containsBean("jwtDecoderByJwkKeySetUri")).isTrue(); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isFalse(); + }); } @Test @@ -296,15 +308,15 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort(), - "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort(), + "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + assertThat(context.containsBean("jwtDecoderByIssuerUri")).isTrue(); + }); } @Test @@ -315,112 +327,116 @@ class OAuth2ResourceServerAutoConfigurationTests { @Test void jwtDecoderByJwkSetUriIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void jwtDecoderByOidcIssuerUriIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") - .withUserConfiguration(JwtDecoderConfig.class) - .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); + .withPropertyValues( + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://jwk-oidc-issuer-location.com") + .withUserConfiguration(JwtDecoderConfig.class) + .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void autoConfigurationShouldBeConditionalOnResourceServerClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)).run((context) -> { - assertThat(context).doesNotHaveBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void autoConfigurationForJwtShouldBeConditionalOnJwtDecoderClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(JwtDecoder.class)).run((context) -> { - assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(JwtDecoder.class)) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void jwtSecurityFilterShouldBeConditionalOnSecurityFilterChainClass() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class) - .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { - assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class) + .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void opaqueTokenSecurityFilterShouldBeConditionalOnSecurityFilterChainClass() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)).run((context) -> { - assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); - assertThat(getBearerTokenFilter(context)).isNull(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) + .run((context) -> { + assertThat(context).hasSingleBean(OAuth2ResourceServerAutoConfiguration.class); + assertThat(getBearerTokenFilter(context)).isNull(); + }); } @Test void autoConfigurationWhenJwkSetUriAndIntrospectionUriAvailable() { this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); - assertThat(context).hasSingleBean(JwtDecoder.class); - assertThat(getBearerTokenFilter(context)) - .extracting("authenticationManagerResolver.arg$1.providers").asList() - .hasAtLeastOneElementOfType(JwtAuthenticationProvider.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); + assertThat(context).hasSingleBean(JwtDecoder.class); + assertThat(getBearerTokenFilter(context)).extracting("authenticationManagerResolver.arg$1.providers") + .asList() + .hasAtLeastOneElementOfType(JwtAuthenticationProvider.class); + }); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldConfigureIntrospectionClient() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> { - assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); - assertThat(getBearerTokenFilter(context)).isNotNull(); - }); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> { + assertThat(context).hasSingleBean(OpaqueTokenIntrospector.class); + assertThat(getBearerTokenFilter(context)).isNotNull(); + }); } @Test void opaqueTokenIntrospectorIsConditionalOnMissingBean() { this.contextRunner - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") - .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) - .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com") + .withUserConfiguration(OpaqueTokenIntrospectorConfig.class) + .run((context) -> assertThat(getBearerTokenFilter(context)).isNotNull()); } @Test void autoConfigurationWhenIntrospectionUriAvailableShouldBeConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(BearerTokenAuthenticationToken.class)) - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> assertThat(context).doesNotHaveBean(OpaqueTokenIntrospector.class)); + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> assertThat(context).doesNotHaveBean(OpaqueTokenIntrospector.class)); } @Test @@ -432,16 +448,16 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", - "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" - + this.server.getPort() + "/" + path) - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") - .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) - .hasAtLeastOneElementOfType(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=http://" + this.server.getHostName() + ":" + + this.server.getPort() + "/" + path) + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") + .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) + .hasAtLeastOneElementOfType(JwtIssuerValidator.class); + }); } @Test @@ -453,16 +469,16 @@ class OAuth2ResourceServerAutoConfigurationTests { String cleanIssuerPath = cleanIssuerPath(issuer); setupMockResponse(cleanIssuerPath); this.contextRunner - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") - .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) - .hasExactlyElementsOfTypes(JwtTimestampValidator.class) - .doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class) - .doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); - }); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + assertThat(jwtDecoder).extracting("jwtValidator.tokenValidators") + .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) + .hasExactlyElementsOfTypes(JwtTimestampValidator.class) + .doesNotHaveAnyElementsOfTypes(JwtClaimValidator.class) + .doesNotHaveAnyElementsOfTypes(JwtIssuerValidator.class); + }); } @Test @@ -478,11 +494,11 @@ class OAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - validate(issuerUri, jwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + validate(issuerUri, jwtDecoder); + }); } @SuppressWarnings("unchecked") @@ -497,19 +513,19 @@ class OAuth2ResourceServerAutoConfigurationTests { String issuerUri = "http://" + this.server.getHostName() + ":" + this.server.getPort() + "/" + path; this.contextRunner.withPropertyValues("spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); - Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils - .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); - JwtDecoder jwtDecoder = jwtDecoderSupplier.get(); - validate(issuerUri, jwtDecoder); - }); + .run((context) -> { + SupplierJwtDecoder supplierJwtDecoderBean = context.getBean(SupplierJwtDecoder.class); + Supplier jwtDecoderSupplier = (Supplier) ReflectionTestUtils + .getField(supplierJwtDecoderBean, "jwtDecoderSupplier"); + JwtDecoder jwtDecoder = jwtDecoderSupplier.get(); + validate(issuerUri, jwtDecoder); + }); } @SuppressWarnings("unchecked") private void validate(String issuerUri, JwtDecoder jwtDecoder) throws MalformedURLException { DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); + .getField(jwtDecoder, "jwtValidator"); Jwt.Builder builder = jwt().claim("aud", Collections.singletonList("https://test-audience.com")); if (issuerUri != null) { builder.claim("iss", new URL(issuerUri)); @@ -517,18 +533,20 @@ class OAuth2ResourceServerAutoConfigurationTests { Jwt jwt = builder.build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); Collection> delegates = (Collection>) ReflectionTestUtils - .getField(jwtValidator, "tokenValidators"); + .getField(jwtValidator, "tokenValidators"); validateDelegates(issuerUri, delegates); } private void validateDelegates(String issuerUri, Collection> delegates) { assertThat(delegates).hasAtLeastOneElementOfType(JwtClaimValidator.class); OAuth2TokenValidator delegatingValidator = delegates.stream() - .filter((v) -> v instanceof DelegatingOAuth2TokenValidator).findFirst().get(); + .filter((v) -> v instanceof DelegatingOAuth2TokenValidator) + .findFirst() + .get(); if (issuerUri != null) { assertThat(delegatingValidator).extracting("tokenValidators") - .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) - .hasAtLeastOneElementOfType(JwtIssuerValidator.class); + .asInstanceOf(InstanceOfAssertFactories.collection(OAuth2TokenValidator.class)) + .hasAtLeastOneElementOfType(JwtIssuerValidator.class); } } @@ -543,11 +561,11 @@ class OAuth2ResourceServerAutoConfigurationTests { this.contextRunner.withPropertyValues( "spring.security.oauth2.resourceserver.jwt.public-key-location=classpath:public-key-location", "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,http://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - validate(null, jwtDecoder); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + validate(null, jwtDecoder); + }); } @SuppressWarnings("unchecked") @@ -564,34 +582,35 @@ class OAuth2ResourceServerAutoConfigurationTests { "spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com", "spring.security.oauth2.resourceserver.jwt.issuer-uri=" + issuerUri, "spring.security.oauth2.resourceserver.jwt.audiences=https://test-audience.com,https://test-audience1.com") - .run((context) -> { - assertThat(context).hasSingleBean(JwtDecoder.class); - JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); - DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils - .getField(jwtDecoder, "jwtValidator"); - Jwt jwt = jwt().claim("iss", new URL(issuerUri)) - .claim("aud", Collections.singletonList("https://other-audience.com")).build(); - assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(JwtDecoder.class); + JwtDecoder jwtDecoder = context.getBean(JwtDecoder.class); + DelegatingOAuth2TokenValidator jwtValidator = (DelegatingOAuth2TokenValidator) ReflectionTestUtils + .getField(jwtDecoder, "jwtValidator"); + Jwt jwt = jwt().claim("iss", new URL(issuerUri)) + .claim("aud", Collections.singletonList("https://other-audience.com")) + .build(); + assertThat(jwtValidator.validate(jwt).hasErrors()).isTrue(); + }); } @Test void jwtSecurityConfigurerBacksOffWhenSecurityFilterChainBeanIsPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebMvcAutoConfiguration.class)) - .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") - .withUserConfiguration(JwtDecoderConfig.class, TestSecurityFilterChainConfig.class) - .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); + .withPropertyValues("spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://jwk-set-uri.com") + .withUserConfiguration(JwtDecoderConfig.class, TestSecurityFilterChainConfig.class) + .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); } @Test void opaqueTokenSecurityConfigurerBacksOffWhenSecurityFilterChainBeanIsPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebMvcAutoConfiguration.class)) - .withUserConfiguration(TestSecurityFilterChainConfig.class) - .withPropertyValues( - "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", - "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", - "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") - .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); + .withUserConfiguration(TestSecurityFilterChainConfig.class) + .withPropertyValues( + "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://check-token.com", + "spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id", + "spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret") + .run((context) -> assertThat(context).hasSingleBean(SecurityFilterChain.class)); } private Filter getBearerTokenFilter(AssertableWebApplicationContext context) { @@ -610,8 +629,8 @@ class OAuth2ResourceServerAutoConfigurationTests { private void setupMockResponse(String issuer) throws JsonProcessingException { MockResponse mockResponse = new MockResponse().setResponseCode(HttpStatus.OK.value()) - .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + .setBody(new ObjectMapper().writeValueAsString(getResponse(issuer))) + .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); this.server.enqueue( new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET)); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java index 59ce29e815..4436ab7360 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveSecurityAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -43,26 +43,26 @@ class ReactiveSecurityAutoConfigurationTests { @Test void backsOffWhenWebFilterChainProxyBeanPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) - .withUserConfiguration(WebFilterChainProxyConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(WebFilterChainProxy.class)); + .withUserConfiguration(WebFilterChainProxyConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(WebFilterChainProxy.class)); } @Test void enablesWebFluxSecurity() { this.contextRunner - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class)) - .run((context) -> assertThat(context).getBean(WebFilterChainProxy.class).isNotNull()); + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class)) + .run((context) -> assertThat(context).getBean(WebFilterChainProxy.class).isNotNull()); } @Test void autoConfigurationIsConditionalOnClass() { this.contextRunner - .withClassLoader(new FilteredClassLoader(Flux.class, EnableWebFluxSecurity.class, - WebFilterChainProxy.class, WebFluxConfigurer.class)) - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, - ReactiveUserDetailsServiceAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(WebFilterChainProxy.class)); + .withClassLoader(new FilteredClassLoader(Flux.class, EnableWebFluxSecurity.class, WebFilterChainProxy.class, + WebFluxConfigurer.class)) + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class, + ReactiveUserDetailsServiceAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(WebFilterChainProxy.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java index 31b350ccc5..e2389c322a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/ReactiveUserDetailsServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ import static org.mockito.Mockito.mock; class ReactiveUserDetailsServiceAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class)); @Test void configuresADefaultUser() { @@ -67,12 +67,13 @@ class ReactiveUserDetailsServiceAutoConfigurationTests { @Test void userDetailsServiceWhenRSocketConfigured() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, - RSocketMessagingAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class)) - .withUserConfiguration(TestRSocketSecurityConfiguration.class).run((context) -> { - ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); - assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, + RSocketMessagingAutoConfiguration.class, RSocketStrategiesAutoConfiguration.class)) + .withUserConfiguration(TestRSocketSecurityConfiguration.class) + .run((context) -> { + ReactiveUserDetailsService userDetailsService = context.getBean(ReactiveUserDetailsService.class); + assertThat(userDetailsService.findByUsername("user").block(Duration.ofSeconds(30))).isNotNull(); + }); } @Test @@ -88,15 +89,15 @@ class ReactiveUserDetailsServiceAutoConfigurationTests { @Test void doesNotConfigureDefaultUserIfAuthenticationManagerAvailable() { this.contextRunner.withUserConfiguration(AuthenticationManagerConfig.class, TestSecurityConfiguration.class) - .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) - .run((context) -> assertThat(context).getBean(ReactiveUserDetailsService.class).isNull()); + .withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class)) + .run((context) -> assertThat(context).getBean(ReactiveUserDetailsService.class).isNull()); } @Test void doesNotConfigureDefaultUserIfAuthenticationManagerResolverAvailable() { this.contextRunner.withUserConfiguration(AuthenticationManagerResolverConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ReactiveAuthenticationManagerResolver.class) - .doesNotHaveBean(ReactiveUserDetailsService.class)); + .run((context) -> assertThat(context).hasSingleBean(ReactiveAuthenticationManagerResolver.class) + .doesNotHaveBean(ReactiveUserDetailsService.class)); } @Test @@ -142,13 +143,12 @@ class ReactiveUserDetailsServiceAutoConfigurationTests { private void testPasswordEncoding(Class configClass, String providedPassword, String expectedPassword) { this.contextRunner.withUserConfiguration(configClass) - .withPropertyValues("spring.security.user.password=" + providedPassword).run(((context) -> { - MapReactiveUserDetailsService userDetailsService = context - .getBean(MapReactiveUserDetailsService.class); - String password = userDetailsService.findByUsername("user").block(Duration.ofSeconds(30)) - .getPassword(); - assertThat(password).isEqualTo(expectedPassword); - })); + .withPropertyValues("spring.security.user.password=" + providedPassword) + .run(((context) -> { + MapReactiveUserDetailsService userDetailsService = context.getBean(MapReactiveUserDetailsService.class); + String password = userDetailsService.findByUsername("user").block(Duration.ofSeconds(30)).getPassword(); + assertThat(password).isEqualTo(expectedPassword); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java index 52c48e712d..db501b62ae 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ class StaticResourceRequestTests { @Test void atCommonLocationsWithExcludeShouldNotMatchExcluded() { ServerWebExchangeMatcher matcher = this.resourceRequest.atCommonLocations() - .excluding(StaticResourceLocation.CSS); + .excluding(StaticResourceLocation.CSS); assertMatcher(matcher).doesNotMatch("/css/file.css"); assertMatcher(matcher).matches("/js/file.js"); } @@ -78,13 +78,13 @@ class StaticResourceRequestTests { @Test void atLocationsFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } @Test void excludeFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } private RequestMatcherAssert assertMatcher(ServerWebExchangeMatcher matcher) { @@ -112,7 +112,8 @@ class StaticResourceRequestTests { private void matches(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Matches " + getRequestPath(exchange)).isTrue(); + .as("Matches " + getRequestPath(exchange)) + .isTrue(); } void doesNotMatch(String path) { @@ -123,7 +124,8 @@ class StaticResourceRequestTests { private void doesNotMatch(ServerWebExchange exchange) { assertThat(this.matcher.matches(exchange).block(Duration.ofSeconds(30)).isMatch()) - .as("Does not match " + getRequestPath(exchange)).isFalse(); + .as("Does not match " + getRequestPath(exchange)) + .isFalse(); } private TestHttpWebHandlerAdapter webHandler() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java index 856478f544..95d8072690 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/rsocket/RSocketSecurityAutoConfigurationTests.java @@ -42,9 +42,9 @@ import static org.assertj.core.api.Assertions.assertThat; class RSocketSecurityAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, - RSocketSecurityAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, - RSocketStrategiesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveUserDetailsServiceAutoConfiguration.class, + RSocketSecurityAutoConfiguration.class, RSocketMessagingAutoConfiguration.class, + RSocketStrategiesAutoConfiguration.class)); @Test void autoConfigurationEnablesRSocketSecurity() { @@ -54,7 +54,7 @@ class RSocketSecurityAutoConfigurationTests { @Test void autoConfigurationIsConditionalOnSecuritySocketAcceptorInterceptorClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(SecuritySocketAcceptorInterceptor.class)) - .run((context) -> assertThat(context).doesNotHaveBean(RSocketSecurity.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RSocketSecurity.class)); } @Test @@ -66,7 +66,7 @@ class RSocketSecurityAutoConfigurationTests { server.interceptors((registry) -> registry.forSocketAcceptor((interceptors) -> { assertThat(interceptors).isNotEmpty(); assertThat(interceptors) - .anyMatch((interceptor) -> interceptor instanceof SecuritySocketAcceptorInterceptor); + .anyMatch((interceptor) -> interceptor instanceof SecuritySocketAcceptorInterceptor); })); }); } @@ -77,7 +77,7 @@ class RSocketSecurityAutoConfigurationTests { assertThat(context).hasSingleBean(RSocketMessageHandler.class); RSocketMessageHandler handler = context.getBean(RSocketMessageHandler.class); assertThat(handler.getArgumentResolverConfigurer().getCustomResolvers()) - .anyMatch((customResolver) -> customResolver instanceof AuthenticationPrincipalArgumentResolver); + .anyMatch((customResolver) -> customResolver instanceof AuthenticationPrincipalArgumentResolver); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java index ec5d298187..a5a97d113a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyAutoConfigurationTests.java @@ -65,23 +65,24 @@ class Saml2RelyingPartyAutoConfigurationTests { @Test void autoConfigurationShouldBeConditionalOnRelyingPartyRegistrationRepositoryClass() { - this.contextRunner.withPropertyValues(getPropertyValues()).withClassLoader(new FilteredClassLoader( - "org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository")) - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + this.contextRunner.withPropertyValues(getPropertyValues()) + .withClassLoader(new FilteredClassLoader( + "org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository")) + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test void autoConfigurationShouldBeConditionalOnServletWebApplication() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) - .withPropertyValues(getPropertyValues()) - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + .withConfiguration(AutoConfigurations.of(Saml2RelyingPartyAutoConfiguration.class)) + .withPropertyValues(getPropertyValues()) + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test void relyingPartyRegistrationRepositoryBeanShouldNotBeCreatedWhenPropertiesAbsent() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); + .run((context) -> assertThat(context).doesNotHaveBean(RelyingPartyRegistrationRepository.class)); } @Test @@ -91,30 +92,30 @@ class Saml2RelyingPartyAutoConfigurationTests { RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"); assertThat(registration.getAssertingPartyDetails().getEntityId()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"); assertThat(registration.getAssertionConsumerServiceLocation()) - .isEqualTo("{baseUrl}/login/saml2/foo-entity-id"); + .isEqualTo("{baseUrl}/login/saml2/foo-entity-id"); assertThat(registration.getAssertionConsumerServiceBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); + .isEqualTo(Saml2MessageBinding.POST); assertThat(registration.getAssertingPartyDetails().getWantAuthnRequestsSigned()).isFalse(); assertThat(registration.getSigningX509Credentials()).hasSize(1); assertThat(registration.getDecryptionX509Credentials()).hasSize(1); assertThat(registration.getAssertingPartyDetails().getVerificationX509Credentials()).isNotNull(); assertThat(registration.getEntityId()).isEqualTo("{baseUrl}/saml2/foo-entity-id"); assertThat(registration.getSingleLogoutServiceLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); assertThat(registration.getSingleLogoutServiceResponseLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); assertThat(registration.getSingleLogoutServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SLOService.php"); assertThat(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation()) - .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); + .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/"); assertThat(registration.getAssertingPartyDetails().getSingleLogoutServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); + .isEqualTo(Saml2MessageBinding.POST); }); } @@ -130,7 +131,7 @@ class Saml2RelyingPartyAutoConfigurationTests { @Test void autoConfigurationWhenSignRequestsFalseAndNoSigningCredentialsShouldNotThrowException() { this.contextRunner.withPropertyValues(getPropertyValuesWithoutSigningCredentials(false)) - .run((context) -> assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class)); + .run((context) -> assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class)); } @Test @@ -140,10 +141,10 @@ class Saml2RelyingPartyAutoConfigurationTests { String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); this.contextRunner.withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl) - .run((context) -> { - assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); - assertThat(server.getRequestCount()).isOne(); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); + assertThat(server.getRequestCount()).isOne(); + }); } } @@ -154,13 +155,13 @@ class Saml2RelyingPartyAutoConfigurationTests { String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); this.contextRunner.withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl) - .run((context) -> { - RelyingPartyRegistrationRepository repository = context - .getBean(RelyingPartyRegistrationRepository.class); - RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.POST); - }); + .run((context) -> { + RelyingPartyRegistrationRepository repository = context + .getBean(RelyingPartyRegistrationRepository.class); + RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) + .isEqualTo(Saml2MessageBinding.POST); + }); } } @@ -170,14 +171,16 @@ class Saml2RelyingPartyAutoConfigurationTests { server.start(); String metadataUrl = server.url("").toString(); setupMockResponse(server, new ClassPathResource("saml/idp-metadata")); - this.contextRunner.withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl, - PREFIX + ".foo.assertingparty.singlesignon.binding=redirect").run((context) -> { - RelyingPartyRegistrationRepository repository = context - .getBean(RelyingPartyRegistrationRepository.class); - RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); - assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.REDIRECT); - }); + this.contextRunner + .withPropertyValues(PREFIX + ".foo.assertingparty.metadata-uri=" + metadataUrl, + PREFIX + ".foo.assertingparty.singlesignon.binding=redirect") + .run((context) -> { + RelyingPartyRegistrationRepository repository = context + .getBean(RelyingPartyRegistrationRepository.class); + RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); + assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) + .isEqualTo(Saml2MessageBinding.REDIRECT); + }); } } @@ -187,43 +190,45 @@ class Saml2RelyingPartyAutoConfigurationTests { RelyingPartyRegistrationRepository repository = context.getBean(RelyingPartyRegistrationRepository.class); RelyingPartyRegistration registration = repository.findByRegistrationId("foo"); assertThat(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(Saml2MessageBinding.REDIRECT); + .isEqualTo(Saml2MessageBinding.REDIRECT); }); } @Test void relyingPartyRegistrationRepositoryShouldBeConditionalOnMissingBean() { this.contextRunner.withPropertyValues(getPropertyValues()) - .withUserConfiguration(RegistrationRepositoryConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); - assertThat(context).hasBean("testRegistrationRepository"); - }); + .withUserConfiguration(RegistrationRepositoryConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(RelyingPartyRegistrationRepository.class); + assertThat(context).hasBean("testRegistrationRepository"); + }); } @Test void samlLoginShouldBeConfigured() { this.contextRunner.withPropertyValues(getPropertyValues()) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isTrue()); + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isTrue()); } @Test void samlLoginShouldBackOffWhenASecurityFilterChainBeanIsPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebMvcAutoConfiguration.class)) - .withUserConfiguration(TestSecurityFilterChainConfig.class).withPropertyValues(getPropertyValues()) - .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); + .withUserConfiguration(TestSecurityFilterChainConfig.class) + .withPropertyValues(getPropertyValues()) + .run((context) -> assertThat(hasFilter(context, Saml2WebSsoAuthenticationFilter.class)).isFalse()); } @Test void samlLoginShouldShouldBeConditionalOnSecurityWebFilterClass() { this.contextRunner.withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) - .withPropertyValues(getPropertyValues()) - .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); + .withPropertyValues(getPropertyValues()) + .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); } @Test void samlLogoutShouldBeConfigured() { this.contextRunner.withPropertyValues(getPropertyValues()) - .run((context) -> assertThat(hasFilter(context, Saml2LogoutRequestFilter.class)).isTrue()); + .run((context) -> assertThat(hasFilter(context, Saml2LogoutRequestFilter.class)).isTrue()); } private String[] getPropertyValuesWithoutSigningCredentials(boolean signRequests) { @@ -303,7 +308,8 @@ class Saml2RelyingPartyAutoConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { return http.securityMatcher("/**") - .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()).build(); + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java index 2ad57592c7..0ac09bc3c4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/saml2/Saml2RelyingPartyPropertiesTests.java @@ -45,23 +45,29 @@ class Saml2RelyingPartyPropertiesTests { "https://simplesaml-for-spring-saml/SSOService.php"); assertThat( this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getSinglesignon().getUrl()) - .isEqualTo("https://simplesaml-for-spring-saml/SSOService.php"); + .isEqualTo("https://simplesaml-for-spring-saml/SSOService.php"); } @Test void customizeSsoBinding() { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.binding", "post"); - assertThat(this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getSinglesignon() - .getBinding()).isEqualTo(Saml2MessageBinding.POST); + assertThat(this.properties.getRegistration() + .get("simplesamlphp") + .getAssertingparty() + .getSinglesignon() + .getBinding()).isEqualTo(Saml2MessageBinding.POST); } @Test void customizeSsoSignRequests() { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.single-sign-on.sign-request", "false"); - assertThat(this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getSinglesignon() - .isSignRequest()).isFalse(); + assertThat(this.properties.getRegistration() + .get("simplesamlphp") + .getAssertingparty() + .getSinglesignon() + .isSignRequest()).isFalse(); } @Test @@ -69,13 +75,13 @@ class Saml2RelyingPartyPropertiesTests { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.entity-id", "{baseUrl}/saml2/custom-entity-id"); assertThat(this.properties.getRegistration().get("simplesamlphp").getEntityId()) - .isEqualTo("{baseUrl}/saml2/custom-entity-id"); + .isEqualTo("{baseUrl}/saml2/custom-entity-id"); } @Test void customizeRelyingPartyEntityIdDefaultsToServiceProviderMetadata() { assertThat(RelyingPartyRegistration.withRegistrationId("id")).extracting("entityId") - .isEqualTo(new Saml2RelyingPartyProperties.Registration().getEntityId()); + .isEqualTo(new Saml2RelyingPartyProperties.Registration().getEntityId()); } @Test @@ -83,14 +89,17 @@ class Saml2RelyingPartyPropertiesTests { bind("spring.security.saml2.relyingparty.registration.simplesamlphp.assertingparty.metadata-uri", "https://idp.example.org/metadata"); assertThat(this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getMetadataUri()) - .isEqualTo("https://idp.example.org/metadata"); + .isEqualTo("https://idp.example.org/metadata"); } @Test void customizeSsoSignRequestsIsTrueByDefault() { this.properties.getRegistration().put("simplesamlphp", new Saml2RelyingPartyProperties.Registration()); - assertThat(this.properties.getRegistration().get("simplesamlphp").getAssertingparty().getSinglesignon() - .isSignRequest()).isTrue(); + assertThat(this.properties.getRegistration() + .get("simplesamlphp") + .getAssertingparty() + .getSinglesignon() + .isSignRequest()).isTrue(); } private void bind(String name, String value) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java index fc63062025..3a75d04394 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfigurationTests.java @@ -79,22 +79,23 @@ class SecurityAutoConfigurationTests { @Test void enableWebSecurityIsConditionalOnClass() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security.config")) - .run((context) -> assertThat(context).doesNotHaveBean("springSecurityFilterChain")); + .run((context) -> assertThat(context).doesNotHaveBean("springSecurityFilterChain")); } @Test void filterChainBeanIsConditionalOnClassSecurityFilterChain() { this.contextRunner.withClassLoader(new FilteredClassLoader(SecurityFilterChain.class)) - .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SecurityFilterChain.class)); } @Test void securityConfigurerBacksOffWhenOtherSecurityFilterChainBeanPresent() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebMvcAutoConfiguration.class)) - .withUserConfiguration(TestSecurityFilterChainConfig.class).run((context) -> { - assertThat(context.getBeansOfType(SecurityFilterChain.class)).hasSize(1); - assertThat(context.containsBean("testSecurityFilterChain")).isTrue(); - }); + .withUserConfiguration(TestSecurityFilterChainConfig.class) + .run((context) -> { + assertThat(context.getBeansOfType(SecurityFilterChain.class)).hasSize(1); + assertThat(context.containsBean("testSecurityFilterChain")).isTrue(); + }); } @Test @@ -110,40 +111,42 @@ class SecurityAutoConfigurationTests { @Test void defaultAuthenticationEventPublisherRegistered() { this.contextRunner.run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)) - .isInstanceOf(DefaultAuthenticationEventPublisher.class)); + .isInstanceOf(DefaultAuthenticationEventPublisher.class)); } @Test void defaultAuthenticationEventPublisherIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(AuthenticationEventPublisherConfiguration.class) - .run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)).isInstanceOf( - AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); + .run((context) -> assertThat(context.getBean(AuthenticationEventPublisher.class)) + .isInstanceOf(AuthenticationEventPublisherConfiguration.TestAuthenticationEventPublisher.class)); } @Test void testDefaultFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .run((context) -> assertThat( - context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()) + .isEqualTo(OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100)); } @Test void testCustomFilterOrder() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .withPropertyValues("spring.security.filter.order:12345") - .run((context) -> assertThat( - context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) - .getOrder()).isEqualTo(12345)); + .withPropertyValues("spring.security.filter.order:12345") + .run((context) -> assertThat( + context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class) + .getOrder()) + .isEqualTo(12345)); } @Test void testJpaCoexistsHappily() { this.contextRunner.withPropertyValues("spring.datasource.url:jdbc:hsqldb:mem:testsecdb") - .withUserConfiguration(EntityConfiguration.class) - .withConfiguration( - AutoConfigurations.of(HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context.getBean(JpaTransactionManager.class)).isNotNull()); + .withUserConfiguration(EntityConfiguration.class) + .withConfiguration( + AutoConfigurations.of(HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class)) + .run((context) -> assertThat(context.getBean(JpaTransactionManager.class)).isNotNull()); // This can fail if security @Conditionals force early instantiation of the // HibernateJpaAutoConfiguration (e.g. the EntityManagerFactory is not found) } @@ -151,60 +154,59 @@ class SecurityAutoConfigurationTests { @Test void testSecurityEvaluationContextExtensionSupport() { this.contextRunner - .run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull()); + .run((context) -> assertThat(context).getBean(SecurityEvaluationContextExtension.class).isNotNull()); } @Test void defaultFilterDispatcherTypes() { this.contextRunner.withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) - .run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); - assertThat(bean) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsExactlyInAnyOrderElementsOf(EnumSet.allOf(DispatcherType.class)); - }); + .run((context) -> { + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class); + assertThat(bean).extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsExactlyInAnyOrderElementsOf(EnumSet.allOf(DispatcherType.class)); + }); } @Test void customFilterDispatcherTypes() { this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:INCLUDE,ERROR") - .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); - assertThat(bean) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR); - }); + .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + .run((context) -> { + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class); + assertThat(bean).extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR); + }); } @Test void emptyFilterDispatcherTypesDoNotThrowException() { this.contextRunner.withPropertyValues("spring.security.filter.dispatcher-types:") - .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)).run((context) -> { - DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", - DelegatingFilterProxyRegistrationBean.class); - assertThat(bean) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .isEmpty(); - }); + .withConfiguration(AutoConfigurations.of(SecurityFilterAutoConfiguration.class)) + .run((context) -> { + DelegatingFilterProxyRegistrationBean bean = context.getBean("securityFilterChainRegistration", + DelegatingFilterProxyRegistrationBean.class); + assertThat(bean).extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .isEmpty(); + }); } @Test void whenAConfigurationPropertyBindingConverterIsDefinedThenBindingToAnRsaKeySucceeds() { this.contextRunner.withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class) - .withPropertyValues("jwt.public-key=classpath:public-key-location") - .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); + .withPropertyValues("jwt.public-key=classpath:public-key-location") + .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); } @Test void whenTheBeanFactoryHasAConversionServiceAndAConfigurationPropertyBindingConverterIsDefinedThenBindingToAnRsaKeySucceeds() { this.contextRunner - .withInitializer( - (context) -> context.getBeanFactory().setConversionService(new ApplicationConversionService())) - .withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class) - .withPropertyValues("jwt.public-key=classpath:public-key-location") - .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); + .withInitializer( + (context) -> context.getBeanFactory().setConversionService(new ApplicationConversionService())) + .withUserConfiguration(ConverterConfiguration.class, PropertiesConfiguration.class) + .withPropertyValues("jwt.public-key=classpath:public-key-location") + .run((context) -> assertThat(context.getBean(JwtProperties.class).getPublicKey()).isNotNull()); } @Configuration(proxyBeanMethods = false) @@ -243,7 +245,8 @@ class SecurityAutoConfigurationTests { @Bean SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { return http.securityMatcher("/**") - .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()).build(); + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) + .build(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java index 5f25d22b5b..e99120b3ee 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,13 +87,13 @@ class StaticResourceRequestTests { @Test void atLocationsFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.at(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } @Test void excludeFromSetWhenSetIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.resourceRequest.atCommonLocations().excluding(null)) - .withMessageContaining("Locations must not be null"); + .withMessageContaining("Locations must not be null"); } private RequestMatcherAssert assertMatcher(RequestMatcher matcher) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java index b65d3bdd1d..b0375a3afc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,8 +59,8 @@ import static org.mockito.Mockito.mock; class UserDetailsServiceAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestSecurityConfiguration.class) - .withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); + .withUserConfiguration(TestSecurityConfiguration.class) + .withConfiguration(AutoConfigurations.of(UserDetailsServiceAutoConfiguration.class)); @Test void testDefaultUsernamePassword(CapturedOutput output) { @@ -76,7 +76,7 @@ class UserDetailsServiceAutoConfigurationTests { this.contextRunner.withUserConfiguration(TestAuthenticationManagerConfiguration.class).run((context) -> { AuthenticationManager manager = context.getBean(AuthenticationManager.class); assertThat(manager) - .isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager); + .isEqualTo(context.getBean(TestAuthenticationManagerConfiguration.class).authenticationManager); assertThat(output).doesNotContain("Using generated security password: "); TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); assertThat(manager.authenticate(token)).isNotNull(); @@ -86,7 +86,7 @@ class UserDetailsServiceAutoConfigurationTests { @Test void defaultUserNotCreatedIfAuthenticationManagerResolverBeanPresent(CapturedOutput output) { this.contextRunner.withUserConfiguration(TestAuthenticationManagerResolverConfiguration.class) - .run((context) -> assertThat(output).doesNotContain("Using generated security password: ")); + .run((context) -> assertThat(output).doesNotContain("Using generated security password: ")); } @Test @@ -152,24 +152,24 @@ class UserDetailsServiceAutoConfigurationTests { @Test void userDetailsServiceWhenClientRegistrationRepositoryBeanPresent() { this.contextRunner.withUserConfiguration(TestConfigWithClientRegistrationRepository.class) - .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); + .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); } @Test void userDetailsServiceWhenRelyingPartyRegistrationRepositoryBeanPresent() { this.contextRunner - .withBean(RelyingPartyRegistrationRepository.class, - () -> mock(RelyingPartyRegistrationRepository.class)) - .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); + .withBean(RelyingPartyRegistrationRepository.class, () -> mock(RelyingPartyRegistrationRepository.class)) + .run(((context) -> assertThat(context).doesNotHaveBean(InMemoryUserDetailsManager.class))); } private void testPasswordEncoding(Class configClass, String providedPassword, String expectedPassword) { this.contextRunner.withUserConfiguration(configClass) - .withPropertyValues("spring.security.user.password=" + providedPassword).run(((context) -> { - InMemoryUserDetailsManager userDetailsService = context.getBean(InMemoryUserDetailsManager.class); - String password = userDetailsService.loadUserByUsername("user").getPassword(); - assertThat(password).isEqualTo(expectedPassword); - })); + .withPropertyValues("spring.security.user.password=" + providedPassword) + .run(((context) -> { + InMemoryUserDetailsManager userDetailsService = context.getBean(InMemoryUserDetailsManager.class); + String password = userDetailsService.loadUserByUsername("user").getPassword(); + assertThat(password).isEqualTo(expectedPassword); + })); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java index ba09a6ef1e..388f6c8398 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sendgrid/SendGridAutoConfigurationTests.java @@ -59,7 +59,7 @@ class SendGridAutoConfigurationTests { void autoConfigurationNotFiredWhenPropertiesNotSet() { loadContext(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(SendGrid.class)); + .isThrownBy(() -> this.context.getBean(SendGrid.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java index 3b78e05e73..81c3359c83 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/JdbcSessionDataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ class JdbcSessionDataSourceScriptDatabaseInitializerTests { DatabaseInitializationSettings settings = JdbcSessionDataSourceScriptDatabaseInitializer.getSettings(dataSource, properties); assertThat(settings.getSchemaLocations()) - .containsOnly("classpath:org/springframework/session/jdbc/schema-test.sql"); + .containsOnly("classpath:org/springframework/session/jdbc/schema-test.sql"); then(dataSource).shouldHaveNoInteractions(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java index 166f9cbc7f..4ad31f136f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationMongoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,48 +53,49 @@ class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionAutoConf @Container static final MongoDBContainer mongoDb = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withClassLoader(new FilteredClassLoader(ReactiveRedisSessionRepository.class)) - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class, MongoAutoConfiguration.class, - MongoDataAutoConfiguration.class, MongoReactiveAutoConfiguration.class, - MongoReactiveDataAutoConfiguration.class)); + .withClassLoader(new FilteredClassLoader(ReactiveRedisSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class, MongoAutoConfiguration.class, + MongoDataAutoConfiguration.class, MongoReactiveAutoConfiguration.class, + MongoReactiveDataAutoConfiguration.class)); @Test void defaultConfig() { this.contextRunner.withPropertyValues("spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .run(validateSpringSessionUsesMongo("sessions")); + .run(validateSpringSessionUsesMongo("sessions")); } @Test void defaultConfigWithCustomTimeout() { - this.contextRunner.withPropertyValues("spring.session.timeout=1m", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()).run((context) -> { - ReactiveMongoSessionRepository repository = validateSessionRepository(context, - ReactiveMongoSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", - Duration.ofMinutes(1)); - }); + this.contextRunner + .withPropertyValues("spring.session.timeout=1m", "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .run((context) -> { + ReactiveMongoSessionRepository repository = validateSessionRepository(context, + ReactiveMongoSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", Duration.ofMinutes(1)); + }); } @Test void defaultConfigWithCustomSessionTimeout() { - this.contextRunner.withPropertyValues("server.reactive.session.timeout=1m", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()).run((context) -> { - ReactiveMongoSessionRepository repository = validateSessionRepository(context, - ReactiveMongoSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", - Duration.ofMinutes(1)); - }); + this.contextRunner + .withPropertyValues("server.reactive.session.timeout=1m", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .run((context) -> { + ReactiveMongoSessionRepository repository = validateSessionRepository(context, + ReactiveMongoSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", Duration.ofMinutes(1)); + }); } @Test void mongoSessionStoreWithCustomizations() { this.contextRunner - .withPropertyValues("spring.session.mongodb.collection-name=foo", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .run(validateSpringSessionUsesMongo("foo")); + .withPropertyValues("spring.session.mongodb.collection-name=foo", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .run(validateSpringSessionUsesMongo("foo")); } @Test @@ -103,24 +104,24 @@ class ReactiveSessionAutoConfigurationMongoTests extends AbstractSessionAutoConf MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, MongoReactiveAutoConfiguration.class, MongoReactiveDataAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class); new ReactiveWebApplicationContextRunner().withConfiguration(autoConfigurations) - .withUserConfiguration(Config.class) - .withClassLoader(new FilteredClassLoader(ReactiveRedisSessionRepository.class)) - .withPropertyValues("server.reactive.session.cookie.name:JSESSIONID", - "server.reactive.session.cookie.domain:.example.com", - "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", - "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", - "server.reactive.session.cookie.same-site:strict", - "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) - .run(assertExchangeWithSession((exchange) -> { - List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); - assertThat(cookies).isNotEmpty(); - assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); - assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); - assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); - assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); - assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); - assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); - })); + .withUserConfiguration(Config.class) + .withClassLoader(new FilteredClassLoader(ReactiveRedisSessionRepository.class)) + .withPropertyValues("server.reactive.session.cookie.name:JSESSIONID", + "server.reactive.session.cookie.domain:.example.com", + "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", + "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", + "server.reactive.session.cookie.same-site:strict", + "spring.data.mongodb.uri=" + mongoDb.getReplicaSetUrl()) + .run(assertExchangeWithSession((exchange) -> { + List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); + assertThat(cookies).isNotEmpty(); + assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); + assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); + assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); + assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); + assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); + assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); + })); } private ContextConsumer validateSpringSessionUsesMongo( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java index 303d044f4a..0cb97f900e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/ReactiveSessionAutoConfigurationRedisTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,12 +53,13 @@ class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionAutoConf @Container public static RedisContainer redis = new RedisContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)); + .withStartupTimeout(Duration.ofMinutes(10)); protected final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withClassLoader(new FilteredClassLoader(ReactiveMongoSessionRepository.class)).withConfiguration( - AutoConfigurations.of(SessionAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class, - RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); + .withClassLoader(new FilteredClassLoader(ReactiveMongoSessionRepository.class)) + .withConfiguration( + AutoConfigurations.of(SessionAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class, + RedisAutoConfiguration.class, RedisReactiveAutoConfiguration.class)); @Test void defaultConfig() { @@ -94,28 +95,30 @@ class ReactiveSessionAutoConfigurationRedisTests extends AbstractSessionAutoConf @Test void redisSessionStoreWithCustomizations() { this.contextRunner - .withPropertyValues("spring.session.redis.namespace=foo", - "spring.session.redis.save-mode=on-get-attribute") - .run(validateSpringSessionUsesRedis("foo:", SaveMode.ON_GET_ATTRIBUTE)); + .withPropertyValues("spring.session.redis.namespace=foo", "spring.session.redis.save-mode=on-get-attribute") + .run(validateSpringSessionUsesRedis("foo:", SaveMode.ON_GET_ATTRIBUTE)); } @Test void sessionCookieConfigurationIsAppliedToAutoConfiguredWebSessionIdResolver() { - this.contextRunner.withUserConfiguration(Config.class).withPropertyValues( - "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort(), - "server.reactive.session.cookie.name:JSESSIONID", "server.reactive.session.cookie.domain:.example.com", - "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", - "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", - "server.reactive.session.cookie.same-site:strict").run(assertExchangeWithSession((exchange) -> { - List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); - assertThat(cookies).isNotEmpty(); - assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); - assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); - assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); - assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); - assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); - assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); - })); + this.contextRunner.withUserConfiguration(Config.class) + .withPropertyValues("spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort(), + "server.reactive.session.cookie.name:JSESSIONID", + "server.reactive.session.cookie.domain:.example.com", + "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", + "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", + "server.reactive.session.cookie.same-site:strict") + .run(assertExchangeWithSession((exchange) -> { + List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); + assertThat(cookies).isNotEmpty(); + assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); + assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); + assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); + assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); + assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); + assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); + })); } private ContextConsumer validateSpringSessionUsesRedis(String namespace, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java index f47ec20c17..556a38f8cc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationHazelcastTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,10 +49,10 @@ import static org.mockito.Mockito.mock; class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withClassLoader(new FilteredClassLoader(JdbcIndexedSessionRepository.class, - RedisIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)) - .withUserConfiguration(HazelcastConfiguration.class); + .withClassLoader(new FilteredClassLoader(JdbcIndexedSessionRepository.class, + RedisIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)) + .withUserConfiguration(HazelcastConfiguration.class); @Test void defaultConfig() { @@ -61,9 +61,10 @@ class SessionAutoConfigurationHazelcastTests extends AbstractSessionAutoConfigur @Test void hazelcastTakesPrecedenceOverMongo() { - this.contextRunner.withClassLoader( - new FilteredClassLoader(RedisIndexedSessionRepository.class, JdbcIndexedSessionRepository.class)) - .run(this::validateDefaultConfig); + this.contextRunner + .withClassLoader( + new FilteredClassLoader(RedisIndexedSessionRepository.class, JdbcIndexedSessionRepository.class)) + .run(this::validateDefaultConfig); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java index 621dbc73ca..d243398fd3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java @@ -64,12 +64,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, - MongoIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, - SessionAutoConfiguration.class)) - .withPropertyValues("spring.datasource.generate-unique-name=true"); + .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, + MongoIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, + SessionAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name=true"); @Test void defaultConfig() { @@ -79,7 +79,7 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration @Test void jdbcTakesPrecedenceOverMongoAndHazelcast() { this.contextRunner.withClassLoader(new FilteredClassLoader(RedisIndexedSessionRepository.class)) - .run(this::validateDefaultConfig); + .run(this::validateDefaultConfig); } private void validateDefaultConfig(AssertableWebApplicationContext context) { @@ -90,7 +90,7 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); assertThat(repository).hasFieldOrPropertyWithValue("cleanupCron", "0 * * * * *"); assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); + .isEqualTo(DatabaseInitializationMode.EMBEDDED); assertThat(context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")).isEmpty(); } @@ -110,9 +110,9 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.NEVER); - assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( - () -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); + .isEqualTo(DatabaseInitializationMode.NEVER); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); }); } @@ -127,15 +127,17 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration @Test void customTableName() { - this.contextRunner.withPropertyValues("spring.session.jdbc.table-name=FOO_BAR", - "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql").run((context) -> { - JdbcIndexedSessionRepository repository = validateSessionRepository(context, - JdbcIndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("tableName", "FOO_BAR"); - assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) - .isEqualTo(DatabaseInitializationMode.EMBEDDED); - assertThat(context.getBean(JdbcOperations.class).queryForList("select * from FOO_BAR")).isEmpty(); - }); + this.contextRunner + .withPropertyValues("spring.session.jdbc.table-name=FOO_BAR", + "spring.session.jdbc.schema=classpath:session/custom-schema-h2.sql") + .run((context) -> { + JdbcIndexedSessionRepository repository = validateSessionRepository(context, + JdbcIndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("tableName", "FOO_BAR"); + assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) + .isEqualTo(DatabaseInitializationMode.EMBEDDED); + assertThat(context.getBean(JdbcOperations.class).queryForList("select * from FOO_BAR")).isEmpty(); + }); } @Test @@ -174,9 +176,9 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration DataSource sessionDataSource = context.getBean("sessionDataSource", DataSource.class); assertThat(repository).extracting("jdbcOperations.dataSource").isEqualTo(sessionDataSource); assertThat(context.getBean(JdbcSessionDataSourceScriptDatabaseInitializer.class)) - .hasFieldOrPropertyWithValue("dataSource", sessionDataSource); - assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( - () -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); + .hasFieldOrPropertyWithValue("dataSource", sessionDataSource); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); }); } @@ -188,7 +190,7 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration assertThat(sessionRepositoryNames).isNotEmpty(); for (String sessionRepositoryName : sessionRepositoryNames) { assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) - .contains("jdbcSessionDataSourceScriptDatabaseInitializer"); + .contains("jdbcSessionDataSourceScriptDatabaseInitializer"); } }); } @@ -196,52 +198,50 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration @Test void sessionRepositoryBeansDependOnFlyway() { this.contextRunner.withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) - .withPropertyValues("spring.session.jdbc.initialize-schema=never").run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] sessionRepositoryNames = beanFactory - .getBeanNamesForType(JdbcIndexedSessionRepository.class); - assertThat(sessionRepositoryNames).isNotEmpty(); - for (String sessionRepositoryName : sessionRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) - .contains("flyway", "flywayInitializer"); - } - }); + .withPropertyValues("spring.session.jdbc.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] sessionRepositoryNames = beanFactory.getBeanNamesForType(JdbcIndexedSessionRepository.class); + assertThat(sessionRepositoryNames).isNotEmpty(); + for (String sessionRepositoryName : sessionRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()).contains("flyway", + "flywayInitializer"); + } + }); } @Test void sessionRepositoryBeansDependOnLiquibase() { this.contextRunner.withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) - .withPropertyValues("spring.session.jdbc.initialize-schema=never").run((context) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - String[] sessionRepositoryNames = beanFactory - .getBeanNamesForType(JdbcIndexedSessionRepository.class); - assertThat(sessionRepositoryNames).isNotEmpty(); - for (String sessionRepositoryName : sessionRepositoryNames) { - assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) - .contains("liquibase"); - } - }); + .withPropertyValues("spring.session.jdbc.initialize-schema=never") + .run((context) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + String[] sessionRepositoryNames = beanFactory.getBeanNamesForType(JdbcIndexedSessionRepository.class); + assertThat(sessionRepositoryNames).isNotEmpty(); + for (String sessionRepositoryName : sessionRepositoryNames) { + assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) + .contains("liquibase"); + } + }); } @Test void whenTheUserDefinesTheirOwnJdbcSessionDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomJdbcSessionDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) - .doesNotHaveBean("jdbcSessionDataSourceScriptDatabaseInitializer") - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) + .doesNotHaveBean("jdbcSessionDataSourceScriptDatabaseInitializer") + .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredJdbcSessionInitializerRemains() { this.contextRunner.withUserConfiguration(CustomDatabaseInitializerConfiguration.class) - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .run((context) -> assertThat(context) - .hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .run((context) -> assertThat(context).hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Test @@ -253,12 +253,13 @@ class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfiguration DO UPDATE SET ATTRIBUTE_BYTES = EXCLUDED.ATTRIBUTE_BYTES """; this.contextRunner.withUserConfiguration(CustomJdbcIndexedSessionRepositoryCustomizerConfiguration.class) - .withConfiguration(AutoConfigurations.of(JdbcSessionConfiguration.class)).run((context) -> { - JdbcIndexedSessionRepository repository = validateSessionRepository(context, - JdbcIndexedSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("createSessionAttributeQuery", - expectedCreateSessionAttributeQuery); - }); + .withConfiguration(AutoConfigurations.of(JdbcSessionConfiguration.class)) + .run((context) -> { + JdbcIndexedSessionRepository repository = validateSessionRepository(context, + JdbcIndexedSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("createSessionAttributeQuery", + expectedCreateSessionAttributeQuery); + }); } @Configuration diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java index de70740eb2..6af94eb574 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationMongoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,14 +49,14 @@ class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfiguratio @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, - JdbcIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) - .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, - SessionAutoConfiguration.class)) - .withPropertyValues("spring.data.mongodb.uri=" + mongoDB.getReplicaSetUrl()); + .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, + JdbcIndexedSessionRepository.class, RedisIndexedSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class, + SessionAutoConfiguration.class)) + .withPropertyValues("spring.data.mongodb.uri=" + mongoDB.getReplicaSetUrl()); @Test void defaultConfig() { @@ -66,13 +66,13 @@ class SessionAutoConfigurationMongoTests extends AbstractSessionAutoConfiguratio @Test void defaultConfigWithCustomTimeout() { this.contextRunner.withPropertyValues("spring.session.timeout=1m") - .run(validateSpringSessionUsesMongo("sessions", Duration.ofMinutes(1))); + .run(validateSpringSessionUsesMongo("sessions", Duration.ofMinutes(1))); } @Test void mongoSessionStoreWithCustomizations() { this.contextRunner.withPropertyValues("spring.session.mongodb.collection-name=foo") - .run(validateSpringSessionUsesMongo("foo")); + .run(validateSpringSessionUsesMongo("foo")); } private ContextConsumer validateSpringSessionUsesMongo(String collectionName) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java index 4d30ea6dde..781b388fff 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationRedisTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,113 +58,110 @@ class SessionAutoConfigurationRedisTests extends AbstractSessionAutoConfiguratio @Container public static RedisContainer redis = new RedisContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(10)); + .withStartupTimeout(Duration.ofMinutes(10)); protected final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, - JdbcIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withClassLoader(new FilteredClassLoader(HazelcastIndexedSessionRepository.class, + JdbcIndexedSessionRepository.class, MongoIndexedSessionRepository.class)) + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test void defaultConfig() { this.contextRunner - .withPropertyValues("spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .run(validateSpringSessionUsesDefaultRedis("spring:session:", FlushMode.ON_SAVE, - SaveMode.ON_SET_ATTRIBUTE)); + .withPropertyValues("spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort()) + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run(validateSpringSessionUsesDefaultRedis("spring:session:", FlushMode.ON_SAVE, + SaveMode.ON_SET_ATTRIBUTE)); } @Test void invalidConfigurationPropertyValueWhenDefaultConfigIsUsedWithCustomCronCleanup() { this.contextRunner.withPropertyValues("spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort(), "spring.session.redis.cleanup-cron=0 0 * * * *") - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseExactlyInstanceOf(InvalidConfigurationPropertyValueException.class); - }); + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseExactlyInstanceOf(InvalidConfigurationPropertyValueException.class); + }); } @Test void redisTakesPrecedenceMultipleImplementations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort()) - .run(validateSpringSessionUsesDefaultRedis("spring:session:", FlushMode.ON_SAVE, - SaveMode.ON_SET_ATTRIBUTE)); + .withPropertyValues("spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort()) + .run(validateSpringSessionUsesDefaultRedis("spring:session:", FlushMode.ON_SAVE, + SaveMode.ON_SET_ATTRIBUTE)); } @Test void defaultConfigWithCustomTimeout() { this.contextRunner - .withPropertyValues("spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort(), "spring.session.timeout=1m") - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)).run((context) -> { - RedisSessionRepository repository = validateSessionRepository(context, - RedisSessionRepository.class); - assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", - Duration.ofMinutes(1)); - }); + .withPropertyValues("spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort(), "spring.session.timeout=1m") + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run((context) -> { + RedisSessionRepository repository = validateSessionRepository(context, RedisSessionRepository.class); + assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", Duration.ofMinutes(1)); + }); } @Test void defaultRedisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", - "spring.session.redis.save-mode=on-get-attribute", "spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort()) - .run(validateSpringSessionUsesDefaultRedis("foo:", FlushMode.IMMEDIATE, SaveMode.ON_GET_ATTRIBUTE)); + .withPropertyValues("spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", + "spring.session.redis.save-mode=on-get-attribute", "spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort()) + .run(validateSpringSessionUsesDefaultRedis("foo:", FlushMode.IMMEDIATE, SaveMode.ON_GET_ATTRIBUTE)); } @Test void indexedRedisSessionDefaultConfig() { - this.contextRunner.withPropertyValues("spring.session.redis.repository-type=indexed", - "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) - .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .run(validateSpringSessionUsesIndexedRedis("spring:session:", FlushMode.ON_SAVE, - SaveMode.ON_SET_ATTRIBUTE, "0 * * * * *")); + this.contextRunner + .withPropertyValues("spring.session.redis.repository-type=indexed", + "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) + .withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) + .run(validateSpringSessionUsesIndexedRedis("spring:session:", FlushMode.ON_SAVE, SaveMode.ON_SET_ATTRIBUTE, + "0 * * * * *")); } @Test void indexedRedisSessionStoreWithCustomizations() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.redis.repository-type=indexed", - "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate", - "spring.session.redis.save-mode=on-get-attribute", - "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort()) - .run(validateSpringSessionUsesIndexedRedis("foo:", FlushMode.IMMEDIATE, SaveMode.ON_GET_ATTRIBUTE, - "0 0 12 * * *")); + .withPropertyValues("spring.session.redis.repository-type=indexed", "spring.session.redis.namespace=foo", + "spring.session.redis.flush-mode=immediate", "spring.session.redis.save-mode=on-get-attribute", + "spring.session.redis.cleanup-cron=0 0 12 * * *", "spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort()) + .run(validateSpringSessionUsesIndexedRedis("foo:", FlushMode.IMMEDIATE, SaveMode.ON_GET_ATTRIBUTE, + "0 0 12 * * *")); } @Test void indexedRedisSessionWithConfigureActionNone() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.redis.repository-type=indexed", - "spring.session.redis.configure-action=none", "spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort()) - .run(validateStrategy(ConfigureRedisAction.NO_OP.getClass())); + .withPropertyValues("spring.session.redis.repository-type=indexed", + "spring.session.redis.configure-action=none", "spring.data.redis.host=" + redis.getHost(), + "spring.data.redis.port=" + redis.getFirstMappedPort()) + .run(validateStrategy(ConfigureRedisAction.NO_OP.getClass())); } @Test void indexedRedisSessionWithDefaultConfigureActionNone() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withPropertyValues("spring.session.redis.repository-type=indexed", - "spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort()) - .run(validateStrategy(ConfigureNotifyKeyspaceEventsAction.class, - entry("notify-keyspace-events", "gxE"))); + .withPropertyValues("spring.session.redis.repository-type=indexed", + "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) + .run(validateStrategy(ConfigureNotifyKeyspaceEventsAction.class, entry("notify-keyspace-events", "gxE"))); } @Test void indexedRedisSessionWithCustomConfigureRedisActionBean() { this.contextRunner.withConfiguration(AutoConfigurations.of(RedisAutoConfiguration.class)) - .withUserConfiguration(MaxEntriesRedisAction.class) - .withPropertyValues("spring.session.redis.repository-type=indexed", - "spring.data.redis.host=" + redis.getHost(), - "spring.data.redis.port=" + redis.getFirstMappedPort()) - .run(validateStrategy(MaxEntriesRedisAction.class, entry("set-max-intset-entries", "1024"))); + .withUserConfiguration(MaxEntriesRedisAction.class) + .withPropertyValues("spring.session.redis.repository-type=indexed", + "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) + .run(validateStrategy(MaxEntriesRedisAction.class, entry("set-max-intset-entries", "1024"))); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java index 03773dd0ee..1f85c0e4b8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -65,15 +65,15 @@ import static org.mockito.Mockito.mock; class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test void autoConfigurationDisabledIfNoImplementationMatches() { this.contextRunner - .withClassLoader(new FilteredClassLoader(RedisIndexedSessionRepository.class, - HazelcastIndexedSessionRepository.class, JdbcIndexedSessionRepository.class, - MongoIndexedSessionRepository.class)) - .run((context) -> assertThat(context).doesNotHaveBean(SessionRepository.class)); + .withClassLoader(new FilteredClassLoader(RedisIndexedSessionRepository.class, + HazelcastIndexedSessionRepository.class, JdbcIndexedSessionRepository.class, + MongoIndexedSessionRepository.class)) + .run((context) -> assertThat(context).doesNotHaveBean(SessionRepository.class)); } @Test @@ -87,7 +87,7 @@ class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTest @Test void backOffIfReactiveSessionRepositoryIsPresent() { ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); contextRunner.withUserConfiguration(ReactiveSessionRepositoryConfiguration.class).run((context) -> { ReactiveMapSessionRepository repository = validateSessionRepository(context, ReactiveMapSessionRepository.class); @@ -101,69 +101,73 @@ class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTest FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); assertThat(registration.getFilter()).isSameAs(context.getBean(SessionRepositoryFilter.class)); assertThat(registration) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); + .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST); }); } @Test void filterOrderCanBeCustomizedWithCustomStore() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.servlet.filter-order=123").run((context) -> { - FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); - assertThat(registration.getOrder()).isEqualTo(123); - }); + .withPropertyValues("spring.session.servlet.filter-order=123") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration.getOrder()).isEqualTo(123); + }); } @Test void filterDispatcherTypesCanBeCustomized() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.servlet.filter-dispatcher-types=error, request").run((context) -> { - FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); - assertThat(registration) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .containsOnly(DispatcherType.ERROR, DispatcherType.REQUEST); - }); + .withPropertyValues("spring.session.servlet.filter-dispatcher-types=error, request") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration) + .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .containsOnly(DispatcherType.ERROR, DispatcherType.REQUEST); + }); } @Test void emptyFilterDispatcherTypesDoNotThrowException() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("spring.session.servlet.filter-dispatcher-types=").run((context) -> { - FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); - assertThat(registration) - .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) - .isEmpty(); - }); + .withPropertyValues("spring.session.servlet.filter-dispatcher-types=") + .run((context) -> { + FilterRegistrationBean registration = context.getBean(FilterRegistrationBean.class); + assertThat(registration) + .extracting("dispatcherTypes", InstanceOfAssertFactories.iterable(DispatcherType.class)) + .isEmpty(); + }); } @Test void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("server.servlet.session.cookie.name=sid", - "server.servlet.session.cookie.domain=spring", "server.servlet.session.cookie.path=/test", - "server.servlet.session.cookie.httpOnly=false", "server.servlet.session.cookie.secure=false", - "server.servlet.session.cookie.maxAge=10s", "server.servlet.session.cookie.sameSite=strict") - .run((context) -> { - DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieName", "sid"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("domainName", "spring"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookiePath", "/test"); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useHttpOnlyCookie", false); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useSecureCookie", false); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieMaxAge", 10); - assertThat(cookieSerializer).hasFieldOrPropertyWithValue("sameSite", "Strict"); - }); + .withPropertyValues("server.servlet.session.cookie.name=sid", "server.servlet.session.cookie.domain=spring", + "server.servlet.session.cookie.path=/test", "server.servlet.session.cookie.httpOnly=false", + "server.servlet.session.cookie.secure=false", "server.servlet.session.cookie.maxAge=10s", + "server.servlet.session.cookie.sameSite=strict") + .run((context) -> { + DefaultCookieSerializer cookieSerializer = context.getBean(DefaultCookieSerializer.class); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieName", "sid"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("domainName", "spring"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookiePath", "/test"); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useHttpOnlyCookie", false); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("useSecureCookie", false); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("cookieMaxAge", 10); + assertThat(cookieSerializer).hasFieldOrPropertyWithValue("sameSite", "Strict"); + }); } @Test void autoConfiguredCookieSerializerIsUsedBySessionRepositoryFilter() { this.contextRunner.withUserConfiguration(SessionRepositoryConfiguration.class) - .withPropertyValues("server.port=0").run((context) -> { - SessionRepositoryFilter filter = context.getBean(SessionRepositoryFilter.class); - assertThat(filter).extracting("httpSessionIdResolver.cookieSerializer") - .isSameAs(context.getBean(DefaultCookieSerializer.class)); - }); + .withPropertyValues("server.port=0") + .run((context) -> { + SessionRepositoryFilter filter = context.getBean(SessionRepositoryFilter.class); + assertThat(filter).extracting("httpSessionIdResolver.cookieSerializer") + .isSameAs(context.getBean(DefaultCookieSerializer.class)); + }); } @Test @@ -177,19 +181,19 @@ class SessionAutoConfigurationTests extends AbstractSessionAutoConfigurationTest @Test void cookiesSerializerIsAutoConfiguredWhenUserConfiguresCookieHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedCookieHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isNotEmpty()); + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isNotEmpty()); } @Test void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresHeaderHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedHeaderHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test void autoConfiguredCookieSerializerBacksOffWhenUserConfiguresCustomHttpSessionIdResolver() { this.contextRunner.withUserConfiguration(UserProvidedCustomHttpSessionStrategyConfiguration.class) - .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); + .run((context) -> assertThat(context.getBeansOfType(DefaultCookieSerializer.class)).isEmpty()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java index 7f8768afce..956afde4de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationWithoutSecurityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class SessionAutoConfigurationWithoutSecurityTests extends AbstractSessionAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)); @Test void sessionCookieConfigurationIsAppliedToAutoConfiguredCookieSerializer() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java index 8378fb2b57..fd44e19a44 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/OnDatabaseInitializationConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertyNoSetMatches() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.another", "noise")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.another", "noise")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -46,7 +46,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToAlwaysMatches() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=always")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=always")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -54,7 +54,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToEmbeddedMatches() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -62,7 +62,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToNeverDoesNotMatch() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=never")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=never")), null); assertThat(outcome.isMatch()).isFalse(); } @@ -70,7 +70,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeWithPropertySetToEmptyStringIsIgnored() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode")), null); assertThat(outcome.isMatch()).isTrue(); } @@ -79,7 +79,7 @@ class OnDatabaseInitializationConditionTests { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode", "test.schema-mode", "test.init-schema-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-schema-mode=embedded")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-schema-mode=embedded")), null); assertThat(outcome.isMatch()).isTrue(); assertThat(outcome.getMessage()).isEqualTo("TestDatabase Initialization test.init-schema-mode is EMBEDDED"); } @@ -88,7 +88,7 @@ class OnDatabaseInitializationConditionTests { void getMatchOutcomeHasDedicatedDescription() { OnDatabaseInitializationCondition condition = new OnDatabaseInitializationCondition("Test", "test.init-mode"); ConditionOutcome outcome = condition - .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); + .getMatchOutcome(mockConditionContext(TestPropertyValues.of("test.init-mode=embedded")), null); assertThat(outcome.getMessage()).isEqualTo("TestDatabase Initialization test.init-mode is EMBEDDED"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java index e9b3fbc29f..b4e02caa79 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/sql/init/SqlInitializationAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,106 +48,111 @@ import static org.assertj.core.api.Assertions.assertThat; class SqlInitializationAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)).withPropertyValues( - "spring.datasource.generate-unique-name:true", "spring.r2dbc.generate-unique-name:true"); + .withConfiguration(AutoConfigurations.of(SqlInitializationAutoConfiguration.class)) + .withPropertyValues("spring.datasource.generate-unique-name:true", "spring.r2dbc.generate-unique-name:true"); @Test void whenNoDataSourceOrConnectionFactoryIsAvailableThenAutoConfigurationBacksOff() { this.contextRunner - .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); } @Test void whenConnectionFactoryIsAvailableThenR2dbcInitializerIsAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(R2dbcScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).hasSingleBean(R2dbcScriptDatabaseInitializer.class)); } @Test void whenConnectionFactoryIsAvailableAndModeIsNeverThenInitializerIsNotAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withInitializer(ConditionEvaluationReportLoggingListener.forLogLevel(LogLevel.INFO)) - .withPropertyValues("spring.sql.init.mode:never") - .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); + .withInitializer(ConditionEvaluationReportLoggingListener.forLogLevel(LogLevel.INFO)) + .withPropertyValues("spring.sql.init.mode:never") + .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); } @Test void whenDataSourceIsAvailableThenDataSourceInitializerIsAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(DataSourceScriptDatabaseInitializer.class)); + .run((context) -> assertThat(context).hasSingleBean(DataSourceScriptDatabaseInitializer.class)); } @Test void whenDataSourceIsAvailableAndModeIsNeverThenThenInitializerIsNotAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withPropertyValues("spring.sql.init.mode:never") - .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); + .withPropertyValues("spring.sql.init.mode:never") + .run((context) -> assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class)); } @Test void whenDataSourceAndConnectionFactoryAreAvailableThenOnlyR2dbcInitializerIsAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(DataSourceAutoConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) - .hasSingleBean(DataSource.class).hasSingleBean(R2dbcScriptDatabaseInitializer.class) - .doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); + .withUserConfiguration(DataSourceAutoConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(ConnectionFactory.class) + .hasSingleBean(DataSource.class) + .hasSingleBean(R2dbcScriptDatabaseInitializer.class) + .doesNotHaveBean(DataSourceScriptDatabaseInitializer.class)); } @Test void whenAnSqlInitializerIsDefinedThenInitializerIsNotAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(DataSourceAutoConfiguration.class, SqlDatabaseInitializerConfiguration.class) - .run((context) -> assertThat(context).hasSingleBean(AbstractScriptDatabaseInitializer.class) - .hasBean("customInitializer")); + .withUserConfiguration(DataSourceAutoConfiguration.class, SqlDatabaseInitializerConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(AbstractScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Test void whenAnInitializerIsDefinedThenSqlInitializerIsStillAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withUserConfiguration(DatabaseInitializerConfiguration.class).run((context) -> assertThat(context) - .hasSingleBean(SqlDataSourceScriptDatabaseInitializer.class).hasBean("customInitializer")); + .withUserConfiguration(DatabaseInitializerConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(SqlDataSourceScriptDatabaseInitializer.class) + .hasBean("customInitializer")); } @Test void whenBeanIsAnnotatedAsDependingOnDatabaseInitializationThenItDependsOnR2dbcScriptDatabaseInitializer() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition( + .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory() + .getBeanDefinition( "sqlInitializationAutoConfigurationTests.DependsOnInitializedDatabaseConfiguration"); - assertThat(beanDefinition.getDependsOn()) - .containsExactlyInAnyOrder("r2dbcScriptDatabaseInitializer"); - }); + assertThat(beanDefinition.getDependsOn()).containsExactlyInAnyOrder("r2dbcScriptDatabaseInitializer"); + }); } @Test void whenBeanIsAnnotatedAsDependingOnDatabaseInitializationThenItDependsOnDataSourceScriptDatabaseInitializer() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class).run((context) -> { - BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition( + .withUserConfiguration(DependsOnInitializedDatabaseConfiguration.class) + .run((context) -> { + BeanDefinition beanDefinition = context.getBeanFactory() + .getBeanDefinition( "sqlInitializationAutoConfigurationTests.DependsOnInitializedDatabaseConfiguration"); - assertThat(beanDefinition.getDependsOn()) - .containsExactlyInAnyOrder("dataSourceScriptDatabaseInitializer"); - }); + assertThat(beanDefinition.getDependsOn()) + .containsExactlyInAnyOrder("dataSourceScriptDatabaseInitializer"); + }); } @Test void whenADataSourceIsAvailableAndSpringJdbcIsNotThenAutoConfigurationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)).run((context) -> { - assertThat(context).hasSingleBean(DataSource.class); - assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); - }); + .withClassLoader(new FilteredClassLoader(DatabasePopulator.class)) + .run((context) -> { + assertThat(context).hasSingleBean(DataSource.class); + assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); + }); } @Test void whenAConnectionFactoryIsAvailableAndSpringR2dbcIsNotThenAutoConfigurationBacksOff() { this.contextRunner.withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) - .withClassLoader( - new FilteredClassLoader(org.springframework.r2dbc.connection.init.DatabasePopulator.class)) - .run((context) -> { - assertThat(context).hasSingleBean(ConnectionFactory.class); - assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); - }); + .withClassLoader(new FilteredClassLoader(org.springframework.r2dbc.connection.init.DatabasePopulator.class)) + .run((context) -> { + assertThat(context).hasSingleBean(ConnectionFactory.class); + assertThat(context).doesNotHaveBean(AbstractScriptDatabaseInitializer.class); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java index f9464241f9..c1d0507903 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskExecutionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,25 +56,27 @@ import static org.mockito.Mockito.mock; class TaskExecutionAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TaskExecutionAutoConfiguration.class)); @Test void taskExecutorBuilderShouldApplyCustomSettings() { - this.contextRunner.withPropertyValues("spring.task.execution.pool.queue-capacity=10", - "spring.task.execution.pool.core-size=2", "spring.task.execution.pool.max-size=4", - "spring.task.execution.pool.allow-core-thread-timeout=true", "spring.task.execution.pool.keep-alive=5s", - "spring.task.execution.shutdown.await-termination=true", - "spring.task.execution.shutdown.await-termination-period=30s", - "spring.task.execution.thread-name-prefix=mytest-").run(assertTaskExecutor((taskExecutor) -> { - assertThat(taskExecutor).hasFieldOrPropertyWithValue("queueCapacity", 10); - assertThat(taskExecutor.getCorePoolSize()).isEqualTo(2); - assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(4); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true); - assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(5); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); - assertThat(taskExecutor.getThreadNamePrefix()).isEqualTo("mytest-"); - })); + this.contextRunner + .withPropertyValues("spring.task.execution.pool.queue-capacity=10", + "spring.task.execution.pool.core-size=2", "spring.task.execution.pool.max-size=4", + "spring.task.execution.pool.allow-core-thread-timeout=true", + "spring.task.execution.pool.keep-alive=5s", "spring.task.execution.shutdown.await-termination=true", + "spring.task.execution.shutdown.await-termination-period=30s", + "spring.task.execution.thread-name-prefix=mytest-") + .run(assertTaskExecutor((taskExecutor) -> { + assertThat(taskExecutor).hasFieldOrPropertyWithValue("queueCapacity", 10); + assertThat(taskExecutor.getCorePoolSize()).isEqualTo(2); + assertThat(taskExecutor.getMaxPoolSize()).isEqualTo(4); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("allowCoreThreadTimeOut", true); + assertThat(taskExecutor.getKeepAliveSeconds()).isEqualTo(5); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); + assertThat(taskExecutor.getThreadNamePrefix()).isEqualTo("mytest-"); + })); } @Test @@ -82,7 +84,7 @@ class TaskExecutionAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomTaskExecutorBuilderConfig.class).run((context) -> { assertThat(context).hasSingleBean(TaskExecutorBuilder.class); assertThat(context.getBean(TaskExecutorBuilder.class)) - .isSameAs(context.getBean(CustomTaskExecutorBuilderConfig.class).taskExecutorBuilder); + .isSameAs(context.getBean(CustomTaskExecutorBuilderConfig.class).taskExecutorBuilder); }); } @@ -99,8 +101,9 @@ class TaskExecutionAutoConfigurationTests { void taskExecutorAutoConfiguredIsLazy() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Executor.class).hasBean("applicationTaskExecutor"); - BeanDefinition beanDefinition = context.getSourceApplicationContext().getBeanFactory() - .getBeanDefinition("applicationTaskExecutor"); + BeanDefinition beanDefinition = context.getSourceApplicationContext() + .getBeanFactory() + .getBeanDefinition("applicationTaskExecutor"); assertThat(beanDefinition.isLazyInit()).isTrue(); assertThat(context).getBean("applicationTaskExecutor").isInstanceOf(ThreadPoolTaskExecutor.class); }); @@ -126,24 +129,25 @@ class TaskExecutionAutoConfigurationTests { @Test void enableAsyncUsesAutoConfiguredOneByDefault() { this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") - .withUserConfiguration(AsyncConfiguration.class, TestBean.class).run((context) -> { - assertThat(context).hasSingleBean(TaskExecutor.class); - TestBean bean = context.getBean(TestBean.class); - String text = bean.echo("something").get(); - assertThat(text).contains("task-test-").contains("something"); - }); + .withUserConfiguration(AsyncConfiguration.class, TestBean.class) + .run((context) -> { + assertThat(context).hasSingleBean(TaskExecutor.class); + TestBean bean = context.getBean(TestBean.class); + String text = bean.echo("something").get(); + assertThat(text).contains("task-test-").contains("something"); + }); } @Test void enableAsyncUsesAutoConfiguredOneByDefaultEvenThoughSchedulingIsConfigured() { this.contextRunner.withPropertyValues("spring.task.execution.thread-name-prefix=task-test-") - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) - .withUserConfiguration(AsyncConfiguration.class, SchedulingConfiguration.class, TestBean.class) - .run((context) -> { - TestBean bean = context.getBean(TestBean.class); - String text = bean.echo("something").get(); - assertThat(text).contains("task-test-").contains("something"); - }); + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) + .withUserConfiguration(AsyncConfiguration.class, SchedulingConfiguration.class, TestBean.class) + .run((context) -> { + TestBean bean = context.getBean(TestBean.class); + String text = bean.echo("something").get(); + assertThat(text).contains("task-test-").contains("something"); + }); } private ContextConsumer assertTaskExecutor( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java index e437068987..990e8cb6db 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,8 +53,8 @@ import static org.assertj.core.api.Assertions.assertThat; class TaskSchedulingAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)); + .withUserConfiguration(TestConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)); @Test void noSchedulingDoesNotExposeTaskScheduler() { @@ -63,89 +63,91 @@ class TaskSchedulingAutoConfigurationTests { @Test void noSchedulingDoesNotExposeScheduledBeanLazyInitializationExcludeFilter() { - this.contextRunner.run( - (context) -> assertThat(context).doesNotHaveBean(ScheduledBeanLazyInitializationExcludeFilter.class)); + this.contextRunner + .run((context) -> assertThat(context).doesNotHaveBean(ScheduledBeanLazyInitializationExcludeFilter.class)); } @Test void enableSchedulingWithNoTaskExecutorAutoConfiguresOne() { this.contextRunner - .withPropertyValues("spring.task.scheduling.shutdown.await-termination=true", - "spring.task.scheduling.shutdown.await-termination-period=30s", - "spring.task.scheduling.thread-name-prefix=scheduling-test-") - .withUserConfiguration(SchedulingConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(TaskExecutor.class); - TaskExecutor taskExecutor = context.getBean(TaskExecutor.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); - assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); - assertThat(bean.threadNames).allMatch((name) -> name.contains("scheduling-test-")); - }); + .withPropertyValues("spring.task.scheduling.shutdown.await-termination=true", + "spring.task.scheduling.shutdown.await-termination-period=30s", + "spring.task.scheduling.thread-name-prefix=scheduling-test-") + .withUserConfiguration(SchedulingConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(TaskExecutor.class); + TaskExecutor taskExecutor = context.getBean(TaskExecutor.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("waitForTasksToCompleteOnShutdown", true); + assertThat(taskExecutor).hasFieldOrPropertyWithValue("awaitTerminationMillis", 30000L); + assertThat(bean.threadNames).allMatch((name) -> name.contains("scheduling-test-")); + }); } @Test void enableSchedulingWithNoTaskExecutorAppliesCustomizers() { this.contextRunner.withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") - .withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerCustomizerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TaskExecutor.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).allMatch((name) -> name.contains("customized-scheduler-")); - }); + .withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerCustomizerConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(TaskExecutor.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).allMatch((name) -> name.contains("customized-scheduler-")); + }); } @Test void enableSchedulingWithExistingTaskSchedulerBacksOff() { this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, TaskSchedulerConfiguration.class) - .run((context) -> { - assertThat(context).hasSingleBean(TaskScheduler.class); - assertThat(context.getBean(TaskScheduler.class)).isInstanceOf(TestTaskScheduler.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).containsExactly("test-1"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(TaskScheduler.class); + assertThat(context.getBean(TaskScheduler.class)).isInstanceOf(TestTaskScheduler.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).containsExactly("test-1"); + }); } @Test void enableSchedulingWithExistingScheduledExecutorServiceBacksOff() { this.contextRunner - .withUserConfiguration(SchedulingConfiguration.class, ScheduledExecutorServiceConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(TaskScheduler.class); - assertThat(context).hasSingleBean(ScheduledExecutorService.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).allMatch((name) -> name.contains("pool-")); - }); + .withUserConfiguration(SchedulingConfiguration.class, ScheduledExecutorServiceConfiguration.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(TaskScheduler.class); + assertThat(context).hasSingleBean(ScheduledExecutorService.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).allMatch((name) -> name.contains("pool-")); + }); } @Test void enableSchedulingWithConfigurerBacksOff() { this.contextRunner.withUserConfiguration(SchedulingConfiguration.class, SchedulingConfigurerConfiguration.class) - .run((context) -> { - assertThat(context).doesNotHaveBean(TaskScheduler.class); - TestBean bean = context.getBean(TestBean.class); - assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); - assertThat(bean.threadNames).containsExactly("test-1"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean(TaskScheduler.class); + TestBean bean = context.getBean(TestBean.class); + assertThat(bean.latch.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(bean.threadNames).containsExactly("test-1"); + }); } @Test void enableSchedulingWithLazyInitializationInvokeScheduledMethods() { List threadNames = new ArrayList<>(); new ApplicationContextRunner() - .withInitializer((context) -> context - .addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) - .withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") - .withBean(LazyTestBean.class, () -> new LazyTestBean(threadNames)) - .withUserConfiguration(SchedulingConfiguration.class) - .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)).run((context) -> { - // No lazy lookup. - Awaitility.waitAtMost(Duration.ofSeconds(3)).until(() -> !threadNames.isEmpty()); - assertThat(threadNames).allMatch((name) -> name.contains("scheduling-test-")); - }); + .withInitializer( + (context) -> context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor())) + .withPropertyValues("spring.task.scheduling.thread-name-prefix=scheduling-test-") + .withBean(LazyTestBean.class, () -> new LazyTestBean(threadNames)) + .withUserConfiguration(SchedulingConfiguration.class) + .withConfiguration(AutoConfigurations.of(TaskSchedulingAutoConfiguration.class)) + .run((context) -> { + // No lazy lookup. + Awaitility.waitAtMost(Duration.ofSeconds(3)).until(() -> !threadNames.isEmpty()); + assertThat(threadNames).allMatch((name) -> name.contains("scheduling-test-")); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java index ffb7e693a7..48cc8cb8c5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,8 +66,8 @@ class TemplateAvailabilityProvidersTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TemplateAvailabilityProviders((ApplicationContext) null)) - .withMessageContaining("ClassLoader must not be null"); + .isThrownBy(() -> new TemplateAvailabilityProviders((ApplicationContext) null)) + .withMessageContaining("ClassLoader must not be null"); } @Test @@ -82,7 +82,7 @@ class TemplateAvailabilityProvidersTests { @Test void createWhenClassLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TemplateAvailabilityProviders((ClassLoader) null)) - .withMessageContaining("ClassLoader must not be null"); + .withMessageContaining("ClassLoader must not be null"); } @Test @@ -94,8 +94,8 @@ class TemplateAvailabilityProvidersTests { @Test void createWhenProvidersIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TemplateAvailabilityProviders((Collection) null)) - .withMessageContaining("Providers must not be null"); + .isThrownBy(() -> new TemplateAvailabilityProviders((Collection) null)) + .withMessageContaining("Providers must not be null"); } @Test @@ -108,36 +108,35 @@ class TemplateAvailabilityProvidersTests { @Test void getProviderWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.providers.getProvider(this.view, null)) - .withMessageContaining("ApplicationContext must not be null"); + .withMessageContaining("ApplicationContext must not be null"); } @Test void getProviderWhenViewIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader)) - .withMessageContaining("View must not be null"); + .isThrownBy(() -> this.providers.getProvider(null, this.environment, this.classLoader, this.resourceLoader)) + .withMessageContaining("View must not be null"); } @Test void getProviderWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> this.providers.getProvider(this.view, null, this.classLoader, this.resourceLoader)) + .withMessageContaining("Environment must not be null"); } @Test void getProviderWhenClassLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, null, this.resourceLoader)) - .withMessageContaining("ClassLoader must not be null"); + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, null, this.resourceLoader)) + .withMessageContaining("ClassLoader must not be null"); } @Test void getProviderWhenResourceLoaderIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, this.classLoader, null)) - .withMessageContaining("ResourceLoader must not be null"); + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, this.classLoader, null)) + .withMessageContaining("ResourceLoader must not be null"); } @Test @@ -145,14 +144,14 @@ class TemplateAvailabilityProvidersTests { TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); assertThat(found).isNull(); - then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should() + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test void getProviderWhenMatchShouldReturnProvider() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) - .willReturn(true); + .willReturn(true); TemplateAvailabilityProvider found = this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); assertThat(found).isSameAs(this.provider); @@ -162,30 +161,30 @@ class TemplateAvailabilityProvidersTests { @Test void getProviderShouldCacheMatchResult() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) - .willReturn(true); + .willReturn(true); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); - then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should() + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test void getProviderShouldCacheNoMatchResult() { this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); - then(this.provider).should().isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should() + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } @Test void getProviderWhenCacheDisabledShouldNotUseCache() { given(this.provider.isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader)) - .willReturn(true); + .willReturn(true); this.environment.setProperty("spring.template.provider.cache", "false"); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); this.providers.getProvider(this.view, this.environment, this.classLoader, this.resourceLoader); - then(this.provider).should(times(2)).isTemplateAvailable(this.view, this.environment, this.classLoader, - this.resourceLoader); + then(this.provider).should(times(2)) + .isTemplateAvailable(this.view, this.environment, this.classLoader, this.resourceLoader); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateRuntimeHintsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateRuntimeHintsTests.java index c98dd13f31..28a41cbd01 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; class TemplateRuntimeHintsTests { private static final Predicate TEST_PREDICATE = RuntimeHintsPredicates.resource() - .forResource("templates/something/hello.html"); + .forResource("templates/something/hello.html"); @Test void templateRuntimeHintsIsRegistered() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java index 77b6baa929..6d17a0ef75 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafReactiveAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,7 +67,7 @@ class ThymeleafReactiveAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); @Test void createFromConfigClass() { @@ -92,98 +92,99 @@ class ThymeleafReactiveAutoConfigurationTests { @Test void defaultMediaTypes() { - this.contextRunner.run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) - .containsExactly(MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML, - MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_RSS_XML, - MediaType.APPLICATION_ATOM_XML, new MediaType("application", "javascript"), - new MediaType("application", "ecmascript"), new MediaType("text", "javascript"), - new MediaType("text", "ecmascript"), MediaType.APPLICATION_JSON, - new MediaType("text", "css"), MediaType.TEXT_PLAIN, MediaType.TEXT_EVENT_STREAM)); + this.contextRunner + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) + .containsExactly(MediaType.TEXT_HTML, MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML, + MediaType.TEXT_XML, MediaType.APPLICATION_RSS_XML, MediaType.APPLICATION_ATOM_XML, + new MediaType("application", "javascript"), new MediaType("application", "ecmascript"), + new MediaType("text", "javascript"), new MediaType("text", "ecmascript"), + MediaType.APPLICATION_JSON, new MediaType("text", "css"), MediaType.TEXT_PLAIN, + MediaType.TEXT_EVENT_STREAM)); } @Test void overrideMediaTypes() { - this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.media-types:text/html,text/plain").run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) - .containsExactly(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN)); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.media-types:text/html,text/plain") + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getSupportedMediaTypes()) + .containsExactly(MediaType.TEXT_HTML, MediaType.TEXT_PLAIN)); } @Test void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") - .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) - .isEqualTo(Integer.valueOf(25))); + .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) + .isEqualTo(Integer.valueOf(25))); } @Test void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") - .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideMaxChunkSize() { this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.maxChunkSize:8KB") - .run((context) -> assertThat( - context.getBean(ThymeleafReactiveViewResolver.class).getResponseMaxChunkSizeBytes()) - .isEqualTo(Integer.valueOf(8192))); + .run((context) -> assertThat( + context.getBean(ThymeleafReactiveViewResolver.class).getResponseMaxChunkSizeBytes()) + .isEqualTo(Integer.valueOf(8192))); } @Test void overrideFullModeViewNames() { - this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.fullModeViewNames:foo,bar").run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getFullModeViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.fullModeViewNames:foo,bar") + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getFullModeViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideChunkedModeViewNames() { - this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar").run( - (context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getChunkedModeViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + this.contextRunner.withPropertyValues("spring.thymeleaf.reactive.chunkedModeViewNames:foo,bar") + .run((context) -> assertThat(context.getBean(ThymeleafReactiveViewResolver.class).getChunkedModeViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideEnableSpringElCompiler() { - this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true").run( - (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) - .isTrue()); + this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") + .run((context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) + .isTrue()); } @Test void enableSpringElCompilerIsDisabledByDefault() { - this.contextRunner.run( - (context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) - .isFalse()); + this.contextRunner + .run((context) -> assertThat(context.getBean(SpringWebFluxTemplateEngine.class).getEnableSpringELCompiler()) + .isFalse()); } @Test void overrideRenderHiddenMarkersBeforeCheckboxes() { this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") - .run((context) -> assertThat( - context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) - .isTrue()); + .run((context) -> assertThat( + context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isTrue()); } @Test void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat( - context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); + context.getBean(SpringWebFluxTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isFalse()); } @Test void templateLocationDoesNotExist(CapturedOutput output) { this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") - .run((context) -> assertThat(output).contains("Cannot find template location")); + .run((context) -> assertThat(output).contains("Cannot find template location")); } @Test void templateLocationEmpty(CapturedOutput output) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test @@ -211,10 +212,11 @@ class ThymeleafReactiveAutoConfigurationTests { this.contextRunner.run((context) -> { ISpringWebFluxTemplateEngine engine = context.getBean(ISpringWebFluxTemplateEngine.class); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); - exchange.getAttributes().put(SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME, - new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); - WebContext attrs = new WebContext(SpringWebFluxWebApplication.buildApplication(null).buildExchange(exchange, - Locale.US, MediaType.TEXT_HTML, StandardCharsets.UTF_8)); + exchange.getAttributes() + .put(SpringSecurityContextUtils.SECURITY_CONTEXT_MODEL_ATTRIBUTE_NAME, + new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); + WebContext attrs = new WebContext(SpringWebFluxWebApplication.buildApplication(null) + .buildExchange(exchange, Locale.US, MediaType.TEXT_HTML, StandardCharsets.UTF_8)); String result = engine.process("security-dialect", attrs); assertThat(result).isEqualTo("
alice
" + System.lineSeparator()); }); @@ -223,7 +225,7 @@ class ThymeleafReactiveAutoConfigurationTests { @Test void securityDialectAutoConfigurationBacksOffWithoutSpringSecurity() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security")) - .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); } @Test @@ -239,9 +241,9 @@ class ThymeleafReactiveAutoConfigurationTests { @Test void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) - .run((context) -> assertThat( - ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) - .isInstanceOf(GroupingStrategy.class)); + .run((context) -> assertThat( + ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) + .isInstanceOf(GroupingStrategy.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java index 4c02ee0aa7..4ddea183ca 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafServletAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,24 +79,24 @@ class ThymeleafServletAutoConfigurationTests { private final BuildOutput buildOutput = new BuildOutput(getClass()); private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)); @Test void autoConfigurationBackOffWithoutThymeleafSpring() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.thymeleaf.spring6")) - .run((context) -> assertThat(context).doesNotHaveBean(TemplateEngine.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TemplateEngine.class)); } @Test void createFromConfigClass() { this.contextRunner.withPropertyValues("spring.thymeleaf.mode:HTML", "spring.thymeleaf.suffix:") - .run((context) -> { - assertThat(context).hasSingleBean(TemplateEngine.class); - TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); - String result = engine.process("template.html", attrs).trim(); - assertThat(result).isEqualTo("bar"); - }); + .run((context) -> { + assertThat(context).hasSingleBean(TemplateEngine.class); + TemplateEngine engine = context.getBean(TemplateEngine.class); + Context attrs = new Context(Locale.UK, Collections.singletonMap("foo", "bar")); + String result = engine.process("template.html", attrs).trim(); + assertThat(result).isEqualTo("bar"); + }); } @Test @@ -114,76 +114,79 @@ class ThymeleafServletAutoConfigurationTests { @Test void overrideDisableProducePartialOutputWhileProcessing() { this.contextRunner.withPropertyValues("spring.thymeleaf.servlet.produce-partial-output-while-processing:false") - .run((context) -> assertThat( - context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) - .isFalse()); + .run((context) -> assertThat( + context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) + .isFalse()); } @Test void disableProducePartialOutputWhileProcessingIsEnabledByDefault() { this.contextRunner.run((context) -> assertThat( - context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()).isTrue()); + context.getBean(ThymeleafViewResolver.class).getProducePartialOutputWhileProcessing()) + .isTrue()); } @Test void overrideTemplateResolverOrder() { this.contextRunner.withPropertyValues("spring.thymeleaf.templateResolverOrder:25") - .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) - .isEqualTo(Integer.valueOf(25))); + .run((context) -> assertThat(context.getBean(ITemplateResolver.class).getOrder()) + .isEqualTo(Integer.valueOf(25))); } @Test void overrideViewNames() { this.contextRunner.withPropertyValues("spring.thymeleaf.viewNames:foo,bar") - .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class).getViewNames()) - .isEqualTo(new String[] { "foo", "bar" })); + .run((context) -> assertThat(context.getBean(ThymeleafViewResolver.class).getViewNames()) + .isEqualTo(new String[] { "foo", "bar" })); } @Test void overrideEnableSpringElCompiler() { this.contextRunner.withPropertyValues("spring.thymeleaf.enable-spring-el-compiler:true") - .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) - .isTrue()); + .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) + .isTrue()); } @Test void enableSpringElCompilerIsDisabledByDefault() { this.contextRunner - .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) - .isFalse()); + .run((context) -> assertThat(context.getBean(SpringTemplateEngine.class).getEnableSpringELCompiler()) + .isFalse()); } @Test void overrideRenderHiddenMarkersBeforeCheckboxes() { this.contextRunner.withPropertyValues("spring.thymeleaf.render-hidden-markers-before-checkboxes:true") - .run((context) -> assertThat( - context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isTrue()); + .run((context) -> assertThat( + context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isTrue()); } @Test void enableRenderHiddenMarkersBeforeCheckboxesIsDisabledByDefault() { this.contextRunner.run((context) -> assertThat( - context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()).isFalse()); + context.getBean(SpringTemplateEngine.class).getRenderHiddenMarkersBeforeCheckboxes()) + .isFalse()); } @Test void templateLocationDoesNotExist(CapturedOutput output) { this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/no-such-directory/") - .run((context) -> assertThat(output).contains("Cannot find template location")); + .run((context) -> assertThat(output).contains("Cannot find template location")); } @Test void templateLocationEmpty(CapturedOutput output) { new File(this.buildOutput.getTestResourcesLocation(), "empty-templates/empty-directory").mkdirs(); this.contextRunner.withPropertyValues("spring.thymeleaf.prefix:classpath:/empty-templates/empty-directory/") - .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); + .run((context) -> assertThat(output).doesNotContain("Cannot find template location")); } @Test void createLayoutFromConfigClass() { this.contextRunner.run((context) -> { - ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class).resolveViewName("view", - Locale.UK); + ThymeleafView view = (ThymeleafView) context.getBean(ThymeleafViewResolver.class) + .resolveViewName("view", Locale.UK); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(context.getBean(ServletContext.class)); request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); @@ -225,7 +228,7 @@ class ThymeleafServletAutoConfigurationTests { new MockHttpServletResponse())); try { SecurityContextHolder - .setContext(new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); + .setContext(new SecurityContextImpl(new TestingAuthenticationToken("alice", "admin"))); String result = engine.process("security-dialect", attrs); assertThat(result).isEqualTo("
alice
" + System.lineSeparator()); } @@ -238,7 +241,7 @@ class ThymeleafServletAutoConfigurationTests { @Test void securityDialectAutoConfigurationBacksOffWithoutSpringSecurity() { this.contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.security")) - .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); + .run((context) -> assertThat(context).doesNotHaveBean(SpringSecurityDialect.class)); } @Test @@ -254,13 +257,13 @@ class ThymeleafServletAutoConfigurationTests { @Test void renderNonWebAppTemplate() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(ThymeleafAutoConfiguration.class)) - .run((context) -> { - assertThat(context).doesNotHaveBean(ViewResolver.class); - TemplateEngine engine = context.getBean(TemplateEngine.class); - Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); - String result = engine.process("message", attrs); - assertThat(result).contains("Hello World"); - }); + .run((context) -> { + assertThat(context).doesNotHaveBean(ViewResolver.class); + TemplateEngine engine = context.getBean(TemplateEngine.class); + Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); + String result = engine.process("message", attrs); + assertThat(result).contains("Hello World"); + }); } @Test @@ -283,14 +286,18 @@ class ThymeleafServletAutoConfigurationTests { void registerResourceHandlingFilterWithOtherRegistrationBean() { // gh-14897 this.contextRunner.withUserConfiguration(FilterRegistrationOtherConfiguration.class) - .withPropertyValues("spring.web.resources.chain.enabled:true").run((context) -> { - Map beans = context.getBeansOfType(FilterRegistrationBean.class); - assertThat(beans).hasSize(2); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); - assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", - EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); - }); + .withPropertyValues("spring.web.resources.chain.enabled:true") + .run((context) -> { + Map beans = context.getBeansOfType(FilterRegistrationBean.class); + assertThat(beans).hasSize(2); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", + EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); + }); } @Test @@ -298,22 +305,26 @@ class ThymeleafServletAutoConfigurationTests { void registerResourceHandlingFilterWithResourceRegistrationBean() { // gh-14926 this.contextRunner.withUserConfiguration(FilterRegistrationResourceConfiguration.class) - .withPropertyValues("spring.web.resources.chain.enabled:true").run((context) -> { - Map beans = context.getBeansOfType(FilterRegistrationBean.class); - assertThat(beans).hasSize(1); - FilterRegistrationBean registration = beans.values().stream() - .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter).findFirst().get(); - assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", - EnumSet.of(DispatcherType.INCLUDE)); - }); + .withPropertyValues("spring.web.resources.chain.enabled:true") + .run((context) -> { + Map beans = context.getBeansOfType(FilterRegistrationBean.class); + assertThat(beans).hasSize(1); + FilterRegistrationBean registration = beans.values() + .stream() + .filter((r) -> r.getFilter() instanceof ResourceUrlEncodingFilter) + .findFirst() + .get(); + assertThat(registration).hasFieldOrPropertyWithValue("dispatcherTypes", + EnumSet.of(DispatcherType.INCLUDE)); + }); } @Test void layoutDialectCanBeCustomized() { this.contextRunner.withUserConfiguration(LayoutDialectConfiguration.class) - .run((context) -> assertThat( - ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) - .isInstanceOf(GroupingStrategy.class)); + .run((context) -> assertThat( + ReflectionTestUtils.getField(context.getBean(LayoutDialect.class), "sortingStrategy")) + .isInstanceOf(GroupingStrategy.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java index 4998d443ce..7861c74fc1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafTemplateAvailabilityProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,27 +41,31 @@ class ThymeleafTemplateAvailabilityProviderTests { @Test void availabilityOfTemplateInDefaultLocation() { assertThat(this.provider.isTemplateAvailable("home", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateThatDoesNotExist() { assertThat(this.provider.isTemplateAvailable("whatever", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isFalse(); + this.resourceLoader)) + .isFalse(); } @Test void availabilityOfTemplateWithCustomPrefix() { this.environment.setProperty("spring.thymeleaf.prefix", "classpath:/custom-templates/"); assertThat(this.provider.isTemplateAvailable("custom", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } @Test void availabilityOfTemplateWithCustomSuffix() { this.environment.setProperty("spring.thymeleaf.suffix", ".thymeleaf"); assertThat(this.provider.isTemplateAvailable("suffixed", this.environment, getClass().getClassLoader(), - this.resourceLoader)).isTrue(); + this.resourceLoader)) + .isTrue(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java index c61dffbb9a..502124eb17 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/TransactionAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ import static org.mockito.Mockito.mock; class TransactionAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TransactionAutoConfiguration.class)); @Test void whenThereIsNoPlatformTransactionManagerNoTransactionTemplateIsAutoConfigured() { @@ -79,33 +79,33 @@ class TransactionAutoConfigurationTests { @Test void whenThereAreBothReactiveAndPlatformTransactionManagersATemplateAndAnOperatorAreAutoConfigured() { this.contextRunner - .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, - DataSourceTransactionManagerAutoConfiguration.class)) - .withUserConfiguration(SinglePlatformTransactionManagerConfiguration.class, - SingleReactiveTransactionManagerConfiguration.class) - .withPropertyValues("spring.datasource.url:jdbc:h2:mem:" + UUID.randomUUID()).run((context) -> { - PlatformTransactionManager platformTransactionManager = context - .getBean(PlatformTransactionManager.class); - TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class); - assertThat(transactionTemplate.getTransactionManager()).isSameAs(platformTransactionManager); - ReactiveTransactionManager reactiveTransactionManager = context - .getBean(ReactiveTransactionManager.class); - TransactionalOperator transactionalOperator = context.getBean(TransactionalOperator.class); - assertThat(transactionalOperator).extracting("transactionManager") - .isSameAs(reactiveTransactionManager); - }); + .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class)) + .withUserConfiguration(SinglePlatformTransactionManagerConfiguration.class, + SingleReactiveTransactionManagerConfiguration.class) + .withPropertyValues("spring.datasource.url:jdbc:h2:mem:" + UUID.randomUUID()) + .run((context) -> { + PlatformTransactionManager platformTransactionManager = context + .getBean(PlatformTransactionManager.class); + TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class); + assertThat(transactionTemplate.getTransactionManager()).isSameAs(platformTransactionManager); + ReactiveTransactionManager reactiveTransactionManager = context + .getBean(ReactiveTransactionManager.class); + TransactionalOperator transactionalOperator = context.getBean(TransactionalOperator.class); + assertThat(transactionalOperator).extracting("transactionManager").isSameAs(reactiveTransactionManager); + }); } @Test void whenThereAreSeveralPlatformTransactionManagersNoTransactionTemplateIsAutoConfigured() { this.contextRunner.withUserConfiguration(SeveralPlatformTransactionManagersConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(TransactionTemplate.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TransactionTemplate.class)); } @Test void whenThereAreSeveralReactiveTransactionManagersNoTransactionOperatorIsAutoConfigured() { this.contextRunner.withUserConfiguration(SeveralReactiveTransactionManagersConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(TransactionalOperator.class)); + .run((context) -> assertThat(context).doesNotHaveBean(TransactionalOperator.class)); } @Test @@ -118,28 +118,31 @@ class TransactionAutoConfigurationTests { @Test void whenAUserProvidesATransactionalOperatorTheAutoConfiguredOperatorBacksOff() { - this.contextRunner.withUserConfiguration(SingleReactiveTransactionManagerConfiguration.class, - CustomTransactionalOperatorConfiguration.class).run((context) -> { - assertThat(context).hasSingleBean(TransactionalOperator.class); - assertThat(context.getBean("customTransactionalOperator")) - .isInstanceOf(TransactionalOperator.class); - }); + this.contextRunner + .withUserConfiguration(SingleReactiveTransactionManagerConfiguration.class, + CustomTransactionalOperatorConfiguration.class) + .run((context) -> { + assertThat(context).hasSingleBean(TransactionalOperator.class); + assertThat(context.getBean("customTransactionalOperator")).isInstanceOf(TransactionalOperator.class); + }); } @Test void platformTransactionManagerCustomizers() { this.contextRunner.withUserConfiguration(SeveralPlatformTransactionManagersConfiguration.class) - .run((context) -> { - TransactionManagerCustomizers customizers = context.getBean(TransactionManagerCustomizers.class); - assertThat(customizers).extracting("customizers").asList().singleElement() - .isInstanceOf(TransactionProperties.class); - }); + .run((context) -> { + TransactionManagerCustomizers customizers = context.getBean(TransactionManagerCustomizers.class); + assertThat(customizers).extracting("customizers") + .asList() + .singleElement() + .isInstanceOf(TransactionProperties.class); + }); } @Test void transactionNotManagedWithNoTransactionManager() { - this.contextRunner.withUserConfiguration(BaseConfiguration.class).run( - (context) -> assertThat(context.getBean(TransactionalService.class).isTransactionActive()).isFalse()); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .run((context) -> assertThat(context.getBean(TransactionalService.class).isTransactionActive()).isFalse()); } @Test @@ -153,23 +156,25 @@ class TransactionAutoConfigurationTests { @Test void transactionManagerCanBeConfiguredToJdkProxy() { this.contextRunner.withUserConfiguration(PlatformTransactionManagersConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class=false").run((context) -> { - assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); - assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); - assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); - }); + .withPropertyValues("spring.aop.proxy-target-class=false") + .run((context) -> { + assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); + assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); + assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); + }); } @Test void customEnableTransactionManagementTakesPrecedence() { this.contextRunner - .withUserConfiguration(CustomTransactionManagementConfiguration.class, - PlatformTransactionManagersConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class=true").run((context) -> { - assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); - assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); - assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); - }); + .withUserConfiguration(CustomTransactionManagementConfiguration.class, + PlatformTransactionManagersConfiguration.class) + .withPropertyValues("spring.aop.proxy-target-class=true") + .run((context) -> { + assertThat(context.getBean(AnotherService.class).isTransactionActive()).isTrue(); + assertThat(context).doesNotHaveBean(AnotherServiceImpl.class); + assertThat(context).doesNotHaveBean(TransactionalServiceImpl.class); + }); } @Configuration @@ -273,8 +278,11 @@ class TransactionAutoConfigurationTests { @Bean DataSource dataSource() { - return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:tx") - .username("sa").build(); + return DataSourceBuilder.create() + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .url("jdbc:hsqldb:mem:tx") + .username("sa") + .build(); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java index 23ead9290f..e70fb24e47 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -103,7 +103,7 @@ class JtaAutoConfigurationTests { this.context = new AnnotationConfigApplicationContext(CustomTransactionManagerConfig.class, JtaAutoConfiguration.class); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(JtaTransactionManager.class)); + .isThrownBy(() -> this.context.getBean(JtaTransactionManager.class)); } @Test @@ -165,8 +165,8 @@ class JtaAutoConfigurationTests { @Override public void beforeEach(ExtensionContext context) throws Exception { Namespace namespace = Namespace.create(getClass(), context.getUniqueId()); - context.getStore(namespace).getOrComputeIfAbsent(InitialContext.class, (k) -> createInitialContext(), - InitialContext.class); + context.getStore(namespace) + .getOrComputeIfAbsent(InitialContext.class, (k) -> createInitialContext(), InitialContext.class); } private InitialContext createInitialContext() { @@ -181,8 +181,8 @@ class JtaAutoConfigurationTests { @Override public void afterEach(ExtensionContext context) throws Exception { Namespace namespace = Namespace.create(getClass(), context.getUniqueId()); - InitialContext initialContext = context.getStore(namespace).remove(InitialContext.class, - InitialContext.class); + InitialContext initialContext = context.getStore(namespace) + .remove(InitialContext.class, InitialContext.class); initialContext.removeFromEnvironment("org.osjava.sj.jndi.ignoreClose"); initialContext.close(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java index 5b404df280..bb5306490b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java @@ -63,16 +63,16 @@ import static org.mockito.Mockito.mock; class ValidationAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test void validationAutoConfigurationShouldConfigureDefaultValidator() { this.contextRunner.run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); + .containsExactly("defaultValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(LocalValidatorFactoryBean.class) - .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); + .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); } @@ -82,9 +82,9 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("customValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("customValidator"); + .containsExactly("customValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(OptionalValidatorFactoryBean.class) - .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); + .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); assertThat(isPrimaryBean(context, "customValidator")).isFalse(); }); } @@ -94,7 +94,7 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedDefaultValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); + .containsExactly("defaultValidator"); assertThat(isPrimaryBean(context, "defaultValidator")).isFalse(); }); } @@ -113,9 +113,9 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedSpringValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); + .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(LocalValidatorFactoryBean.class) - .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); + .isEqualTo(context.getBean(org.springframework.validation.Validator.class)); assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); } @@ -125,10 +125,10 @@ class ValidationAutoConfigurationTests { this.contextRunner.withUserConfiguration(UserDefinedPrimarySpringValidatorConfig.class).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); + .containsExactly("customValidator", "anotherCustomValidator", "defaultValidator"); assertThat(context.getBean(Validator.class)).isInstanceOf(LocalValidatorFactoryBean.class); assertThat(context.getBean(org.springframework.validation.Validator.class)) - .isEqualTo(context.getBean("anotherCustomValidator")); + .isEqualTo(context.getBean("anotherCustomValidator")); assertThat(isPrimaryBean(context, "defaultValidator")).isFalse(); }); } @@ -139,10 +139,10 @@ class ValidationAutoConfigurationTests { this.contextRunner.withParent(parent).run((context) -> { assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); + .containsExactly("defaultValidator"); assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), - org.springframework.validation.Validator.class)).containsExactly("defaultValidator", - "customValidator", "anotherCustomValidator"); + org.springframework.validation.Validator.class)) + .containsExactly("defaultValidator", "customValidator", "anotherCustomValidator"); assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); }); @@ -151,17 +151,17 @@ class ValidationAutoConfigurationTests { @Test void whenUserProvidesPrimarySpringValidatorInParentContextThenAutoConfiguredValidatorIsPrimary() { new ApplicationContextRunner().withUserConfiguration(UserDefinedPrimarySpringValidatorConfig.class) - .run((parent) -> { - this.contextRunner.withParent(parent).run((context) -> { - assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); - assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) - .containsExactly("defaultValidator"); - assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), - org.springframework.validation.Validator.class)).containsExactly("defaultValidator", - "customValidator", "anotherCustomValidator"); - assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); - }); + .run((parent) -> { + this.contextRunner.withParent(parent).run((context) -> { + assertThat(context.getBeanNamesForType(Validator.class)).containsExactly("defaultValidator"); + assertThat(context.getBeanNamesForType(org.springframework.validation.Validator.class)) + .containsExactly("defaultValidator"); + assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), + org.springframework.validation.Validator.class)) + .containsExactly("defaultValidator", "customValidator", "anotherCustomValidator"); + assertThat(isPrimaryBean(context, "defaultValidator")).isTrue(); }); + }); } @Test @@ -197,14 +197,14 @@ class ValidationAutoConfigurationTests { @Test void validationCanBeConfiguredToUseJdkProxy() { this.contextRunner.withUserConfiguration(AnotherSampleServiceConfiguration.class) - .withPropertyValues("spring.aop.proxy-target-class=false").run((context) -> { - assertThat(context.getBeansOfType(Validator.class)).hasSize(1); - assertThat(context.getBeansOfType(DefaultAnotherSampleService.class)).isEmpty(); - AnotherSampleService service = context.getBean(AnotherSampleService.class); - service.doSomething(42); - assertThatExceptionOfType(ConstraintViolationException.class) - .isThrownBy(() -> service.doSomething(2)); - }); + .withPropertyValues("spring.aop.proxy-target-class=false") + .run((context) -> { + assertThat(context.getBeansOfType(Validator.class)).hasSize(1); + assertThat(context.getBeansOfType(DefaultAnotherSampleService.class)).isEmpty(); + AnotherSampleService service = context.getBean(AnotherSampleService.class); + service.doSomething(42); + assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> service.doSomething(2)); + }); } @Test @@ -214,7 +214,7 @@ class ValidationAutoConfigurationTests { assertThat(context.getBeansOfType(Validator.class)).hasSize(1); Object userMethodValidationPostProcessor = context.getBean("testMethodValidationPostProcessor"); assertThat(context.getBean(MethodValidationPostProcessor.class)) - .isSameAs(userMethodValidationPostProcessor); + .isSameAs(userMethodValidationPostProcessor); assertThat(context.getBeansOfType(MethodValidationPostProcessor.class)).hasSize(1); Object validator = ReflectionTestUtils.getField(userMethodValidationPostProcessor, "validator"); assertThat(validator).isNotNull().isInstanceOf(Supplier.class); @@ -225,22 +225,24 @@ class ValidationAutoConfigurationTests { @Test void methodValidationPostProcessorValidatorDependencyDoesNotTriggerEarlyInitialization() { this.contextRunner.withUserConfiguration(CustomValidatorConfiguration.class) - .run((context) -> assertThat(context.getBean(TestBeanPostProcessor.class).postProcessed) - .contains("someService")); + .run((context) -> assertThat(context.getBean(TestBeanPostProcessor.class).postProcessed) + .contains("someService")); } @Test void validationIsEnabledInChildContext() { this.contextRunner.run((parent) -> new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(SampleService.class).withParent(parent).run((context) -> { - assertThat(context.getBeansOfType(Validator.class)).isEmpty(); - assertThat(parent.getBeansOfType(Validator.class)).hasSize(1); - SampleService service = context.getBean(SampleService.class); - service.doSomething("Valid"); - assertThatExceptionOfType(ConstraintViolationException.class) - .isThrownBy(() -> service.doSomething("KO")); - })); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) + .withUserConfiguration(SampleService.class) + .withParent(parent) + .run((context) -> { + assertThat(context.getBeansOfType(Validator.class)).isEmpty(); + assertThat(parent.getBeansOfType(Validator.class)).hasSize(1); + SampleService service = context.getBean(SampleService.class); + service.doSomething("Valid"); + assertThatExceptionOfType(ConstraintViolationException.class) + .isThrownBy(() -> service.doSomething("KO")); + })); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java index 6be064106d..c344690f67 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test void missingElDependencyIsTolerated() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java index ba1903b01e..8a88bcf77d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationWithoutValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ValidationAutoConfigurationWithoutValidatorTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test void validationIsDisabled() { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java index 817c569e58..bf57084b98 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapterTests.java @@ -86,10 +86,9 @@ class ValidatorAdapterTests { ClassPathResource hibernateValidator = new ClassPathResource( "META-INF/services/jakarta.validation.spi.ValidationProvider"); this.contextRunner - .withClassLoader( - new FilteredClassLoader(FilteredClassLoader.ClassPathResourceFilter.of(hibernateValidator), - FilteredClassLoader.PackageFilter.of("org.hibernate.validator"))) - .run((context) -> ValidatorAdapter.get(context, null)); + .withClassLoader(new FilteredClassLoader(FilteredClassLoader.ClassPathResourceFilter.of(hibernateValidator), + FilteredClassLoader.PackageFilter.of("org.hibernate.validator"))) + .run((context) -> ValidatorAdapter.get(context, null)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index 135a77f9bc..eaf0b45c2b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -389,55 +389,55 @@ class ServerPropertiesTests { @Test void tomcatMinSpareThreadsMatchesProtocolDefault() throws Exception { assertThat(this.properties.getTomcat().getThreads().getMinSpare()) - .isEqualTo(getDefaultProtocol().getMinSpareThreads()); + .isEqualTo(getDefaultProtocol().getMinSpareThreads()); } @Test void tomcatMaxHttpPostSizeMatchesConnectorDefault() { assertThat(this.properties.getTomcat().getMaxHttpFormPostSize().toBytes()) - .isEqualTo(getDefaultConnector().getMaxPostSize()); + .isEqualTo(getDefaultConnector().getMaxPostSize()); } @Test void tomcatBackgroundProcessorDelayMatchesEngineDefault() { assertThat(this.properties.getTomcat().getBackgroundProcessorDelay()) - .hasSeconds((new StandardEngine().getBackgroundProcessorDelay())); + .hasSeconds((new StandardEngine().getBackgroundProcessorDelay())); } @Test void tomcatMaxHttpFormPostSizeMatchesConnectorDefault() { assertThat(this.properties.getTomcat().getMaxHttpFormPostSize().toBytes()) - .isEqualTo(getDefaultConnector().getMaxPostSize()); + .isEqualTo(getDefaultConnector().getMaxPostSize()); } @Test void tomcatUriEncodingMatchesConnectorDefault() { assertThat(this.properties.getTomcat().getUriEncoding().name()) - .isEqualTo(getDefaultConnector().getURIEncoding()); + .isEqualTo(getDefaultConnector().getURIEncoding()); } @Test void tomcatRedirectContextRootMatchesDefault() { assertThat(this.properties.getTomcat().getRedirectContextRoot()) - .isEqualTo(new StandardContext().getMapperContextRootRedirectEnabled()); + .isEqualTo(new StandardContext().getMapperContextRootRedirectEnabled()); } @Test void tomcatAccessLogRenameOnRotateMatchesDefault() { assertThat(this.properties.getTomcat().getAccesslog().isRenameOnRotate()) - .isEqualTo(new AccessLogValve().isRenameOnRotate()); + .isEqualTo(new AccessLogValve().isRenameOnRotate()); } @Test void tomcatAccessLogRequestAttributesEnabledMatchesDefault() { assertThat(this.properties.getTomcat().getAccesslog().isRequestAttributesEnabled()) - .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); + .isEqualTo(new AccessLogValve().getRequestAttributesEnabled()); } @Test void tomcatInternalProxiesMatchesDefault() { assertThat(this.properties.getTomcat().getRemoteip().getInternalProxies()) - .isEqualTo(new RemoteIpValve().getInternalProxies()); + .isEqualTo(new RemoteIpValve().getInternalProxies()); } @Test @@ -479,16 +479,17 @@ class ServerPropertiesTests { void jettyMaxHttpFormPostSizeMatchesDefault() { JettyServletWebServerFactory jettyFactory = new JettyServletWebServerFactory(0); JettyWebServer jetty = (JettyWebServer) jettyFactory - .getWebServer((ServletContextInitializer) (servletContext) -> servletContext - .addServlet("formPost", new HttpServlet() { + .getWebServer((ServletContextInitializer) (servletContext) -> servletContext + .addServlet("formPost", new HttpServlet() { - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - req.getParameterMap(); - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + req.getParameterMap(); + } - }).addMapping("/form")); + }) + .addMapping("/form")); jetty.start(); org.eclipse.jetty.server.Connector connector = jetty.getServer().getConnectors()[0]; final AtomicReference failure = new AtomicReference<>(); @@ -534,7 +535,7 @@ class ServerPropertiesTests { @Test void undertowMaxHttpPostSizeMatchesDefault() { assertThat(this.properties.getUndertow().getMaxHttpPostSize().toBytes()) - .isEqualTo(UndertowOptions.DEFAULT_MAX_ENTITY_SIZE); + .isEqualTo(UndertowOptions.DEFAULT_MAX_ENTITY_SIZE); } @Test @@ -542,13 +543,13 @@ class ServerPropertiesTests { @SuppressWarnings("removal") void nettyMaxChunkSizeMatchesHttpDecoderSpecDefault() { assertThat(this.properties.getNetty().getMaxChunkSize().toBytes()) - .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_CHUNK_SIZE); + .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_CHUNK_SIZE); } @Test void nettyMaxInitialLineLengthMatchesHttpDecoderSpecDefault() { assertThat(this.properties.getNetty().getMaxInitialLineLength().toBytes()) - .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_INITIAL_LINE_LENGTH); + .isEqualTo(HttpDecoderSpec.DEFAULT_MAX_INITIAL_LINE_LENGTH); } @Test @@ -564,7 +565,7 @@ class ServerPropertiesTests { @Test void nettyInitialBufferSizeMatchesHttpDecoderSpecDefault() { assertThat(this.properties.getNetty().getInitialBufferSize().toBytes()) - .isEqualTo(HttpDecoderSpec.DEFAULT_INITIAL_BUFFER_SIZE); + .isEqualTo(HttpDecoderSpec.DEFAULT_INITIAL_BUFFER_SIZE); } private Connector getDefaultConnector() { @@ -573,7 +574,8 @@ class ServerPropertiesTests { private AbstractProtocol getDefaultProtocol() throws Exception { return (AbstractProtocol) Class.forName(TomcatServletWebServerFactory.DEFAULT_PROTOCOL) - .getDeclaredConstructor().newInstance(); + .getDeclaredConstructor() + .newInstance(); } private void bind(String name, String value) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java index ce8d794285..0a12d44e10 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -37,20 +37,20 @@ import static org.assertj.core.api.Assertions.assertThat; class WebPropertiesResourcesBindingTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfiguration.class); + .withUserConfiguration(TestConfiguration.class); @Test void staticLocationsExpandArray() { this.contextRunner - .withPropertyValues("spring.web.resources.static-locations[0]=classpath:/one/", - "spring.web.resources.static-locations[1]=classpath:/two", - "spring.web.resources.static-locations[2]=classpath:/three/", - "spring.web.resources.static-locations[3]=classpath:/four", - "spring.web.resources.static-locations[4]=classpath:/five/", - "spring.web.resources.static-locations[5]=classpath:/six") - .run(assertResourceProperties((properties) -> assertThat(properties.getStaticLocations()).contains( - "classpath:/one/", "classpath:/two/", "classpath:/three/", "classpath:/four/", - "classpath:/five/", "classpath:/six/"))); + .withPropertyValues("spring.web.resources.static-locations[0]=classpath:/one/", + "spring.web.resources.static-locations[1]=classpath:/two", + "spring.web.resources.static-locations[2]=classpath:/three/", + "spring.web.resources.static-locations[3]=classpath:/four", + "spring.web.resources.static-locations[4]=classpath:/five/", + "spring.web.resources.static-locations[5]=classpath:/six") + .run(assertResourceProperties((properties) -> assertThat(properties.getStaticLocations()).contains( + "classpath:/one/", "classpath:/two/", "classpath:/three/", "classpath:/four/", "classpath:/five/", + "classpath:/six/"))); } private ContextConsumer assertResourceProperties(Consumer consumer) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java index e77e190de6..c7cf28174a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebPropertiesResourcesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -91,8 +91,8 @@ class WebPropertiesResourcesTests { properties.setStaleWhileRevalidate(Duration.ofSeconds(7)); CacheControl cacheControl = properties.toHttpCacheControl(); assertThat(cacheControl.getHeaderValue()) - .isEqualTo("max-age=4, must-revalidate, no-transform, public, private, proxy-revalidate," - + " s-maxage=5, stale-if-error=6, stale-while-revalidate=7"); + .isEqualTo("max-age=4, must-revalidate, no-transform, public, private, proxy-revalidate," + + " s-maxage=5, stale-if-error=6, stale-while-revalidate=7"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHintsTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHintsTests.java index 960e91bf7e..9c4f337bab 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/WebResourcesRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class WebResourcesRuntimeHintsTests { RuntimeHints hints = register( new TestClassLoader(List.of("META-INF/resources/", "resources/", "static/", "public/"))); assertThat(hints.resources().resourcePatternHints()).singleElement() - .satisfies(include("META-INF/resources/*", "resources/*", "static/*", "public/*")); + .satisfies(include("META-INF/resources/*", "resources/*", "static/*", "public/*")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java index e2b9a746c7..a80f93a737 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/client/RestTemplateAutoConfigurationTests.java @@ -56,33 +56,33 @@ import static org.mockito.Mockito.mock; class RestTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)); @Test void restTemplateBuilderConfigurerShouldBeLazilyDefined() { this.contextRunner.run((context) -> assertThat( - context.getBeanFactory().getBeanDefinition("restTemplateBuilderConfigurer").isLazyInit()).isTrue()); + context.getBeanFactory().getBeanDefinition("restTemplateBuilderConfigurer").isLazyInit()) + .isTrue()); } @Test void restTemplateBuilderShouldBeLazilyDefined() { - this.contextRunner.run( - (context) -> assertThat(context.getBeanFactory().getBeanDefinition("restTemplateBuilder").isLazyInit()) - .isTrue()); + this.contextRunner + .run((context) -> assertThat(context.getBeanFactory().getBeanDefinition("restTemplateBuilder").isLazyInit()) + .isTrue()); } @Test void restTemplateWhenMessageConvertersDefinedShouldHaveMessageConverters() { this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .withUserConfiguration(RestTemplateConfig.class).run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - List> converters = context.getBean(HttpMessageConverters.class) - .getConverters(); - assertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters); - assertThat(restTemplate.getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); - }); + .withUserConfiguration(RestTemplateConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + List> converters = context.getBean(HttpMessageConverters.class).getConverters(); + assertThat(restTemplate.getMessageConverters()).containsExactlyElementsOf(converters); + assertThat(restTemplate.getRequestFactory()).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + }); } @Test @@ -98,51 +98,53 @@ class RestTemplateAutoConfigurationTests { @SuppressWarnings({ "unchecked", "rawtypes" }) void restTemplateWhenHasCustomMessageConvertersShouldHaveMessageConverters() { this.contextRunner.withConfiguration(AutoConfigurations.of(HttpMessageConvertersAutoConfiguration.class)) - .withUserConfiguration(CustomHttpMessageConverter.class, RestTemplateConfig.class).run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters()).extracting(HttpMessageConverter::getClass) - .contains((Class) CustomHttpMessageConverter.class); - }); + .withUserConfiguration(CustomHttpMessageConverter.class, RestTemplateConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + assertThat(restTemplate.getMessageConverters()).extracting(HttpMessageConverter::getClass) + .contains((Class) CustomHttpMessageConverter.class); + }); } @Test void restTemplateShouldApplyCustomizer() { this.contextRunner.withUserConfiguration(RestTemplateConfig.class, RestTemplateCustomizerConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); - then(customizer).should().customize(restTemplate); - }); + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); + then(customizer).should().customize(restTemplate); + }); } @Test void restTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { - this.contextRunner.withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderConfig.class, - RestTemplateCustomizerConfig.class).run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters()).hasSize(1); - assertThat(restTemplate.getMessageConverters().get(0)) - .isInstanceOf(CustomHttpMessageConverter.class); - then(context.getBean(RestTemplateCustomizer.class)).shouldHaveNoInteractions(); - }); + this.contextRunner + .withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderConfig.class, + RestTemplateCustomizerConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + assertThat(restTemplate.getMessageConverters()).hasSize(1); + assertThat(restTemplate.getMessageConverters().get(0)).isInstanceOf(CustomHttpMessageConverter.class); + then(context.getBean(RestTemplateCustomizer.class)).shouldHaveNoInteractions(); + }); } @Test void restTemplateWhenHasCustomBuilderCouldReuseBuilderConfigurer() { - this.contextRunner.withUserConfiguration(RestTemplateConfig.class, - CustomRestTemplateBuilderWithConfigurerConfig.class, RestTemplateCustomizerConfig.class) - .run((context) -> { - assertThat(context).hasSingleBean(RestTemplate.class); - RestTemplate restTemplate = context.getBean(RestTemplate.class); - assertThat(restTemplate.getMessageConverters()).hasSize(1); - assertThat(restTemplate.getMessageConverters().get(0)) - .isInstanceOf(CustomHttpMessageConverter.class); - RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); - then(customizer).should().customize(restTemplate); - }); + this.contextRunner + .withUserConfiguration(RestTemplateConfig.class, CustomRestTemplateBuilderWithConfigurerConfig.class, + RestTemplateCustomizerConfig.class) + .run((context) -> { + assertThat(context).hasSingleBean(RestTemplate.class); + RestTemplate restTemplate = context.getBean(RestTemplate.class); + assertThat(restTemplate.getMessageConverters()).hasSize(1); + assertThat(restTemplate.getMessageConverters().get(0)).isInstanceOf(CustomHttpMessageConverter.class); + RestTemplateCustomizer customizer = context.getBean(RestTemplateCustomizer.class); + then(customizer).should().customize(restTemplate); + }); } @Test @@ -162,22 +164,22 @@ class RestTemplateAutoConfigurationTests { @Test void builderShouldBeFreshForEachUse() { this.contextRunner.withUserConfiguration(DirtyRestTemplateConfig.class) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } @Test void whenServletWebApplicationRestTemplateBuilderIsConfigured() { new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(RestTemplateBuilder.class) - .hasSingleBean(RestTemplateBuilderConfigurer.class)); + .run((context) -> assertThat(context).hasSingleBean(RestTemplateBuilder.class) + .hasSingleBean(RestTemplateBuilderConfigurer.class)); } @Test void whenReactiveWebApplicationRestTemplateBuilderIsNotConfigured() { new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(RestTemplateBuilder.class) - .doesNotHaveBean(RestTemplateBuilderConfigurer.class)); + .withConfiguration(AutoConfigurations.of(RestTemplateAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(RestTemplateBuilder.class) + .doesNotHaveBean(RestTemplateBuilderConfigurer.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java index 47aa183033..94e66e6f5b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -162,7 +162,7 @@ class JettyWebServerFactoryCustomizerTests { assertThat(defaultQueue).isInstanceOf(BlockingArrayQueue.class); assertThat(configuredQueue).isInstanceOf(BlockingArrayQueue.class); assertThat(((BlockingArrayQueue) defaultQueue).getMaxCapacity()) - .isEqualTo(((BlockingArrayQueue) configuredQueue).getMaxCapacity()); + .isEqualTo(((BlockingArrayQueue) configuredQueue).getMaxCapacity()); } @Test @@ -239,7 +239,7 @@ class JettyWebServerFactoryCustomizerTests { assertThat(queuedThreadPool.getMinThreads()).isEqualTo(defaultProperties.getThreads().getMin()); assertThat(queuedThreadPool.getMaxThreads()).isEqualTo(defaultProperties.getThreads().getMax()); assertThat(queuedThreadPool.getIdleTimeout()) - .isEqualTo(defaultProperties.getThreads().getIdleTimeout().toMillis()); + .isEqualTo(defaultProperties.getThreads().getIdleTimeout().toMillis()); } private CustomRequestLog getRequestLog(JettyWebServer server) { @@ -299,7 +299,9 @@ class JettyWebServerFactoryCustomizerTests { server.start(); server.stop(); return Arrays.stream(server.getServer().getConnectors()) - .filter((connector) -> connector instanceof AbstractConnector).map(Connector::getIdleTimeout).toList(); + .filter((connector) -> connector instanceof AbstractConnector) + .map(Connector::getIdleTimeout) + .toList(); } private List getRequestHeaderSizes(JettyWebServer server) { @@ -309,12 +311,14 @@ class JettyWebServerFactoryCustomizerTests { server.stop(); Connector[] connectors = server.getServer().getConnectors(); for (Connector connector : connectors) { - connector.getConnectionFactories().stream().filter((factory) -> factory instanceof ConnectionFactory) - .forEach((cf) -> { - ConnectionFactory factory = (ConnectionFactory) cf; - HttpConfiguration configuration = factory.getHttpConfiguration(); - requestHeaderSizes.add(configuration.getRequestHeaderSize()); - }); + connector.getConnectionFactories() + .stream() + .filter((factory) -> factory instanceof ConnectionFactory) + .forEach((cf) -> { + ConnectionFactory factory = (ConnectionFactory) cf; + HttpConfiguration configuration = factory.getHttpConfiguration(); + requestHeaderSizes.add(configuration.getRequestHeaderSize()); + }); } return requestHeaderSizes; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java index 3bd0407e2c..6ffb41f5c3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java @@ -79,8 +79,8 @@ class TomcatWebServerFactoryCustomizerTests { void defaultsAreConsistent() { customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxSwallowSize()) - .isEqualTo(this.serverProperties.getTomcat().getMaxSwallowSize().toBytes())); + .getMaxSwallowSize()) + .isEqualTo(this.serverProperties.getTomcat().getMaxSwallowSize().toBytes())); } @Test @@ -88,7 +88,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accept-count=10"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getAcceptCount()) - .isEqualTo(10)); + .isEqualTo(10)); } @Test @@ -96,7 +96,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.processor-cache=100"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) - .isEqualTo(100)); + .isEqualTo(100)); } @Test @@ -104,7 +104,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.keep-alive-timeout=30ms"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getKeepAliveTimeout()) - .isEqualTo(30)); + .isEqualTo(30)); } @Test @@ -112,7 +112,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.http2.enabled=true"); customizeAndRunServer((server) -> assertThat( ((Http2Protocol) server.getTomcat().getConnector().findUpgradeProtocols()[0]).getKeepAliveTimeout()) - .isEqualTo(20000L)); + .isEqualTo(20000L)); } @Test @@ -120,7 +120,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.keep-alive-timeout=30s", "server.http2.enabled=true"); customizeAndRunServer((server) -> assertThat( ((Http2Protocol) server.getTomcat().getConnector().findUpgradeProtocols()[0]).getKeepAliveTimeout()) - .isEqualTo(30000L)); + .isEqualTo(30000L)); } @Test @@ -128,14 +128,16 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.max-keep-alive-requests=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxKeepAliveRequests()).isEqualTo(-1)); + .getMaxKeepAliveRequests()) + .isEqualTo(-1)); } @Test void defaultMaxKeepAliveRequests() { customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxKeepAliveRequests()).isEqualTo(100)); + .getMaxKeepAliveRequests()) + .isEqualTo(100)); } @Test @@ -143,7 +145,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.processor-cache=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getProcessorCache()) - .isEqualTo(-1)); + .isEqualTo(-1)); } @Test @@ -164,7 +166,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.max-connections=5"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getMaxConnections()) - .isEqualTo(5)); + .isEqualTo(5)); } @Test @@ -179,19 +181,21 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.max-http-header-size=1KB"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxHttpRequestHeaderSize()).isEqualTo(DataSize.ofKilobytes(1).toBytes())); + .getMaxHttpRequestHeaderSize()) + .isEqualTo(DataSize.ofKilobytes(1).toBytes())); } @Test void customMaxHttpHeaderSizeWithHttp2() { bind("server.max-http-header-size=1KB", "server.http2.enabled=true"); customizeAndRunServer((server) -> { - AbstractHttp11Protocol protocolHandler = (AbstractHttp11Protocol) server.getTomcat().getConnector() - .getProtocolHandler(); + AbstractHttp11Protocol protocolHandler = (AbstractHttp11Protocol) server.getTomcat() + .getConnector() + .getProtocolHandler(); long expectedSize = DataSize.ofKilobytes(1).toBytes(); assertThat(protocolHandler.getMaxHttpRequestHeaderSize()).isEqualTo(expectedSize); assertThat(((Http2Protocol) protocolHandler.getUpgradeProtocol("h2c")).getMaxHeaderSize()) - .isEqualTo(expectedSize); + .isEqualTo(expectedSize); }); } @@ -200,7 +204,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.max-http-header-size=-1"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxHttpRequestHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes())); + .getMaxHttpRequestHeaderSize()) + .isEqualTo(DataSize.ofKilobytes(8).toBytes())); } @Test @@ -208,7 +213,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.max-http-header-size=0"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxHttpRequestHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes())); + .getMaxHttpRequestHeaderSize()) + .isEqualTo(DataSize.ofKilobytes(8).toBytes())); } @Test @@ -216,7 +222,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.max-swallow-size=10MB"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getMaxSwallowSize()).isEqualTo(DataSize.ofMegabytes(10).toBytes())); + .getMaxSwallowSize()) + .isEqualTo(DataSize.ofMegabytes(10).toBytes())); } @Test @@ -267,7 +274,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.relaxed-path-chars=|,^"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getRelaxedPathChars()).isEqualTo("|^")); + .getRelaxedPathChars()) + .isEqualTo("|^")); } @Test @@ -275,7 +283,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.relaxed-query-chars=^ , | "); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getRelaxedQueryChars()).isEqualTo("^|")); + .getRelaxedQueryChars()) + .isEqualTo("^|")); } @Test @@ -357,7 +366,8 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.reject-illegal-header=false"); customizeAndRunServer((server) -> assertThat( ((AbstractHttp11Protocol) server.getTomcat().getConnector().getProtocolHandler()) - .getRejectIllegalHeader()).isFalse()); + .getRejectIllegalHeader()) + .isFalse()); } @Test @@ -384,7 +394,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.connection-timeout=30s"); customizeAndRunServer((server) -> assertThat( ((AbstractProtocol) server.getTomcat().getConnector().getProtocolHandler()).getConnectionTimeout()) - .isEqualTo(30000)); + .isEqualTo(30000)); } @Test @@ -407,7 +417,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) - .isEqualTo(".yyyy-MM-dd"); + .isEqualTo(".yyyy-MM-dd"); } @Test @@ -415,7 +425,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.file-date-format=yyyy-MM-dd.HH"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()) - .isEqualTo("yyyy-MM-dd.HH"); + .isEqualTo("yyyy-MM-dd.HH"); } @Test @@ -436,7 +446,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getMaxDays()) - .isEqualTo(this.serverProperties.getTomcat().getAccesslog().getMaxDays()); + .isEqualTo(this.serverProperties.getTomcat().getAccesslog().getMaxDays()); } @Test @@ -446,10 +456,10 @@ class TomcatWebServerFactoryCustomizerTests { TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getConditionIf()).isEqualTo("foo"); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getConditionUnless()) - .isEqualTo("bar"); + .isEqualTo("bar"); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getCondition()) - .describedAs("value of condition should equal conditionUnless - provided for backwards compatibility") - .isEqualTo("bar"); + .describedAs("value of condition should equal conditionUnless - provided for backwards compatibility") + .isEqualTo("bar"); } @Test @@ -471,7 +481,7 @@ class TomcatWebServerFactoryCustomizerTests { bind("server.tomcat.accesslog.enabled=true"); TomcatServletWebServerFactory factory = customizeAndGetFactory(); assertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getLocale()) - .isEqualTo(Locale.getDefault().toString()); + .isEqualTo(Locale.getDefault().toString()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java index 464dd440ed..15289d60e4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java @@ -258,7 +258,7 @@ class UndertowWebServerFactoryCustomizerTests { Object argument = invocation.getArgument(0); Arrays.stream((argument instanceof UndertowBuilderCustomizer undertowCustomizer) ? new UndertowBuilderCustomizer[] { undertowCustomizer } : (UndertowBuilderCustomizer[]) argument) - .forEach((customizer) -> customizer.customize(builder)); + .forEach((customizer) -> customizer.customize(builder)); return null; }).given(factory).addBuilderCustomizers(any()); return factory; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java index d636adfc51..edb984df74 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/format/WebConversionServiceTests.java @@ -47,7 +47,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()); LocalDate date = LocalDate.of(2020, 4, 26); assertThat(conversionService.convert(date, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(date)); + .isEqualTo(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(date)); } @Test @@ -55,7 +55,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().dateFormat("iso")); LocalDate date = LocalDate.of(2020, 4, 26); assertThat(conversionService.convert(date, String.class)) - .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE.format(date)); + .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE.format(date)); } @Test @@ -73,7 +73,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()); LocalTime time = LocalTime.of(12, 45, 23); assertThat(conversionService.convert(time, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); + .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); } @Test @@ -81,7 +81,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().timeFormat("iso")); LocalTime time = LocalTime.of(12, 45, 23); assertThat(conversionService.convert(time, String.class)) - .isEqualTo(DateTimeFormatter.ISO_LOCAL_TIME.format(time)); + .isEqualTo(DateTimeFormatter.ISO_LOCAL_TIME.format(time)); } @Test @@ -98,7 +98,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(formatters); OffsetTime offsetTime = OffsetTime.of(LocalTime.of(12, 45, 23), ZoneOffset.ofHoursMinutes(1, 30)); assertThat(conversionService.convert(offsetTime, String.class)) - .isEqualTo(DateTimeFormatter.ISO_OFFSET_TIME.format(offsetTime)); + .isEqualTo(DateTimeFormatter.ISO_OFFSET_TIME.format(offsetTime)); } @Test @@ -114,7 +114,7 @@ class WebConversionServiceTests { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()); LocalDateTime dateTime = LocalDateTime.of(2020, 4, 26, 12, 45, 23); assertThat(conversionService.convert(dateTime, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); + .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); } @Test @@ -123,7 +123,7 @@ class WebConversionServiceTests { new DateTimeFormatters().dateTimeFormat("iso")); LocalDateTime dateTime = LocalDateTime.of(2020, 4, 26, 12, 45, 23); assertThat(conversionService.convert(dateTime, String.class)) - .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(dateTime)); + .isEqualTo(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(dateTime)); } @Test @@ -141,7 +141,7 @@ class WebConversionServiceTests { OffsetDateTime offsetDateTime = OffsetDateTime.of(LocalDate.of(2020, 4, 26), LocalTime.of(12, 45, 23), ZoneOffset.ofHoursMinutes(1, 30)); assertThat(conversionService.convert(offsetDateTime, String.class)) - .isEqualTo(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime)); + .isEqualTo(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java index 4c44adc556..70df1d0c2e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/HttpHandlerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ import static org.springframework.web.reactive.function.server.RouterFunctions.r class HttpHandlerAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(HttpHandlerAutoConfiguration.class)); @Test void shouldNotProcessIfExistingHttpHandler() { @@ -57,25 +57,26 @@ class HttpHandlerAutoConfigurationTests { @Test void shouldConfigureHttpHandlerAnnotation() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) - .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); } @Test void shouldConfigureHttpHandlerWithoutWebFluxAutoConfiguration() { this.contextRunner.withUserConfiguration(CustomWebHandler.class) - .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(HttpHandler.class)); } @Test void shouldConfigureBasePathCompositeHandler() { this.contextRunner.withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class)) - .withPropertyValues("spring.webflux.base-path=/something").run((context) -> { - assertThat(context).hasSingleBean(HttpHandler.class); - HttpHandler httpHandler = context.getBean(HttpHandler.class); - assertThat(httpHandler).isInstanceOf(ContextPathCompositeHandler.class) - .extracting("handlerMap", InstanceOfAssertFactories.map(String.class, HttpHandler.class)) - .containsKey("/something"); - }); + .withPropertyValues("spring.webflux.base-path=/something") + .run((context) -> { + assertThat(context).hasSingleBean(HttpHandler.class); + HttpHandler httpHandler = context.getBean(HttpHandler.class); + assertThat(httpHandler).isInstanceOf(ContextPathCompositeHandler.class) + .extracting("handlerMap", InstanceOfAssertFactories.map(String.class, HttpHandler.class)) + .containsKey("/something"); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java index 4959eacc94..ccbc01ae7b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,71 +42,78 @@ import static org.assertj.core.api.Assertions.assertThat; class ReactiveMultipartAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)); @Test void shouldNotProvideCustomizerForNonReactiveApp() { new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); + .withConfiguration(AutoConfigurations.of(ReactiveMultipartAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); } @Test void shouldNotProvideCustomizerWhenWebFluxNotAvailable() { this.contextRunner.withClassLoader(new FilteredClassLoader(WebFluxConfigurer.class)) - .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); + .run((context) -> assertThat(context).doesNotHaveBean(CodecCustomizer.class)); } @Test void shouldConfigureMultipartPropertiesForDefaultReader() { this.contextRunner - .withPropertyValues("spring.webflux.multipart.max-in-memory-size=1GB", - "spring.webflux.multipart.max-headers-size=16KB", - "spring.webflux.multipart.max-disk-usage-per-part=100MB", - "spring.webflux.multipart.max-parts=7", "spring.webflux.multipart.headers-charset:UTF_16") - .run((context) -> { - CodecCustomizer customizer = context.getBean(CodecCustomizer.class); - DefaultServerCodecConfigurer configurer = new DefaultServerCodecConfigurer(); - customizer.customize(configurer); - DefaultPartHttpMessageReader partReader = getDefaultPartReader(configurer); - assertThat(partReader).hasFieldOrPropertyWithValue("maxParts", 7); - assertThat(partReader).hasFieldOrPropertyWithValue("maxHeadersSize", - Math.toIntExact(DataSize.ofKilobytes(16).toBytes())); - assertThat(partReader).hasFieldOrPropertyWithValue("headersCharset", StandardCharsets.UTF_16); - assertThat(partReader).hasFieldOrPropertyWithValue("maxInMemorySize", - Math.toIntExact(DataSize.ofGigabytes(1).toBytes())); - assertThat(partReader).hasFieldOrPropertyWithValue("maxDiskUsagePerPart", - DataSize.ofMegabytes(100).toBytes()); - }); + .withPropertyValues("spring.webflux.multipart.max-in-memory-size=1GB", + "spring.webflux.multipart.max-headers-size=16KB", + "spring.webflux.multipart.max-disk-usage-per-part=100MB", "spring.webflux.multipart.max-parts=7", + "spring.webflux.multipart.headers-charset:UTF_16") + .run((context) -> { + CodecCustomizer customizer = context.getBean(CodecCustomizer.class); + DefaultServerCodecConfigurer configurer = new DefaultServerCodecConfigurer(); + customizer.customize(configurer); + DefaultPartHttpMessageReader partReader = getDefaultPartReader(configurer); + assertThat(partReader).hasFieldOrPropertyWithValue("maxParts", 7); + assertThat(partReader).hasFieldOrPropertyWithValue("maxHeadersSize", + Math.toIntExact(DataSize.ofKilobytes(16).toBytes())); + assertThat(partReader).hasFieldOrPropertyWithValue("headersCharset", StandardCharsets.UTF_16); + assertThat(partReader).hasFieldOrPropertyWithValue("maxInMemorySize", + Math.toIntExact(DataSize.ofGigabytes(1).toBytes())); + assertThat(partReader).hasFieldOrPropertyWithValue("maxDiskUsagePerPart", + DataSize.ofMegabytes(100).toBytes()); + }); } @Test void shouldConfigureMultipartPropertiesForPartEventReader() { - this.contextRunner.withPropertyValues("spring.webflux.multipart.max-in-memory-size=1GB", - "spring.webflux.multipart.max-headers-size=16KB", "spring.webflux.multipart.headers-charset:UTF_16") - .run((context) -> { - CodecCustomizer customizer = context.getBean(CodecCustomizer.class); - DefaultServerCodecConfigurer configurer = new DefaultServerCodecConfigurer(); - customizer.customize(configurer); - PartEventHttpMessageReader partReader = getPartEventReader(configurer); - assertThat(partReader).hasFieldOrPropertyWithValue("maxHeadersSize", - Math.toIntExact(DataSize.ofKilobytes(16).toBytes())); - assertThat(partReader).hasFieldOrPropertyWithValue("headersCharset", StandardCharsets.UTF_16); - assertThat(partReader).hasFieldOrPropertyWithValue("maxInMemorySize", - Math.toIntExact(DataSize.ofGigabytes(1).toBytes())); - }); + this.contextRunner + .withPropertyValues("spring.webflux.multipart.max-in-memory-size=1GB", + "spring.webflux.multipart.max-headers-size=16KB", "spring.webflux.multipart.headers-charset:UTF_16") + .run((context) -> { + CodecCustomizer customizer = context.getBean(CodecCustomizer.class); + DefaultServerCodecConfigurer configurer = new DefaultServerCodecConfigurer(); + customizer.customize(configurer); + PartEventHttpMessageReader partReader = getPartEventReader(configurer); + assertThat(partReader).hasFieldOrPropertyWithValue("maxHeadersSize", + Math.toIntExact(DataSize.ofKilobytes(16).toBytes())); + assertThat(partReader).hasFieldOrPropertyWithValue("headersCharset", StandardCharsets.UTF_16); + assertThat(partReader).hasFieldOrPropertyWithValue("maxInMemorySize", + Math.toIntExact(DataSize.ofGigabytes(1).toBytes())); + }); } private DefaultPartHttpMessageReader getDefaultPartReader(DefaultServerCodecConfigurer codecConfigurer) { - return codecConfigurer.getReaders().stream().filter(DefaultPartHttpMessageReader.class::isInstance) - .map(DefaultPartHttpMessageReader.class::cast).findFirst() - .orElseThrow(() -> new IllegalStateException("Could not find DefaultPartHttpMessageReader")); + return codecConfigurer.getReaders() + .stream() + .filter(DefaultPartHttpMessageReader.class::isInstance) + .map(DefaultPartHttpMessageReader.class::cast) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Could not find DefaultPartHttpMessageReader")); } private PartEventHttpMessageReader getPartEventReader(DefaultServerCodecConfigurer codecConfigurer) { - return codecConfigurer.getReaders().stream().filter(PartEventHttpMessageReader.class::isInstance) - .map(PartEventHttpMessageReader.class::cast).findFirst() - .orElseThrow(() -> new IllegalStateException("Could not find PartEventHttpMessageReader")); + return codecConfigurer.getReaders() + .stream() + .filter(PartEventHttpMessageReader.class::isInstance) + .map(PartEventHttpMessageReader.class::cast) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Could not find PartEventHttpMessageReader")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java index bb575014cd..460083cfaa 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,61 +70,61 @@ class ReactiveWebServerFactoryAutoConfigurationTests { private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)); @Test void createFromConfigClass() { this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - assertThat(context.getBeansOfType(ReactiveWebServerFactory.class)).hasSize(1); - assertThat(context.getBeansOfType(WebServerFactoryCustomizer.class)).hasSize(2); - assertThat(context.getBeansOfType(ReactiveWebServerFactoryCustomizer.class)).hasSize(1); - }); + .run((context) -> { + assertThat(context.getBeansOfType(ReactiveWebServerFactory.class)).hasSize(1); + assertThat(context.getBeansOfType(WebServerFactoryCustomizer.class)).hasSize(2); + assertThat(context.getBeansOfType(ReactiveWebServerFactoryCustomizer.class)).hasSize(1); + }); } @Test void missingHttpHandler() { this.contextRunner.withUserConfiguration(MockWebServerConfiguration.class) - .run((context) -> assertThat(context.getStartupFailure()) - .isInstanceOf(ApplicationContextException.class).rootCause() - .hasMessageContaining("missing HttpHandler bean")); + .run((context) -> assertThat(context.getStartupFailure()).isInstanceOf(ApplicationContextException.class) + .rootCause() + .hasMessageContaining("missing HttpHandler bean")); } @Test void multipleHttpHandler() { this.contextRunner - .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, - TooManyHttpHandlers.class) - .run((context) -> assertThat(context.getStartupFailure()) - .isInstanceOf(ApplicationContextException.class).rootCause() - .hasMessageContaining("multiple HttpHandler beans : httpHandler,additionalHttpHandler")); + .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, + TooManyHttpHandlers.class) + .run((context) -> assertThat(context.getStartupFailure()).isInstanceOf(ApplicationContextException.class) + .rootCause() + .hasMessageContaining("multiple HttpHandler beans : httpHandler,additionalHttpHandler")); } @Test void customizeReactiveWebServer() { this.contextRunner - .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, - ReactiveWebServerCustomization.class) - .run((context) -> assertThat(context.getBean(MockReactiveWebServerFactory.class).getPort()) - .isEqualTo(9000)); + .withUserConfiguration(MockWebServerConfiguration.class, HttpHandlerConfiguration.class, + ReactiveWebServerCustomization.class) + .run((context) -> assertThat(context.getBean(MockReactiveWebServerFactory.class).getPort()) + .isEqualTo(9000)); } @Test void defaultWebServerIsTomcat() { // Tomcat should be chosen over Netty if the Tomcat library is present. - this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class).withPropertyValues("server.port=0") - .run((context) -> assertThat(context.getBean(ReactiveWebServerFactory.class)) - .isInstanceOf(TomcatReactiveWebServerFactory.class)); + this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) + .withPropertyValues("server.port=0") + .run((context) -> assertThat(context.getBean(ReactiveWebServerFactory.class)) + .isInstanceOf(TomcatReactiveWebServerFactory.class)); } @Test void tomcatConnectorCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - TomcatConnectorCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, TomcatConnectorCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", @@ -138,10 +138,10 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatConnectorCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - DoubleRegistrationTomcatConnectorCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, + DoubleRegistrationTomcatConnectorCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatConnectorCustomizer customizer = context.getBean("connectorCustomizer", @@ -155,10 +155,9 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatContextCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - TomcatContextCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, TomcatContextCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); @@ -171,10 +170,10 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatContextCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - DoubleRegistrationTomcatContextCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, + DoubleRegistrationTomcatContextCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatContextCustomizer customizer = context.getBean("contextCustomizer", TomcatContextCustomizer.class); @@ -187,10 +186,9 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatProtocolHandlerCustomizerBeanIsAddedToFactory() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - TomcatProtocolHandlerCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, TomcatProtocolHandlerCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatProtocolHandlerCustomizer customizer = context.getBean("protocolHandlerCustomizer", @@ -204,10 +202,10 @@ class ReactiveWebServerFactoryAutoConfigurationTests { void tomcatProtocolHandlerCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner( AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withUserConfiguration(HttpHandlerConfiguration.class, - DoubleRegistrationTomcatProtocolHandlerCustomizerConfiguration.class) - .withPropertyValues("server.port: 0"); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withUserConfiguration(HttpHandlerConfiguration.class, + DoubleRegistrationTomcatProtocolHandlerCustomizerConfiguration.class) + .withPropertyValues("server.port: 0"); runner.run((context) -> { TomcatReactiveWebServerFactory factory = context.getBean(TomcatReactiveWebServerFactory.class); TomcatProtocolHandlerCustomizer customizer = context.getBean("protocolHandlerCustomizer", @@ -221,106 +219,109 @@ class ReactiveWebServerFactoryAutoConfigurationTests { @Servlet5ClassPathOverrides void jettyServerCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) - .withUserConfiguration(JettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); - assertThat(factory.getServerCustomizers()).hasSize(1); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) + .withUserConfiguration(JettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); + assertThat(factory.getServerCustomizers()).hasSize(1); + }); } @Test @Servlet5ClassPathOverrides void jettyServerCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) - .withUserConfiguration(DoubleRegistrationJettyServerCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .withPropertyValues("server.port=0").run((context) -> { - JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); - JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class); - assertThat(factory.getServerCustomizers()).contains(customizer); - then(customizer).should().customize(any(Server.class)); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class)) + .withUserConfiguration(DoubleRegistrationJettyServerCustomizerConfiguration.class, + HttpHandlerConfiguration.class) + .withPropertyValues("server.port=0") + .run((context) -> { + JettyReactiveWebServerFactory factory = context.getBean(JettyReactiveWebServerFactory.class); + JettyServerCustomizer customizer = context.getBean("serverCustomizer", JettyServerCustomizer.class); + assertThat(factory.getServerCustomizers()).contains(customizer); + then(customizer).should().customize(any(Server.class)); + }); } @Test void undertowBuilderCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) - .withUserConfiguration(UndertowBuilderCustomizerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); - assertThat(factory.getBuilderCustomizers()).hasSize(1); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) + .withUserConfiguration(UndertowBuilderCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); + assertThat(factory.getBuilderCustomizers()).hasSize(1); + }); } @Test void undertowBuilderCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) - .withUserConfiguration(DoubleRegistrationUndertowBuilderCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .withPropertyValues("server.port: 0").run((context) -> { - UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); - UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer", - UndertowBuilderCustomizer.class); - assertThat(factory.getBuilderCustomizers()).contains(customizer); - then(customizer).should().customize(any(Builder.class)); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, HttpServer.class, Server.class)) + .withUserConfiguration(DoubleRegistrationUndertowBuilderCustomizerConfiguration.class, + HttpHandlerConfiguration.class) + .withPropertyValues("server.port: 0") + .run((context) -> { + UndertowReactiveWebServerFactory factory = context.getBean(UndertowReactiveWebServerFactory.class); + UndertowBuilderCustomizer customizer = context.getBean("builderCustomizer", + UndertowBuilderCustomizer.class); + assertThat(factory.getBuilderCustomizers()).contains(customizer); + then(customizer).should().customize(any(Builder.class)); + }); } @Test void nettyServerCustomizerBeanIsAddedToFactory() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) - .withUserConfiguration(NettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) - .run((context) -> { - NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); - assertThat(factory.getServerCustomizers()).hasSize(1); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) + .withUserConfiguration(NettyServerCustomizerConfiguration.class, HttpHandlerConfiguration.class) + .run((context) -> { + NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); + assertThat(factory.getServerCustomizers()).hasSize(1); + }); } @Test void nettyServerCustomizerRegisteredAsBeanAndViaFactoryIsOnlyCalledOnce() { new ReactiveWebApplicationContextRunner(AnnotationConfigReactiveWebServerApplicationContext::new) - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) - .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) - .withUserConfiguration(DoubleRegistrationNettyServerCustomizerConfiguration.class, - HttpHandlerConfiguration.class) - .withPropertyValues("server.port: 0").run((context) -> { - NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); - NettyServerCustomizer customizer = context.getBean("serverCustomizer", NettyServerCustomizer.class); - assertThat(factory.getServerCustomizers()).contains(customizer); - then(customizer).should().apply(any(HttpServer.class)); - }); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class)) + .withClassLoader(new FilteredClassLoader(Tomcat.class, Server.class, Undertow.class)) + .withUserConfiguration(DoubleRegistrationNettyServerCustomizerConfiguration.class, + HttpHandlerConfiguration.class) + .withPropertyValues("server.port: 0") + .run((context) -> { + NettyReactiveWebServerFactory factory = context.getBean(NettyReactiveWebServerFactory.class); + NettyServerCustomizer customizer = context.getBean("serverCustomizer", NettyServerCustomizer.class); + assertThat(factory.getServerCustomizers()).contains(customizer); + then(customizer).should().apply(any(HttpServer.class)); + }); } @Test void forwardedHeaderTransformerShouldBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) - .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") - .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); + .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") + .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); } @Test void forwardedHeaderTransformerWhenStrategyNotFilterShouldNotBeConfigured() { this.contextRunner.withUserConfiguration(HttpHandlerConfiguration.class) - .withPropertyValues("server.forward-headers-strategy=native", "server.port=0") - .run((context) -> assertThat(context).doesNotHaveBean(ForwardedHeaderTransformer.class)); + .withPropertyValues("server.forward-headers-strategy=native", "server.port=0") + .run((context) -> assertThat(context).doesNotHaveBean(ForwardedHeaderTransformer.class)); } @Test void forwardedHeaderTransformerWhenAlreadyRegisteredShouldBackOff() { this.contextRunner - .withUserConfiguration(ForwardedHeaderTransformerConfiguration.class, HttpHandlerConfiguration.class) - .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") - .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); + .withUserConfiguration(ForwardedHeaderTransformerConfiguration.class, HttpHandlerConfiguration.class) + .withPropertyValues("server.forward-headers-strategy=framework", "server.port=0") + .run((context) -> assertThat(context).hasSingleBean(ForwardedHeaderTransformer.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java index e5e3b771b8..8dfc0c0bbe 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java @@ -118,9 +118,9 @@ class WebFluxAutoConfigurationTests { private static final MockReactiveWebServerFactory mockReactiveWebServerFactory = new MockReactiveWebServerFactory(); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(WebFluxAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)) - .withUserConfiguration(Config.class); + .withConfiguration( + AutoConfigurations.of(WebFluxAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)) + .withUserConfiguration(Config.class); @Test void shouldNotProcessIfExistingWebReactiveConfiguration() { @@ -138,7 +138,7 @@ class WebFluxAutoConfigurationTests { assertThat(context).getBeans(RequestedContentTypeResolver.class).hasSize(1); assertThat(context).getBeans(RouterFunctionMapping.class).hasSize(1); assertThat(context.getBean(WebHttpHandlerBuilder.WEB_SESSION_MANAGER_BEAN_NAME, WebSessionManager.class)) - .isNotNull(); + .isNotNull(); assertThat(context.getBean("resourceHandlerMapping", HandlerMapping.class)).isNotNull(); }); } @@ -149,7 +149,7 @@ class WebFluxAutoConfigurationTests { this.contextRunner.withUserConfiguration(CustomArgumentResolvers.class).run((context) -> { RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class); List customResolvers = (List) ReflectionTestUtils - .getField(adapter.getArgumentResolverConfigurer(), "customResolvers"); + .getField(adapter.getArgumentResolverConfigurer(), "customResolvers"); assertThat(customResolvers).contains(context.getBean("firstResolver", HandlerMethodArgumentResolver.class), context.getBean("secondResolver", HandlerMethodArgumentResolver.class)); }); @@ -175,7 +175,7 @@ class WebFluxAutoConfigurationTests { ResourceWebHandler webjarsHandler = (ResourceWebHandler) hm.getUrlMap().get("/webjars/**"); assertThat(webjarsHandler.getLocations()).hasSize(1); assertThat(webjarsHandler.getLocations().get(0)) - .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); + .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); }); } @@ -197,15 +197,15 @@ class WebFluxAutoConfigurationTests { ResourceWebHandler webjarsHandler = (ResourceWebHandler) hm.getUrlMap().get("/assets/**"); assertThat(webjarsHandler.getLocations()).hasSize(1); assertThat(webjarsHandler.getLocations().get(0)) - .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); + .isEqualTo(new ClassPathResource("/META-INF/resources/webjars/")); }); } @Test void shouldNotMapResourcesWhenDisabled() { this.contextRunner.withPropertyValues("spring.web.resources.add-mappings:false") - .run((context) -> assertThat(context.getBean("resourceHandlerMapping")) - .isNotInstanceOf(SimpleUrlHandlerMapping.class)); + .run((context) -> assertThat(context.getBean("resourceHandlerMapping")) + .isNotInstanceOf(SimpleUrlHandlerMapping.class)); } @Test @@ -215,9 +215,9 @@ class WebFluxAutoConfigurationTests { assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); ResourceWebHandler staticHandler = (ResourceWebHandler) hm.getUrlMap().get("/**"); assertThat(staticHandler.getResourceResolvers()).extractingResultOf("getClass") - .containsOnly(CachingResourceResolver.class, PathResourceResolver.class); + .containsOnly(CachingResourceResolver.class, PathResourceResolver.class); assertThat(staticHandler.getResourceTransformers()).extractingResultOf("getClass") - .containsOnly(CachingResourceTransformer.class); + .containsOnly(CachingResourceTransformer.class); }); } @@ -256,7 +256,7 @@ class WebFluxAutoConfigurationTests { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); LocalTime time = LocalTime.of(11, 43, 10); assertThat(conversionService.convert(time, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); + .isEqualTo(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(time)); }); } @@ -275,7 +275,7 @@ class WebFluxAutoConfigurationTests { FormattingConversionService conversionService = context.getBean(FormattingConversionService.class); LocalDateTime dateTime = LocalDateTime.of(2020, 4, 28, 11, 43, 10); assertThat(conversionService.convert(dateTime, String.class)) - .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); + .isEqualTo(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(dateTime)); }); } @@ -300,19 +300,19 @@ class WebFluxAutoConfigurationTests { @Test void validatorWhenNoCustomizationShouldUseAutoConfigured() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .run((context) -> { - assertThat(context).getBeanNames(jakarta.validation.Validator.class) - .containsExactly("defaultValidator"); - assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("defaultValidator", - "webFluxValidator"); - Validator validator = context.getBean("webFluxValidator", Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); - // Primary Spring validator is the one used by WebFlux behind the - // scenes - assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); - }); + .run((context) -> { + assertThat(context).getBeanNames(jakarta.validation.Validator.class) + .containsExactly("defaultValidator"); + assertThat(context).getBeanNames(Validator.class) + .containsExactlyInAnyOrder("defaultValidator", "webFluxValidator"); + Validator validator = context.getBean("webFluxValidator", Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Object defaultValidator = context.getBean("defaultValidator"); + assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); + // Primary Spring validator is the one used by WebFlux behind the + // scenes + assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); + }); } @Test @@ -322,7 +322,7 @@ class WebFluxAutoConfigurationTests { assertThat(context).doesNotHaveBean(jakarta.validation.Validator.class); assertThat(context).getBeanNames(Validator.class).containsOnly("webFluxValidator"); assertThat(context.getBean("webFluxValidator")) - .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); + .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); }); } @@ -335,42 +335,44 @@ class WebFluxAutoConfigurationTests { Validator validator = context.getBean("webFluxValidator", Validator.class); assertThat(validator).isInstanceOf(ValidatorAdapter.class); assertThat(((ValidatorAdapter) validator).getTarget()) - .isSameAs(context.getBean(ValidatorJsr303WebFluxConfigurer.class).validator); + .isSameAs(context.getBean(ValidatorJsr303WebFluxConfigurer.class).validator); }); } @Test void validationCustomConfigurerTakesPrecedence() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(ValidatorWebFluxConfigurer.class).run((context) -> { - assertThat(context).getBeans(ValidatorFactory.class).hasSize(1); - assertThat(context).getBeans(jakarta.validation.Validator.class).hasSize(1); - assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("defaultValidator", - "webFluxValidator"); - assertThat(context.getBean("webFluxValidator")) - .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); - // Primary Spring validator is the auto-configured one as the WebFlux - // one has been customized through a WebFluxConfigurer - assertThat(context.getBean(Validator.class)).isEqualTo(context.getBean("defaultValidator")); - }); + .withUserConfiguration(ValidatorWebFluxConfigurer.class) + .run((context) -> { + assertThat(context).getBeans(ValidatorFactory.class).hasSize(1); + assertThat(context).getBeans(jakarta.validation.Validator.class).hasSize(1); + assertThat(context).getBeanNames(Validator.class) + .containsExactlyInAnyOrder("defaultValidator", "webFluxValidator"); + assertThat(context.getBean("webFluxValidator")) + .isSameAs(context.getBean(ValidatorWebFluxConfigurer.class).validator); + // Primary Spring validator is the auto-configured one as the WebFlux + // one has been customized through a WebFluxConfigurer + assertThat(context.getBean(Validator.class)).isEqualTo(context.getBean("defaultValidator")); + }); } @Test void validatorWithCustomSpringValidatorIgnored() { this.contextRunner.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)) - .withUserConfiguration(CustomSpringValidator.class).run((context) -> { - assertThat(context).getBeanNames(jakarta.validation.Validator.class) - .containsExactly("defaultValidator"); - assertThat(context).getBeanNames(Validator.class).containsExactlyInAnyOrder("customValidator", - "defaultValidator", "webFluxValidator"); - Validator validator = context.getBean("webFluxValidator", Validator.class); - assertThat(validator).isInstanceOf(ValidatorAdapter.class); - Object defaultValidator = context.getBean("defaultValidator"); - assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); - // Primary Spring validator is the one used by WebFlux behind the - // scenes - assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); - }); + .withUserConfiguration(CustomSpringValidator.class) + .run((context) -> { + assertThat(context).getBeanNames(jakarta.validation.Validator.class) + .containsExactly("defaultValidator"); + assertThat(context).getBeanNames(Validator.class) + .containsExactlyInAnyOrder("customValidator", "defaultValidator", "webFluxValidator"); + Validator validator = context.getBean("webFluxValidator", Validator.class); + assertThat(validator).isInstanceOf(ValidatorAdapter.class); + Object defaultValidator = context.getBean("defaultValidator"); + assertThat(((ValidatorAdapter) validator).getTarget()).isSameAs(defaultValidator); + // Primary Spring validator is the one used by WebFlux behind the + // scenes + assertThat(context.getBean(Validator.class)).isEqualTo(defaultValidator); + }); } @Test @@ -394,23 +396,24 @@ class WebFluxAutoConfigurationTests { @Test void hiddenHttpMethodFilterCanBeOverridden() { this.contextRunner.withPropertyValues("spring.webflux.hiddenmethod.filter.enabled=true") - .withUserConfiguration(CustomHiddenHttpMethodFilter.class).run((context) -> { - assertThat(context).doesNotHaveBean(OrderedHiddenHttpMethodFilter.class); - assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class); - }); + .withUserConfiguration(CustomHiddenHttpMethodFilter.class) + .run((context) -> { + assertThat(context).doesNotHaveBean(OrderedHiddenHttpMethodFilter.class); + assertThat(context).hasSingleBean(HiddenHttpMethodFilter.class); + }); } @Test void hiddenHttpMethodFilterCanBeEnabled() { this.contextRunner.withPropertyValues("spring.webflux.hiddenmethod.filter.enabled=true") - .run((context) -> assertThat(context).hasSingleBean(OrderedHiddenHttpMethodFilter.class)); + .run((context) -> assertThat(context).hasSingleBean(OrderedHiddenHttpMethodFilter.class)); } @Test void customRequestMappingHandlerMapping() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerMapping.class).run((context) -> { assertThat(context).getBean(RequestMappingHandlerMapping.class) - .isInstanceOf(MyRequestMappingHandlerMapping.class); + .isInstanceOf(MyRequestMappingHandlerMapping.class); assertThat(context.getBean(CustomRequestMappingHandlerMapping.class).handlerMappings).isOne(); }); } @@ -419,7 +422,7 @@ class WebFluxAutoConfigurationTests { void customRequestMappingHandlerAdapter() { this.contextRunner.withUserConfiguration(CustomRequestMappingHandlerAdapter.class).run((context) -> { assertThat(context).getBean(RequestMappingHandlerAdapter.class) - .isInstanceOf(MyRequestMappingHandlerAdapter.class); + .isInstanceOf(MyRequestMappingHandlerAdapter.class); assertThat(context.getBean(CustomRequestMappingHandlerAdapter.class).handlerAdapters).isOne(); }); } @@ -428,9 +431,9 @@ class WebFluxAutoConfigurationTests { void multipleWebFluxRegistrations() { this.contextRunner.withUserConfiguration(MultipleWebFluxRegistrations.class).run((context) -> { assertThat(context.getBean(RequestMappingHandlerMapping.class)) - .isNotInstanceOf(MyRequestMappingHandlerMapping.class); + .isNotInstanceOf(MyRequestMappingHandlerMapping.class); assertThat(context.getBean(RequestMappingHandlerAdapter.class)) - .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); + .isNotInstanceOf(MyRequestMappingHandlerAdapter.class); }); } @@ -443,7 +446,7 @@ class WebFluxAutoConfigurationTests { for (Object handler : handlerMap.values()) { if (handler instanceof ResourceWebHandler resourceWebHandler) { assertThat(resourceWebHandler.getCacheControl()).usingRecursiveComparison() - .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS)); + .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS)); } } }); @@ -453,17 +456,19 @@ class WebFluxAutoConfigurationTests { @Test void cacheControl() { Assertions.setExtractBareNamePropertyMethods(false); - this.contextRunner.withPropertyValues("spring.web.resources.cache.cachecontrol.max-age:5", - "spring.web.resources.cache.cachecontrol.proxy-revalidate:true").run((context) -> { - Map handlerMap = getHandlerMap(context); - assertThat(handlerMap).hasSize(2); - for (Object handler : handlerMap.values()) { - if (handler instanceof ResourceWebHandler resourceWebHandler) { - assertThat(resourceWebHandler.getCacheControl()).usingRecursiveComparison() - .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS).proxyRevalidate()); - } + this.contextRunner + .withPropertyValues("spring.web.resources.cache.cachecontrol.max-age:5", + "spring.web.resources.cache.cachecontrol.proxy-revalidate:true") + .run((context) -> { + Map handlerMap = getHandlerMap(context); + assertThat(handlerMap).hasSize(2); + for (Object handler : handlerMap.values()) { + if (handler instanceof ResourceWebHandler resourceWebHandler) { + assertThat(resourceWebHandler.getCacheControl()).usingRecursiveComparison() + .isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS).proxyRevalidate()); } - }); + } + }); Assertions.setExtractBareNamePropertyMethods(true); } @@ -483,21 +488,22 @@ class WebFluxAutoConfigurationTests { @Test void customPrinterAndParserShouldBeRegisteredAsConverters() { this.contextRunner.withUserConfiguration(ParserConfiguration.class, PrinterConfiguration.class) - .run((context) -> { - ConversionService service = context.getBean(ConversionService.class); - assertThat(service.convert(new Example("spring", new Date()), String.class)).isEqualTo("spring"); - assertThat(service.convert("boot", Example.class)).extracting(Example::getName).isEqualTo("boot"); - }); + .run((context) -> { + ConversionService service = context.getBean(ConversionService.class); + assertThat(service.convert(new Example("spring", new Date()), String.class)).isEqualTo("spring"); + assertThat(service.convert("boot", Example.class)).extracting(Example::getName).isEqualTo("boot"); + }); } @Test void welcomePageHandlerMapping() { this.contextRunner.withPropertyValues("spring.web.resources.static-locations=classpath:/welcome-page/") - .run((context) -> { - assertThat(context).getBeans(RouterFunctionMapping.class).hasSize(2); - assertThat(context.getBean("welcomePageRouterFunctionMapping", HandlerMapping.class)).isNotNull() - .extracting("order").isEqualTo(1); - }); + .run((context) -> { + assertThat(context).getBeans(RouterFunctionMapping.class).hasSize(2); + assertThat(context.getBean("welcomePageRouterFunctionMapping", HandlerMapping.class)).isNotNull() + .extracting("order") + .isEqualTo(1); + }); } @Test @@ -512,22 +518,24 @@ class WebFluxAutoConfigurationTests { @Test void whenFixedLocalContextResolverIsUsedThenAcceptLanguagesHeaderIsIgnored() { this.contextRunner.withPropertyValues("spring.web.locale:en_UK", "spring.web.locale-resolver=fixed") - .run((context) -> { - MockServerHttpRequest request = MockServerHttpRequest.get("/") - .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")).build(); - MockServerWebExchange exchange = MockServerWebExchange.from(request); - LocaleContextResolver localeContextResolver = context.getBean(LocaleContextResolver.class); - assertThat(localeContextResolver).isInstanceOf(FixedLocaleContextResolver.class); - LocaleContext localeContext = localeContextResolver.resolveLocaleContext(exchange); - assertThat(localeContext.getLocale()).isEqualTo(StringUtils.parseLocaleString("en_UK")); - }); + .run((context) -> { + MockServerHttpRequest request = MockServerHttpRequest.get("/") + .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")) + .build(); + MockServerWebExchange exchange = MockServerWebExchange.from(request); + LocaleContextResolver localeContextResolver = context.getBean(LocaleContextResolver.class); + assertThat(localeContextResolver).isInstanceOf(FixedLocaleContextResolver.class); + LocaleContext localeContext = localeContextResolver.resolveLocaleContext(exchange); + assertThat(localeContext.getLocale()).isEqualTo(StringUtils.parseLocaleString("en_UK")); + }); } @Test void whenAcceptHeaderLocaleContextResolverIsUsedThenAcceptLanguagesHeaderIsHonoured() { this.contextRunner.withPropertyValues("spring.web.locale:en_UK").run((context) -> { MockServerHttpRequest request = MockServerHttpRequest.get("/") - .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")).build(); + .acceptLanguageAsLocales(StringUtils.parseLocaleString("nl_NL")) + .build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); LocaleContextResolver localeContextResolver = context.getBean(LocaleContextResolver.class); assertThat(localeContextResolver).isInstanceOf(AcceptHeaderLocaleContextResolver.class); @@ -551,49 +559,52 @@ class WebFluxAutoConfigurationTests { @Test void customLocaleContextResolverWithMatchingNameReplacedAutoConfiguredLocaleContextResolver() { this.contextRunner - .withBean("localeContextResolver", CustomLocaleContextResolver.class, CustomLocaleContextResolver::new) - .run((context) -> { - assertThat(context).hasSingleBean(LocaleContextResolver.class); - assertThat(context.getBean("localeContextResolver")) - .isInstanceOf(CustomLocaleContextResolver.class); - }); + .withBean("localeContextResolver", CustomLocaleContextResolver.class, CustomLocaleContextResolver::new) + .run((context) -> { + assertThat(context).hasSingleBean(LocaleContextResolver.class); + assertThat(context.getBean("localeContextResolver")).isInstanceOf(CustomLocaleContextResolver.class); + }); } @Test void customLocaleContextResolverWithDifferentNameDoesNotReplaceAutoConfiguredLocaleContextResolver() { - this.contextRunner.withBean("customLocaleContextResolver", CustomLocaleContextResolver.class, - CustomLocaleContextResolver::new).run((context) -> { - assertThat(context.getBean("customLocaleContextResolver")) - .isInstanceOf(CustomLocaleContextResolver.class); - assertThat(context.getBean("localeContextResolver")) - .isInstanceOf(AcceptHeaderLocaleContextResolver.class); - }); + this.contextRunner + .withBean("customLocaleContextResolver", CustomLocaleContextResolver.class, + CustomLocaleContextResolver::new) + .run((context) -> { + assertThat(context.getBean("customLocaleContextResolver")) + .isInstanceOf(CustomLocaleContextResolver.class); + assertThat(context.getBean("localeContextResolver")) + .isInstanceOf(AcceptHeaderLocaleContextResolver.class); + }); } @Test @SuppressWarnings("rawtypes") void userConfigurersCanBeOrderedBeforeOrAfterTheAutoConfiguredConfigurer() { this.contextRunner.withBean(HighPrecedenceConfigurer.class, HighPrecedenceConfigurer::new) - .withBean(LowPrecedenceConfigurer.class, LowPrecedenceConfigurer::new) - .run((context) -> assertThat(context.getBean(DelegatingWebFluxConfiguration.class)) - .extracting("configurers.delegates").asList() - .extracting((configurer) -> (Class) configurer.getClass()).containsExactly( - HighPrecedenceConfigurer.class, WebFluxConfig.class, LowPrecedenceConfigurer.class)); + .withBean(LowPrecedenceConfigurer.class, LowPrecedenceConfigurer::new) + .run((context) -> assertThat(context.getBean(DelegatingWebFluxConfiguration.class)) + .extracting("configurers.delegates") + .asList() + .extracting((configurer) -> (Class) configurer.getClass()) + .containsExactly(HighPrecedenceConfigurer.class, WebFluxConfig.class, LowPrecedenceConfigurer.class)); } @Test void customWebSessionIdResolverShouldBeApplied() { - this.contextRunner.withUserConfiguration(CustomWebSessionIdResolver.class).run(assertExchangeWithSession( - (exchange) -> assertThat(exchange.getResponse().getCookies().get("TEST")).isNotEmpty())); + this.contextRunner.withUserConfiguration(CustomWebSessionIdResolver.class) + .run(assertExchangeWithSession( + (exchange) -> assertThat(exchange.getResponse().getCookies().get("TEST")).isNotEmpty())); } @Test void customSessionTimeoutConfigurationShouldBeApplied() { this.contextRunner.withPropertyValues("server.reactive.session.timeout:123") - .run((assertSessionTimeoutWithWebSession((webSession) -> { - webSession.start(); - assertThat(webSession.getMaxIdleTime()).hasSeconds(123); - }))); + .run((assertSessionTimeoutWithWebSession((webSession) -> { + webSession.start(); + assertThat(webSession.getMaxIdleTime()).hasSeconds(123); + }))); } @Test @@ -602,25 +613,25 @@ class WebFluxAutoConfigurationTests { "server.reactive.session.cookie.domain:.example.com", "server.reactive.session.cookie.path:/example", "server.reactive.session.cookie.max-age:60", "server.reactive.session.cookie.http-only:false", "server.reactive.session.cookie.secure:false", "server.reactive.session.cookie.same-site:strict") - .run(assertExchangeWithSession((exchange) -> { - List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); - assertThat(cookies).isNotEmpty(); - assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); - assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); - assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); - assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); - assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); - assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); - })); + .run(assertExchangeWithSession((exchange) -> { + List cookies = exchange.getResponse().getCookies().get("JSESSIONID"); + assertThat(cookies).isNotEmpty(); + assertThat(cookies).allMatch((cookie) -> cookie.getDomain().equals(".example.com")); + assertThat(cookies).allMatch((cookie) -> cookie.getPath().equals("/example")); + assertThat(cookies).allMatch((cookie) -> cookie.getMaxAge().equals(Duration.ofSeconds(60))); + assertThat(cookies).allMatch((cookie) -> !cookie.isHttpOnly()); + assertThat(cookies).allMatch((cookie) -> !cookie.isSecure()); + assertThat(cookies).allMatch((cookie) -> cookie.getSameSite().equals("Strict")); + })); } @ParameterizedTest @ValueSource(classes = { ServerProperties.class, WebFluxProperties.class }) void propertiesAreNotEnabledInNonWebApplication(Class propertiesClass) { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebFluxAutoConfiguration.class, - WebSessionIdResolverAutoConfiguration.class)) - .run((context) -> assertThat(context).doesNotHaveBean(propertiesClass)); + .withConfiguration( + AutoConfigurations.of(WebFluxAutoConfiguration.class, WebSessionIdResolverAutoConfiguration.class)) + .run((context) -> assertThat(context).doesNotHaveBean(propertiesClass)); } @Test @@ -631,15 +642,15 @@ class WebFluxAutoConfigurationTests { @Test void problemDetailsEnabledAddsExceptionHandler() { this.contextRunner.withPropertyValues("spring.webflux.problemdetails.enabled:true") - .run((context) -> assertThat(context).hasSingleBean(ProblemDetailsExceptionHandler.class)); + .run((context) -> assertThat(context).hasSingleBean(ProblemDetailsExceptionHandler.class)); } @Test void problemDetailsBacksOffWhenExceptionHandler() { this.contextRunner.withPropertyValues("spring.webflux.problemdetails.enabled:true") - .withUserConfiguration(CustomExceptionHandlerConfiguration.class) - .run((context) -> assertThat(context).doesNotHaveBean(ProblemDetailsExceptionHandler.class) - .hasSingleBean(CustomExceptionHandler.class)); + .withUserConfiguration(CustomExceptionHandlerConfiguration.class) + .run((context) -> assertThat(context).doesNotHaveBean(ProblemDetailsExceptionHandler.class) + .hasSingleBean(CustomExceptionHandler.class)); } private ContextConsumer assertExchangeWithSession( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java index c6c8499083..7a464da43e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WelcomePageRouterFunctionFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -63,15 +63,27 @@ class WelcomePageRouterFunctionFactoryTests { @Test void handlesRequestForStaticPageThatAcceptsTextHtml() { WebTestClient client = withStaticIndex(); - client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test void handlesRequestForStaticPageThatAcceptsAll() { WebTestClient client = withStaticIndex(); - client.get().uri("/").accept(MediaType.ALL).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test @@ -83,15 +95,26 @@ class WelcomePageRouterFunctionFactoryTests { @Test void handlesRequestWithNoAcceptHeader() { WebTestClient client = withStaticIndex(); - client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test void handlesRequestWithEmptyAcceptHeader() { WebTestClient client = withStaticIndex(); - client.get().uri("/").header(HttpHeaders.ACCEPT, "").exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .header(HttpHeaders.ACCEPT, "") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } @Test @@ -103,22 +126,40 @@ class WelcomePageRouterFunctionFactoryTests { @Test void handlesRequestForTemplateThatAcceptsTextHtml() { WebTestClient client = withTemplateIndex(); - client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-template"); + client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-template"); } @Test void handlesRequestForTemplateThatAcceptsAll() { WebTestClient client = withTemplateIndex(); - client.get().uri("/").accept(MediaType.ALL).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-template"); + client.get() + .uri("/") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-template"); } @Test void prefersAStaticResourceToATemplate() { WebTestClient client = withStaticAndTemplateIndex(); - client.get().uri("/").accept(MediaType.ALL).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo("welcome-page-static"); + client.get() + .uri("/") + .accept(MediaType.ALL) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("welcome-page-static"); } private WebTestClient withStaticIndex() { @@ -130,14 +171,16 @@ class WelcomePageRouterFunctionFactoryTests { WelcomePageRouterFunctionFactory factory = factoryWithTemplateSupport(this.noIndexLocations); TestViewResolver testViewResolver = new TestViewResolver(); return WebTestClient.bindToRouterFunction(factory.createRouterFunction()) - .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()).build(); + .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()) + .build(); } private WebTestClient withStaticAndTemplateIndex() { WelcomePageRouterFunctionFactory factory = factoryWithTemplateSupport(this.indexLocations); TestViewResolver testViewResolver = new TestViewResolver(); return WebTestClient.bindToRouterFunction(factory.createRouterFunction()) - .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()).build(); + .handlerStrategies(HandlerStrategies.builder().viewResolver(testViewResolver).build()) + .build(); } private WelcomePageRouterFunctionFactory factoryWithoutTemplateSupport(String[] locations, diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java index 6e6e2ff536..430ea1e7f1 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -72,24 +72,38 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { private final LogIdFilter logIdFilter = new LogIdFilter(); private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class, - HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, - ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, - MustacheAutoConfiguration.class)) - .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0") - .withUserConfiguration(Application.class); + .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class, + HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, ErrorWebFluxAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, MustacheAutoConfiguration.class)) + .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0") + .withUserConfiguration(Application.class); @Test void jsonError(CapturedOutput output) { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/").exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() - .jsonPath("status").isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("path").isEqualTo(("/")) - .jsonPath("message").doesNotExist().jsonPath("exception").doesNotExist().jsonPath("trace") - .doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + client.get() + .uri("/") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/")) + .jsonPath("message") + .doesNotExist() + .jsonPath("exception") + .doesNotExist() + .jsonPath("trace") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); assertThat(output).contains("500 Server Error for HTTP GET \"/\"") - .contains("java.lang.IllegalStateException: Expected!"); + .contains("java.lang.IllegalStateException: Expected!"); }); } @@ -97,10 +111,22 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { void notFound() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/notFound").exchange().expectStatus().isNotFound().expectBody().jsonPath("status") - .isEqualTo("404").jsonPath("error").isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()) - .jsonPath("path").isEqualTo(("/notFound")).jsonPath("exception").doesNotExist() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + client.get() + .uri("/notFound") + .exchange() + .expectStatus() + .isNotFound() + .expectBody() + .jsonPath("status") + .isEqualTo("404") + .jsonPath("error") + .isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/notFound")) + .jsonPath("exception") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); }); } @@ -108,9 +134,17 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { void htmlError() { this.contextRunner.withPropertyValues("server.error.include-message=always").run((context) -> { WebTestClient client = getWebClient(context); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) - .expectBody(String.class).returnResult().getResponseBody(); + String body = client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectHeader() + .contentType(TEXT_HTML_UTF8) + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(body).contains("status: 500").contains("message: Expected!"); }); } @@ -119,168 +153,300 @@ class DefaultErrorWebExceptionHandlerIntegrationTests { void bindingResultError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); - client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON).bodyValue("{}").exchange().expectStatus() - .isBadRequest().expectBody().jsonPath("status").isEqualTo("400").jsonPath("error") - .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()).jsonPath("path").isEqualTo(("/bind")) - .jsonPath("exception").doesNotExist().jsonPath("errors").doesNotExist().jsonPath("message") - .doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); + client.post() + .uri("/bind") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue("{}") + .exchange() + .expectStatus() + .isBadRequest() + .expectBody() + .jsonPath("status") + .isEqualTo("400") + .jsonPath("error") + .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/bind")) + .jsonPath("exception") + .doesNotExist() + .jsonPath("errors") + .doesNotExist() + .jsonPath("message") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); }); } @Test void bindingResultErrorIncludeMessageAndErrors() { - this.contextRunner.withPropertyValues("server.error.include-message=on-param", - "server.error.include-binding-errors=on-param").run((context) -> { - WebTestClient client = getWebClient(context); - client.post().uri("/bind?message=true&errors=true").contentType(MediaType.APPLICATION_JSON) - .bodyValue("{}").exchange().expectStatus().isBadRequest().expectBody().jsonPath("status") - .isEqualTo("400").jsonPath("error").isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) - .jsonPath("path").isEqualTo(("/bind")).jsonPath("exception").doesNotExist() - .jsonPath("errors").isArray().jsonPath("message").isNotEmpty().jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); - }); + this.contextRunner + .withPropertyValues("server.error.include-message=on-param", "server.error.include-binding-errors=on-param") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.post() + .uri("/bind?message=true&errors=true") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue("{}") + .exchange() + .expectStatus() + .isBadRequest() + .expectBody() + .jsonPath("status") + .isEqualTo("400") + .jsonPath("error") + .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) + .jsonPath("path") + .isEqualTo(("/bind")) + .jsonPath("exception") + .doesNotExist() + .jsonPath("errors") + .isArray() + .jsonPath("message") + .isNotEmpty() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void includeStackTraceOnParam() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=on-param") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=on-param") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("trace") + .exists() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void alwaysIncludeStackTrace() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=false").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=false") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("trace") + .exists() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void neverIncludeStackTrace() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").doesNotExist() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("trace") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void includeMessageOnParam() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-message=on-param") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?message=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("message").isNotEmpty() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-message=on-param") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?message=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("message") + .isNotEmpty() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void alwaysIncludeMessage() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-message=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=false").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("message").isNotEmpty() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-message=always") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=false") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("message") + .isNotEmpty() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void neverIncludeMessage() { this.contextRunner - .withPropertyValues("server.error.include-exception=true", "server.error.include-message=never") - .run((context) -> { - WebTestClient client = getWebClient(context); - client.get().uri("/?trace=true").exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") - .isEqualTo("500").jsonPath("error") - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") - .isEqualTo(IllegalStateException.class.getName()).jsonPath("message").doesNotExist() - .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); - }); + .withPropertyValues("server.error.include-exception=true", "server.error.include-message=never") + .run((context) -> { + WebTestClient client = getWebClient(context); + client.get() + .uri("/?trace=true") + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectBody() + .jsonPath("status") + .isEqualTo("500") + .jsonPath("error") + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(IllegalStateException.class.getName()) + .jsonPath("message") + .doesNotExist() + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); + }); } @Test void statusException() { this.contextRunner.withPropertyValues("server.error.include-exception=true").run((context) -> { WebTestClient client = getWebClient(context); - client.get().uri("/badRequest").exchange().expectStatus().isBadRequest().expectBody().jsonPath("status") - .isEqualTo("400").jsonPath("error").isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) - .jsonPath("exception").isEqualTo(ResponseStatusException.class.getName()).jsonPath("requestId") - .isEqualTo(this.logIdFilter.getLogId()); + client.get() + .uri("/badRequest") + .exchange() + .expectStatus() + .isBadRequest() + .expectBody() + .jsonPath("status") + .isEqualTo("400") + .jsonPath("error") + .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) + .jsonPath("exception") + .isEqualTo(ResponseStatusException.class.getName()) + .jsonPath("requestId") + .isEqualTo(this.logIdFilter.getLogId()); }); } @Test void defaultErrorView() { this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/", - "server.error.include-stacktrace=always", "server.error.include-message=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) - .expectBody(String.class).returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) - .contains("
Expected!
") - .contains("
java.lang.IllegalStateException"); - }); + .withPropertyValues("spring.mustache.prefix=classpath:/unknown/", "server.error.include-stacktrace=always", + "server.error.include-message=always") + .run((context) -> { + WebTestClient client = getWebClient(context); + String body = client.get() + .uri("/") + .accept(MediaType.TEXT_HTML) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) + .expectHeader() + .contentType(TEXT_HTML_UTF8) + .expectBody(String.class) + .returnResult() + .getResponseBody(); + assertThat(body).contains("Whitelabel Error Page") + .contains(this.logIdFilter.getLogId()) + .contains("
Expected!
") + .contains("
java.lang.IllegalStateException"); + }); } @Test void escapeHtmlInDefaultErrorView() { this.contextRunner - .withPropertyValues("spring.mustache.prefix=classpath:/unknown/", "server.error.include-message=always") - .run((context) -> { - WebTestClient client = getWebClient(context); - String body = client.get().uri("/html").accept(MediaType.TEXT_HTML).exchange().expectStatus() - .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) - .expectBody(String.class).returnResult().getResponseBody(); - assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) - .doesNotContain("")) .accept(MediaType.TEXT_HTML)) - .andExpect(status().is5xxServerError()).andReturn(); + .andExpect(status().is5xxServerError()) + .andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).contains("<script>"); assertThat(content).contains("Hello World"); @@ -92,9 +95,11 @@ class DefaultErrorViewIntegrationTests { @Test void testErrorWithSpelEscape() throws Exception { String spel = "${T(" + getClass().getName() + ").injectCall()}"; - MvcResult response = this.mockMvc.perform(get("/error") - .requestAttr("jakarta.servlet.error.exception", new RuntimeException(spel)).accept(MediaType.TEXT_HTML)) - .andExpect(status().is5xxServerError()).andReturn(); + MvcResult response = this.mockMvc + .perform(get("/error").requestAttr("jakarta.servlet.error.exception", new RuntimeException(spel)) + .accept(MediaType.TEXT_HTML)) + .andExpect(status().is5xxServerError()) + .andReturn(); String content = response.getResponse().getContentAsString(); assertThat(content).doesNotContain("injection"); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java index f0197a630f..1f4b6e4599 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -83,14 +83,14 @@ class DefaultErrorViewResolverTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultErrorViewResolver(null, new Resources())) - .withMessageContaining("ApplicationContext must not be null"); + .withMessageContaining("ApplicationContext must not be null"); } @Test void createWhenResourcePropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DefaultErrorViewResolver(mock(ApplicationContext.class), (Resources) null)) - .withMessageContaining("Resources must not be null"); + .isThrownBy(() -> new DefaultErrorViewResolver(mock(ApplicationContext.class), (Resources) null)) + .withMessageContaining("Resources must not be null"); } @Test @@ -102,21 +102,25 @@ class DefaultErrorViewResolverTests { @Test void resolveWhenExactTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved).isNotNull(); assertThat(resolved.getViewName()).isEqualTo("error/404"); - then(this.templateAvailabilityProvider).should().isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class)); + then(this.templateAvailabilityProvider).should() + .isTemplateAvailable(eq("error/404"), any(Environment.class), any(ClassLoader.class), + any(ResourceLoader.class)); then(this.templateAvailabilityProvider).shouldHaveNoMoreInteractions(); } @Test void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/503"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(false); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.SERVICE_UNAVAILABLE, this.model); assertThat(resolved.getViewName()).isEqualTo("error/5xx"); @@ -125,9 +129,11 @@ class DefaultErrorViewResolverTests { @Test void resolveWhenSeries4xxTemplateMatchShouldReturnTemplate() { given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(false); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/4xx"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/4xx"); } @@ -164,7 +170,8 @@ class DefaultErrorViewResolverTests { void resolveWhenTemplateAndResourceMatchShouldFavorTemplate() { setResourceLocation("/exact"); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(true); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(true); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); assertThat(resolved.getViewName()).isEqualTo("error/404"); } @@ -173,7 +180,8 @@ class DefaultErrorViewResolverTests { void resolveWhenExactResourceMatchAndSeriesTemplateMatchShouldFavorResource() throws Exception { setResourceLocation("/exact"); given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/404"), any(Environment.class), - any(ClassLoader.class), any(ResourceLoader.class))).willReturn(false); + any(ClassLoader.class), any(ResourceLoader.class))) + .willReturn(false); ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.NOT_FOUND, this.model); then(this.templateAvailabilityProvider).shouldHaveNoMoreInteractions(); MockHttpServletResponse response = render(resolved); @@ -195,7 +203,7 @@ class DefaultErrorViewResolverTests { private void setResourceLocation(String path) { String packageName = getClass().getPackage().getName(); this.resourcesProperties - .setStaticLocations(new String[] { "classpath:" + packageName.replace('.', '/') + path + "/" }); + .setStaticLocations(new String[] { "classpath:" + packageName.replace('.', '/') + path + "/" }); } private MockHttpServletResponse render(ModelAndView modelAndView) throws Exception { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java index 7271331a70..e4d211f546 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -63,8 +63,8 @@ class ErrorMvcAutoConfigurationTests { String responseString = ((MockHttpServletResponse) webRequest.getResponse()).getContentAsString(); assertThat(responseString).contains( "

This application has no explicit mapping for /error, so you are seeing this as a fallback.

") - .contains("
Exception message
") - .contains("
java.lang.IllegalStateException"); + .contains("
Exception message
") + .contains("
java.lang.IllegalStateException"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java index 1af4376cac..2baaf793f2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/RemappedErrorViewIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,7 @@ class RemappedErrorViewIntegrationTests { // For manual testing static void main(String[] args) { new SpringApplicationBuilder(TestConfiguration.class).properties("spring.mvc.servlet.path:spring/*") - .run(args); + .run(args); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java index 3359c134e3..1311e4d2e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/OnWsdlLocationsConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ import static org.assertj.core.api.Assertions.assertThat; class OnWsdlLocationsConditionTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestConfig.class); + .withUserConfiguration(TestConfig.class); @Test void wsdlLocationsNotDefined() { @@ -44,13 +44,13 @@ class OnWsdlLocationsConditionTests { @Test void wsdlLocationsDefinedAsCommaSeparated() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Test void wsdlLocationsDefinedAsList() { this.contextRunner.withPropertyValues("spring.webservices.wsdl-locations[0]=value1") - .run((context) -> assertThat(context).hasBean("foo")); + .run((context) -> assertThat(context).hasBean("foo")); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java index c160a64887..89aed095a3 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat; class WebServicesAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebServicesAutoConfiguration.class)); @Test void defaultConfiguration() { @@ -51,20 +51,22 @@ class WebServicesAutoConfigurationTests { @Test void customPathMustBeginWithASlash() { this.contextRunner.withPropertyValues("spring.webservices.path=invalid") - .run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class).rootCause() - .hasMessageContaining("Path must start with '/'")); + .run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .rootCause() + .hasMessageContaining("Path must start with '/'")); } @Test void customPath() { this.contextRunner.withPropertyValues("spring.webservices.path=/valid") - .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); + .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test void customPathWithTrailingSlash() { this.contextRunner.withPropertyValues("spring.webservices.path=/valid/") - .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); + .run((context) -> assertThat(getUrlMappings(context)).contains("/valid/*")); } @Test @@ -78,10 +80,11 @@ class WebServicesAutoConfigurationTests { @Test void customInitParameters() { this.contextRunner - .withPropertyValues("spring.webservices.servlet.init.key1=value1", - "spring.webservices.servlet.init.key2=value2") - .run((context) -> assertThat(getServletRegistrationBean(context).getInitParameters()) - .containsEntry("key1", "value1").containsEntry("key2", "value2")); + .withPropertyValues("spring.webservices.servlet.init.key1=value1", + "spring.webservices.servlet.init.key2=value2") + .run((context) -> assertThat(getServletRegistrationBean(context).getInitParameters()) + .containsEntry("key1", "value1") + .containsEntry("key2", "value2")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java index 6cf838fef0..c1450a1f46 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -33,21 +33,21 @@ class WebServicesPropertiesTests { void pathMustNotBeEmpty() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void pathMustHaveLengthGreaterThanOne() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("/")) - .withMessageContaining("Path must have length greater than 1"); + .withMessageContaining("Path must have length greater than 1"); } @Test void customPathMustBeginWithASlash() { this.properties = new WebServicesProperties(); assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("custom")) - .withMessageContaining("Path must start with '/'"); + .withMessageContaining("Path must start with '/'"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java index 2ecc12810a..f1bd27163c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/client/WebServiceTemplateAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; class WebServiceTemplateAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebServiceTemplateAutoConfiguration.class)); @Test void autoConfiguredBuilderShouldNotHaveMarshallerAndUnmarshaller() { @@ -70,27 +70,27 @@ class WebServiceTemplateAutoConfigurationTests { @Test void webServiceTemplateWhenHasCustomBuilderShouldUseCustomBuilder() { this.contextRunner.withUserConfiguration(CustomWebServiceTemplateBuilderConfig.class) - .run(assertWebServiceTemplateBuilder((builder) -> { - WebServiceTemplate webServiceTemplate = builder.build(); - assertThat(webServiceTemplate.getMarshaller()) - .isSameAs(CustomWebServiceTemplateBuilderConfig.marshaller); - })); + .run(assertWebServiceTemplateBuilder((builder) -> { + WebServiceTemplate webServiceTemplate = builder.build(); + assertThat(webServiceTemplate.getMarshaller()) + .isSameAs(CustomWebServiceTemplateBuilderConfig.marshaller); + })); } @Test void webServiceTemplateShouldApplyCustomizer() { this.contextRunner.withUserConfiguration(WebServiceTemplateCustomizerConfig.class) - .run(assertWebServiceTemplateBuilder((builder) -> { - WebServiceTemplate webServiceTemplate = builder.build(); - assertThat(webServiceTemplate.getUnmarshaller()) - .isSameAs(WebServiceTemplateCustomizerConfig.unmarshaller); - })); + .run(assertWebServiceTemplateBuilder((builder) -> { + WebServiceTemplate webServiceTemplate = builder.build(); + assertThat(webServiceTemplate.getUnmarshaller()) + .isSameAs(WebServiceTemplateCustomizerConfig.unmarshaller); + })); } @Test void builderShouldBeFreshForEachUse() { this.contextRunner.withUserConfiguration(DirtyWebServiceTemplateConfig.class) - .run((context) -> assertThat(context).hasNotFailed()); + .run((context) -> assertThat(context).hasNotFailed()); } private ContextConsumer assertWebServiceTemplateBuilder( diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java index ac1aad0185..d4eb88131c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/websocket/servlet/WebSocketServletAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ class WebSocketServletAutoConfigurationTests { try (AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext( configuration)) { Object serverContainer = context.getServletContext() - .getAttribute("jakarta.websocket.server.ServerContainer"); + .getAttribute("jakarta.websocket.server.ServerContainer"); assertThat(serverContainer).isInstanceOf(ServerContainer.class); } } diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java index 6a8446235d..5dfae2d5db 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/com/example/DevToolsTestApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -25,7 +25,7 @@ public class DevToolsTestApplication { public static void main(String[] args) { new SpringApplicationBuilder(DevToolsTestApplication.class).listeners(new WebServerPortFileWriter(args[0])) - .run(args); + .run(args); } } diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java index 80848cac56..d0a90c246a 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/AbstractDevToolsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -66,9 +66,9 @@ abstract class AbstractDevToolsIntegrationTests { protected int awaitServerPort() throws Exception { int port = Awaitility.waitAtMost(Duration.ofMinutes(3)) - .until(() -> new ApplicationState(this.serverPortFile, this.launchedApplication), - ApplicationState::hasServerPort) - .getServerPort(); + .until(() -> new ApplicationState(this.serverPortFile, this.launchedApplication), + ApplicationState::hasServerPort) + .getServerPort(); this.serverPortFile.delete(); this.launchedApplication.restartRemote(port); Thread.sleep(1000); @@ -98,12 +98,15 @@ abstract class AbstractDevToolsIntegrationTests { } protected void build() throws Exception { - DynamicType.Builder builder = new ByteBuddy().subclass(Object.class).name(this.name) - .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build()); + DynamicType.Builder builder = new ByteBuddy().subclass(Object.class) + .name(this.name) + .annotateType(AnnotationDescription.Builder.ofType(RestController.class).build()); for (String mapping : this.mappings) { builder = builder.defineMethod(mapping, String.class, Visibility.PUBLIC) - .intercept(FixedValue.value(mapping)).annotateMethod(AnnotationDescription.Builder - .ofType(RequestMapping.class).defineArray("value", mapping).build()); + .intercept(FixedValue.value(mapping)) + .annotateMethod(AnnotationDescription.Builder.ofType(RequestMapping.class) + .defineArray("value", mapping) + .build()); } builder.make().saveIn(this.classesDirectory); } diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java index c440eba655..50220392be 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,9 +40,9 @@ import static org.assertj.core.api.Assertions.assertThat; class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { private final TestRestTemplate template = new TestRestTemplate(new RestTemplateBuilder() - .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(HttpClients.custom() - .setRetryStrategy(new DefaultHttpRequestRetryStrategy(10, TimeValue.of(1, TimeUnit.SECONDS))) - .build()))); + .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(HttpClients.custom() + .setRetryStrategy(new DefaultHttpRequestRetryStrategy(10, TimeValue.of(1, TimeUnit.SECONDS))) + .build()))); @ParameterizedTest(name = "{0}") @MethodSource("parameters") @@ -51,7 +51,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -67,7 +67,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { controller("com.example.ControllerOne").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForEntity(urlBase + "/one", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } @ParameterizedTest(name = "{0}") @@ -77,7 +77,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -92,7 +92,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -110,7 +110,7 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); @@ -129,10 +129,10 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(new File(this.launchedApplication.getClassesDirectory(), "com/example/ControllerOne.class").delete()) - .isTrue(); + .isTrue(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForEntity(urlBase + "/one", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } @@ -143,16 +143,16 @@ class DevToolsIntegrationTests extends AbstractDevToolsIntegrationTests { String urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerTwo").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(this.template.getForObject(urlBase + "/two", String.class)).isEqualTo("two"); assertThat(new File(this.launchedApplication.getClassesDirectory(), "com/example/ControllerTwo.class").delete()) - .isTrue(); + .isTrue(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(this.template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } static Object[] parameters() { diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java index 135bcdbfb0..d5666384a4 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/DevToolsWithLazyInitializationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -40,7 +40,7 @@ class DevToolsWithLazyInitializationIntegrationTests extends AbstractDevToolsInt String urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); assertThat(template.getForEntity(urlBase + "/two", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); controller("com.example.ControllerOne").withRequestMapping("one").withRequestMapping("two").build(); urlBase = "http://localhost:" + awaitServerPort(); assertThat(template.getForObject(urlBase + "/one", String.class)).isEqualTo("one"); diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java index 757ed11f87..bbda1c26d1 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/JvmLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -59,7 +59,8 @@ class JvmLauncher implements BeforeTestExecutionCallback { File standardOut = new File(this.outputDirectory, name + ".out"); File standardError = new File(this.outputDirectory, name + ".err"); Process process = new ProcessBuilder(StringUtils.toStringArray(command)).redirectError(standardError) - .redirectOutput(standardOut).start(); + .redirectOutput(standardOut) + .start(); return new LaunchedJvm(process, standardOut, standardError); } diff --git a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java index 0fcf1d4787..51199d8289 100644 --- a/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java +++ b/spring-boot-project/spring-boot-devtools/src/intTest/java/org/springframework/boot/devtools/tests/RemoteApplicationLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -102,15 +102,15 @@ abstract class RemoteApplicationLauncher extends AbstractApplicationLauncher { private int awaitServerPort(LaunchedJvm jvm, File serverPortFile) { return Awaitility.waitAtMost(Duration.ofMinutes(3)) - .until(() -> new ApplicationState(serverPortFile, jvm), ApplicationState::hasServerPort) - .getServerPort(); + .until(() -> new ApplicationState(serverPortFile, jvm), ApplicationState::hasServerPort) + .getServerPort(); } private void awaitRemoteSpringApplication(LaunchedJvm launchedJvm) { FileContents contents = new FileContents(launchedJvm.getStandardOut()); try { - Awaitility.waitAtMost(Duration.ofMinutes(3)).until(contents::get, - containsString("Started RemoteSpringApplication")); + Awaitility.waitAtMost(Duration.ofMinutes(3)) + .until(contents::get, containsString("Started RemoteSpringApplication")); } catch (ConditionTimeoutException ex) { if (!launchedJvm.getProcess().isAlive()) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java index 914d36f0ac..5e1d401b70 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,7 +73,7 @@ public final class RemoteSpringApplication { List> listeners = new ArrayList<>(); listeners.add(new AnsiOutputApplicationListener()); listeners.add(EnvironmentPostProcessorApplicationListener - .with(EnvironmentPostProcessorsFactory.of(ConfigDataEnvironmentPostProcessor.class))); + .with(EnvironmentPostProcessorsFactory.of(ConfigDataEnvironmentPostProcessor.class))); listeners.add(new LoggingApplicationListener()); listeners.add(new RemoteUrlPropertyExtractor()); return listeners; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java index 4c363f0292..8926de5432 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -189,8 +189,10 @@ public class DevToolsDataSourceAutoConfiguration { BeanDefinition dataSourceDefinition = context.getRegistry().getBeanDefinition(dataSourceBeanNames[0]); if (dataSourceDefinition instanceof AnnotatedBeanDefinition annotatedBeanDefinition && annotatedBeanDefinition.getFactoryMethodMetadata() != null - && annotatedBeanDefinition.getFactoryMethodMetadata().getDeclaringClassName().startsWith( - DataSourceAutoConfiguration.class.getPackage().getName() + ".DataSourceConfiguration$")) { + && annotatedBeanDefinition.getFactoryMethodMetadata() + .getDeclaringClassName() + .startsWith(DataSourceAutoConfiguration.class.getPackage().getName() + + ".DataSourceConfiguration$")) { return ConditionOutcome.match(message.foundExactly("auto-configured DataSource")); } return ConditionOutcome.noMatch(message.didNotFind("an auto-configured DataSource").atAll()); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java index ac569f100f..ce5be59374 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsR2dbcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -75,7 +75,8 @@ public class DevToolsR2dbcAutoConfiguration { public void destroy() throws Exception { if (shouldShutdown()) { Mono.usingWhen(this.connectionFactory.create(), this::executeShutdown, this::closeConnection, - this::closeConnection, this::closeConnection).block(); + this::closeConnection, this::closeConnection) + .block(); this.eventPublisher.publishEvent(new R2dbcDatabaseShutdownEvent(this.connectionFactory)); } } @@ -128,7 +129,7 @@ public class DevToolsR2dbcAutoConfiguration { private boolean isAutoConfigured(AnnotatedBeanDefinition beanDefinition) { MethodMetadata methodMetadata = beanDefinition.getFactoryMethodMetadata(); return methodMetadata != null && methodMetadata.getDeclaringClassName() - .startsWith(R2dbcAutoConfiguration.class.getPackage().getName()); + .startsWith(R2dbcAutoConfiguration.class.getPackage().getName()); } } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java index 982a9e4714..b08ce3beff 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/classpath/ClassPathChangedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,8 @@ public class ClassPathChangedEvent extends ApplicationEvent { @Override public String toString() { return new ToStringCreator(this).append("changeSet", this.changeSet) - .append("restartRequired", this.restartRequired).toString(); + .append("restartRequired", this.restartRequired) + .toString(); } /** diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java index e8dd2bfe31..232df1adb9 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -134,7 +134,7 @@ public class DevToolsHomePropertiesPostProcessor implements EnvironmentPostProce private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { return Arrays.stream(loader.getFileExtensions()) - .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); + .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); } protected File getHomeDirectory() { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java index 0f89deac4c..a135e7e46a 100755 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java @@ -135,7 +135,7 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro private static Map loadDefaultProperties() { Properties properties = new Properties(); try (InputStream stream = DevToolsPropertyDefaultsPostProcessor.class - .getResourceAsStream("devtools-property-defaults.properties")) { + .getResourceAsStream("devtools-property-defaults.properties")) { if (stream == null) { throw new RuntimeException( "Failed to load devtools-property-defaults.properties because it doesn't exist"); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java index e4cc02047b..fc68becc1c 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/livereload/Connection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -96,7 +96,8 @@ class Connection { this.outputStream.writeHeaders("HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: " + accept); new Frame("{\"command\":\"hello\",\"protocols\":[\"http://livereload.com/protocols/official-7\"]," - + "\"serverName\":\"spring-boot\"}").write(this.outputStream); + + "\"serverName\":\"spring-boot\"}") + .write(this.outputStream); while (this.running) { readWebSocketFrame(); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java index b299f179d1..c46656c173 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/RemoteClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -95,7 +95,7 @@ public class RemoteClientConfiguration implements InitializingBean { Proxy proxy = this.properties.getRemote().getProxy(); if (proxy.getHost() != null && proxy.getPort() != null) { requestFactory - .setProxy(new java.net.Proxy(Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()))); + .setProxy(new java.net.Proxy(Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort()))); } return new InterceptingClientHttpRequestFactory(requestFactory, interceptors); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java index 24ce4bbbad..e7a6ac524f 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -106,7 +106,8 @@ final class ChangeableUrls implements Iterable { return urlClassLoader.getURLs(); } return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(ChangeableUrls::toURL).toArray(URL[]::new); + .map(ChangeableUrls::toURL) + .toArray(URL[]::new); } private static URL toURL(String classPathEntry) { diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java index 239d190e19..593dbf35b8 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ClassLoaderFilesResourcePatternResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -74,7 +74,7 @@ final class ClassLoaderFilesResourcePatternResolver implements ResourcePatternRe ClassLoaderFiles classLoaderFiles) { this.classLoaderFiles = classLoaderFiles; this.patternResolverDelegate = getResourcePatternResolverFactory() - .getResourcePatternResolver(applicationContext, retrieveResourceLoader(applicationContext)); + .getResourcePatternResolver(applicationContext, retrieveResourceLoader(applicationContext)); } private ResourceLoader retrieveResourceLoader(ApplicationContext applicationContext) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java index 24f24b53f0..a6b5cbf3cf 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,8 @@ class RemoteUrlPropertyExtractorTests { @AfterEach void preventRunFailuresFromPollutingLoggerContext() { ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext() - .getTurboFilterList().clear(); + .getTurboFilterList() + .clear(); } @Test @@ -50,14 +51,14 @@ class RemoteUrlPropertyExtractorTests { @Test void malformedUrl() { assertThatIllegalStateException().isThrownBy(() -> doTest("::://wibble")) - .withMessageContaining("Malformed URL '::://wibble'"); + .withMessageContaining("Malformed URL '::://wibble'"); } @Test void multipleUrls() { assertThatIllegalStateException().isThrownBy(() -> doTest("http://localhost:8080", "http://localhost:9090")) - .withMessageContaining("Multiple URLs specified"); + .withMessageContaining("Multiple URLs specified"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java index 0db015da50..5acc1ecd7a 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/DevToolsPooledDataSourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -132,16 +132,17 @@ class DevToolsPooledDataSourceAutoConfigurationTests extends AbstractDevToolsDat jdbc.execute("SELECT 1 FROM SYSIBM.SYSDUMMY1"); HikariPoolMXBean pool = dataSource.getHikariPoolMXBean(); // Prevent a race between Hikari's initialization and Derby shutdown - Awaitility.await().atMost(Duration.ofSeconds(30)).until(pool::getIdleConnections, - (idle) -> idle == dataSource.getMinimumIdle()); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(pool::getIdleConnections, (idle) -> idle == dataSource.getMinimumIdle()); context.close(); // Connect should fail as DB no longer exists assertThatExceptionOfType(SQLException.class) - .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:memory:test", new Properties())) - .satisfies((ex) -> assertThat(ex.getSQLState()).isEqualTo("XJ004")); + .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:memory:test", new Properties())) + .satisfies((ex) -> assertThat(ex.getSQLState()).isEqualTo("XJ004")); // Shut Derby down fully so that it closes its log file assertThatExceptionOfType(SQLException.class) - .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:;shutdown=true", new Properties())); + .isThrownBy(() -> new EmbeddedDriver().connect("jdbc:derby:;shutdown=true", new Properties())); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java index 9155b232d8..478e6ff283 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -153,7 +153,7 @@ class LocalDevToolsAutoConfigurationTests { properties.put("spring.devtools.livereload.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); + .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test @@ -185,7 +185,7 @@ class LocalDevToolsAutoConfigurationTests { properties.put("spring.devtools.restart.enabled", false); this.context = getContext(() -> initializeAndRun(Config.class, properties)); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); + .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); } @Test @@ -208,19 +208,20 @@ class LocalDevToolsAutoConfigurationTests { Object watcher = ReflectionTestUtils.getField(classPathWatcher, "fileSystemWatcher"); @SuppressWarnings("unchecked") Map directories = (Map) ReflectionTestUtils.getField(watcher, "directories"); - assertThat(directories).hasSize(2).containsKey(new File("src/main/java").getAbsoluteFile()) - .containsKey(new File("src/test/java").getAbsoluteFile()); + assertThat(directories).hasSize(2) + .containsKey(new File("src/main/java").getAbsoluteFile()) + .containsKey(new File("src/test/java").getAbsoluteFile()); } @Test void devToolsSwitchesJspServletToDevelopmentMode() throws Exception { this.context = getContext(() -> initializeAndRun(Config.class)); TomcatWebServer tomcatContainer = (TomcatWebServer) ((ServletWebServerApplicationContext) this.context) - .getWebServer(); + .getWebServer(); Container context = tomcatContainer.getTomcat().getHost().findChildren()[0]; StandardWrapper jspServletWrapper = (StandardWrapper) context.findChild("jsp"); EmbeddedServletOptions options = (EmbeddedServletOptions) ReflectionTestUtils - .getField(jspServletWrapper.getServlet(), "options"); + .getField(jspServletWrapper.getServlet(), "options"); assertThat(options.getDevelopment()).isTrue(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index 3acc3e9193..895adead50 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -94,7 +94,7 @@ class RemoteDevToolsAutoConfigurationTests { void disabledIfRemoteSecretIsMissing() throws Exception { this.context = getContext(() -> loadContext("a:b")); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(DispatcherFilter.class)); + .isThrownBy(() -> this.context.getBean(DispatcherFilter.class)); } @Test @@ -151,10 +151,14 @@ class RemoteDevToolsAutoConfigurationTests { void securityConfigurationShouldAllowAccess() throws Exception { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).addFilter(filter) - .build(); - mockMvc.perform(MockMvcRequestBuilders.get(DEFAULT_CONTEXT_PATH + "/restart").header(DEFAULT_SECRET_HEADER_NAME, - "supersecret")).andExpect(status().isOk()); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(springSecurity()) + .addFilter(filter) + .build(); + mockMvc + .perform(MockMvcRequestBuilders.get(DEFAULT_CONTEXT_PATH + "/restart") + .header(DEFAULT_SECRET_HEADER_NAME, "supersecret")) + .andExpect(status().isOk()); assertRestartInvoked(true); assertThat(this.context.containsBean("devtoolsSecurityFilterChain")).isTrue(); } @@ -164,11 +168,14 @@ class RemoteDevToolsAutoConfigurationTests { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret", "server.servlet.context-path:/test", "spring.devtools.remote.context-path:/custom")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).addFilter(filter) - .build(); - mockMvc.perform( - MockMvcRequestBuilders.get("/test/custom/restart").header(DEFAULT_SECRET_HEADER_NAME, "supersecret")) - .andExpect(status().isOk()); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(springSecurity()) + .addFilter(filter) + .build(); + mockMvc + .perform(MockMvcRequestBuilders.get("/test/custom/restart") + .header(DEFAULT_SECRET_HEADER_NAME, "supersecret")) + .andExpect(status().isOk()); assertRestartInvoked(true); } @@ -177,8 +184,10 @@ class RemoteDevToolsAutoConfigurationTests { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret")); DispatcherFilter filter = this.context.getBean(DispatcherFilter.class); Filter securityFilterChain = this.context.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN, Filter.class); - MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).addFilter(securityFilterChain) - .addFilter(filter).build(); + MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .addFilter(securityFilterChain) + .addFilter(filter) + .build(); mockMvc.perform(MockMvcRequestBuilders.get("/my-path")).andExpect(status().isUnauthorized()); } @@ -187,7 +196,7 @@ class RemoteDevToolsAutoConfigurationTests { this.context = getContext(() -> loadContext("spring.devtools.remote.secret:supersecret", "spring.devtools.remote.restart.enabled:false")); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean("remoteRestartHandlerMapper")); + .isThrownBy(() -> this.context.getBean("remoteRestartHandlerMapper")); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java index 1e7257e2e9..458a5826d5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class TriggerFileFilterTests { @Test void nameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new TriggerFileFilter(null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java index 54f62eea76..ee62e93085 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,7 +38,7 @@ class ClassPathChangedEventTests { @Test void changeSetMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false)) - .withMessageContaining("ChangeSet must not be null"); + .withMessageContaining("ChangeSet must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java index 10d24c88ea..1247722343 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,15 +63,15 @@ class ClassPathFileChangeListenerTests { @Test void eventPublisherMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher)) - .withMessageContaining("EventPublisher must not be null"); + .isThrownBy(() -> new ClassPathFileChangeListener(null, this.restartStrategy, this.fileSystemWatcher)) + .withMessageContaining("EventPublisher must not be null"); } @Test void restartStrategyMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher)) - .withMessageContaining("RestartStrategy must not be null"); + .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, null, this.fileSystemWatcher)) + .withMessageContaining("RestartStrategy must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index 8e88690ae2..877374e93d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,9 +53,9 @@ class ClassPathFileSystemWatcherTests { @Test void urlsMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), - mock(ClassPathRestartStrategy.class), (URL[]) null)) - .withMessageContaining("Urls must not be null"); + .isThrownBy(() -> new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), + mock(ClassPathRestartStrategy.class), (URL[]) null)) + .withMessageContaining("Urls must not be null"); } @Test @@ -83,7 +83,7 @@ class ClassPathFileSystemWatcherTests { } assertThat(events).hasSize(1); assertThat(events.get(0).getChangeSet().iterator().next()).extracting(ChangedFile::getFile) - .containsExactly(classFile); + .containsExactly(classFile); context.close(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java index a5a0d62002..1ebbac1bf4 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,7 @@ class DevToolPropertiesIntegrationTests { application.setWebApplicationType(WebApplicationType.NONE); this.context = getContext(application::run); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(MyBean.class)); + .isThrownBy(() -> this.context.getBean(MyBean.class)); } @Test @@ -109,10 +109,10 @@ class DevToolPropertiesIntegrationTests { ConfigurableEnvironment environment = this.context.getEnvironment(); String includeStackTrace = environment.getProperty("server.error.include-stacktrace"); assertThat(includeStackTrace) - .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); + .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); String includeMessage = environment.getProperty("server.error.include-message"); assertThat(includeMessage) - .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); + .isEqualTo(ErrorProperties.IncludeAttribute.ALWAYS.toString().toLowerCase(Locale.ENGLISH)); } protected ConfigurableApplicationContext getContext(Supplier supplier) diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java index bb5c3a344e..7a59b90c06 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -39,22 +39,23 @@ class ChangedFileTests { @Test void sourceDirectoryMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ChangedFile(null, new File(this.tempDir, "file"), Type.ADD)) - .withMessageContaining("SourceDirectory must not be null"); + .isThrownBy(() -> new ChangedFile(null, new File(this.tempDir, "file"), Type.ADD)) + .withMessageContaining("SourceDirectory must not be null"); } @Test void fileMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ChangedFile(new File(this.tempDir, "directory"), null, Type.ADD)) - .withMessageContaining("File must not be null"); + .isThrownBy(() -> new ChangedFile(new File(this.tempDir, "directory"), null, Type.ADD)) + .withMessageContaining("File must not be null"); } @Test void typeMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy( - () -> new ChangedFile(new File(this.tempDir, "file"), new File(this.tempDir, "directory"), null)) - .withMessageContaining("Type must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new ChangedFile(new File(this.tempDir, "file"), new File(this.tempDir, "directory"), null)) + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java index 7a9ff839c2..c4c52da7ce 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java @@ -53,7 +53,7 @@ class DirectorySnapshotTests { @Test void directoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DirectorySnapshot(null)) - .withMessageContaining("Directory must not be null"); + .withMessageContaining("Directory must not be null"); } @Test @@ -61,7 +61,7 @@ class DirectorySnapshotTests { File file = new File(this.tempDir, "file"); file.createNewFile(); assertThatIllegalArgumentException().isThrownBy(() -> new DirectorySnapshot(file)) - .withMessageContaining("Directory '" + file + "' must not be a file"); + .withMessageContaining("Directory '" + file + "' must not be a file"); } @Test @@ -103,14 +103,14 @@ class DirectorySnapshotTests { @Test void getChangedFilesSnapshotMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null)) - .withMessageContaining("Snapshot must not be null"); + .withMessageContaining("Snapshot must not be null"); } @Test void getChangedFilesSnapshotMustBeTheSameSourceDirectory() { assertThatIllegalArgumentException().isThrownBy( () -> this.initialSnapshot.getChangedFiles(new DirectorySnapshot(createTestDirectoryStructure()), null)) - .withMessageContaining("Snapshot source directory must be '" + this.directory + "'"); + .withMessageContaining("Snapshot source directory must be '" + this.directory + "'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java index 75dba75392..72705e1dd2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java @@ -47,7 +47,7 @@ class FileSnapshotTests { @Test void fileMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(null)) - .withMessageContaining("File must not be null"); + .withMessageContaining("File must not be null"); } @Test @@ -55,7 +55,7 @@ class FileSnapshotTests { File file = new File(this.tempDir, "file"); file.mkdir(); assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(file)) - .withMessageContaining("File must not be a directory"); + .withMessageContaining("File must not be a directory"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index 2b689acdfe..0e3cdca195 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -63,41 +63,41 @@ class FileSystemWatcherTests { @Test void pollIntervalMustBePositive() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1))) - .withMessageContaining("PollInterval must be positive"); + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1))) + .withMessageContaining("PollInterval must be positive"); } @Test void quietPeriodMustBePositive() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0))) - .withMessageContaining("QuietPeriod must be positive"); + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0))) + .withMessageContaining("QuietPeriod must be positive"); } @Test void pollIntervalMustBeGreaterThanQuietPeriod() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1))) - .withMessageContaining("PollInterval must be greater than QuietPeriod"); + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1))) + .withMessageContaining("PollInterval must be greater than QuietPeriod"); } @Test void listenerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addListener(null)) - .withMessageContaining("FileChangeListener must not be null"); + .withMessageContaining("FileChangeListener must not be null"); } @Test void cannotAddListenerToStartedListener() { this.watcher.start(); assertThatIllegalStateException().isThrownBy(() -> this.watcher.addListener(mock(FileChangeListener.class))) - .withMessageContaining("FileSystemWatcher already started"); + .withMessageContaining("FileSystemWatcher already started"); } @Test void sourceDirectoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceDirectory(null)) - .withMessageContaining("Directory must not be null"); + .withMessageContaining("Directory must not be null"); } @Test @@ -106,14 +106,14 @@ class FileSystemWatcherTests { assertThat(file.createNewFile()).isTrue(); assertThat(file).isFile(); assertThatIllegalArgumentException().isThrownBy(() -> this.watcher.addSourceDirectory(file)) - .withMessageContaining("Directory '" + file + "' must not be a file"); + .withMessageContaining("Directory '" + file + "' must not be a file"); } @Test void cannotAddSourceDirectoryToStartedListener() { this.watcher.start(); assertThatIllegalStateException().isThrownBy(() -> this.watcher.addSourceDirectory(this.tempDir)) - .withMessageContaining("FileSystemWatcher already started"); + .withMessageContaining("FileSystemWatcher already started"); } @Test @@ -313,8 +313,10 @@ class FileSystemWatcherTests { } private Set getAllFileChanges(List> changes) { - return changes.stream().flatMap(Set::stream) - .flatMap((changedFiles) -> changedFiles.getFiles().stream()).collect(Collectors.toSet()); + return changes.stream() + .flatMap(Set::stream) + .flatMap((changedFiles) -> changedFiles.getFiles().stream()) + .collect(Collectors.toSet()); } private File touch(File file) throws IOException { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java index 37b7c8278b..3331d28f7f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class ConnectionInputStreamTests { byte[] buffer = new byte[100]; ConnectionInputStream inputStream = new ConnectionInputStream(new ByteArrayInputStream(NO_BYTES)); assertThatIOException().isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length)) - .withMessageContaining("End of stream"); + .withMessageContaining("End of stream"); } static class LimitedInputStream extends FilterInputStream { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java index 3a4d49ae55..d54764ffef 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -36,13 +36,13 @@ class FrameTests { @Test void payloadMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Frame((String) null)) - .withMessageContaining("Payload must not be null"); + .withMessageContaining("Payload must not be null"); } @Test void typeMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Frame((Frame.Type) null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test @@ -88,14 +88,14 @@ class FrameTests { void readFragmentedNotSupported() { byte[] bytes = new byte[] { 0x0F }; assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) - .withMessageContaining("Fragmented frames are not supported"); + .withMessageContaining("Fragmented frames are not supported"); } @Test void readLargeFramesNotSupported() { byte[] bytes = new byte[] { (byte) 0x80, (byte) 0xFF }; assertThatIllegalStateException().isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) - .withMessageContaining("Large frames are not supported"); + .withMessageContaining("Large frames are not supported"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java index fa445e3ca0..2211602fcb 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/LiveReloadServerTests.java @@ -113,8 +113,8 @@ class LiveReloadServerTests { void triggerReload() throws Exception { LiveReloadWebSocketHandler handler = connect(); this.server.triggerReload(); - List messages = await().atMost(Duration.ofSeconds(10)).until(handler::getMessages, - (msgs) -> msgs.size() == 2); + List messages = await().atMost(Duration.ofSeconds(10)) + .until(handler::getMessages, (msgs) -> msgs.size() == 2); assertThat(messages.get(0)).contains("http://livereload.com/protocols/official-7"); assertThat(messages.get(1)).contains("command\":\"reload\""); } @@ -123,8 +123,8 @@ class LiveReloadServerTests { void triggerReloadWithUppercaseHeaders() throws Exception { LiveReloadWebSocketHandler handler = connect(UppercaseWebSocketClient::new); this.server.triggerReload(); - List messages = await().atMost(Duration.ofSeconds(10)).until(handler::getMessages, - (msgs) -> msgs.size() == 2); + List messages = await().atMost(Duration.ofSeconds(10)) + .until(handler::getMessages, (msgs) -> msgs.size() == 2); assertThat(messages.get(0)).contains("http://livereload.com/protocols/official-7"); assertThat(messages.get(1)).contains("command\":\"reload\""); } @@ -152,8 +152,8 @@ class LiveReloadServerTests { void serverClose() throws Exception { LiveReloadWebSocketHandler handler = connect(); this.server.stop(); - CloseStatus closeStatus = await().atMost(Duration.ofSeconds(10)).until(handler::getCloseStatus, - Objects::nonNull); + CloseStatus closeStatus = await().atMost(Duration.ofSeconds(10)) + .until(handler::getCloseStatus, Objects::nonNull); assertThat(closeStatus.getCode()).isEqualTo(1006); } @@ -303,8 +303,10 @@ class LiveReloadServerTests { remoteAddress); Stream adaptedExtensions = extensions.stream().map(WebSocketToStandardExtensionAdapter::new); ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create() - .configurator(new UppercaseWebSocketClientConfigurator(headers)).preferredSubprotocols(protocols) - .extensions(adaptedExtensions.toList()).build(); + .configurator(new UppercaseWebSocketClientConfigurator(headers)) + .preferredSubprotocols(protocols) + .extensions(adaptedExtensions.toList()) + .build(); endpointConfig.getUserProperties().putAll(getUserProperties()); Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); Callable connectTask = () -> { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java index 6420eb68ef..7b941938d1 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java @@ -67,27 +67,27 @@ class ClassPathChangeUploaderTests { @Test void urlMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader(null, this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassPathChangeUploader("", this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangeUploader("http://localhost:8080", null)) - .withMessageContaining("RequestFactory must not be null"); + .isThrownBy(() -> new ClassPathChangeUploader("http://localhost:8080", null)) + .withMessageContaining("RequestFactory must not be null"); } @Test void urlMustNotBeMalformed() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory)) - .withMessageContaining("Malformed URL 'htttttp:///ttest'"); + .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory)) + .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java index 5845181f60..df10274811 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -76,29 +76,29 @@ class DelayedLiveReloadTriggerTests { @Test void liveReloadServerMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) - .withMessageContaining("LiveReloadServer must not be null"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) + .withMessageContaining("LiveReloadServer must not be null"); } @Test void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) - .withMessageContaining("RequestFactory must not be null"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) + .withMessageContaining("RequestFactory must not be null"); } @Test void urlMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null)) - .withMessageContaining("URL must not be empty"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null)) + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeEmpty() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, "")) - .withMessageContaining("URL must not be empty"); + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, "")) + .withMessageContaining("URL must not be empty"); } @Test @@ -108,7 +108,7 @@ class DelayedLiveReloadTriggerTests { given(this.errorResponse.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR); given(this.okResponse.getStatusCode()).willReturn(HttpStatus.OK); given(this.requestFactory.createRequest(new URI(URL), HttpMethod.GET)).willThrow(new IOException()) - .willReturn(this.errorRequest, this.okRequest); + .willReturn(this.errorRequest, this.okRequest); long startTime = System.currentTimeMillis(); this.trigger.setTimings(10, 200, 30000); this.trigger.run(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java index 86e4ce66cf..5140994e32 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -74,25 +74,25 @@ class HttpHeaderInterceptorTests { @Test void constructorNullHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(null, this.value)) - .withMessageContaining("Name must not be empty"); + .withMessageContaining("Name must not be empty"); } @Test void constructorEmptyHeaderName() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor("", this.value)) - .withMessageContaining("Name must not be empty"); + .withMessageContaining("Name must not be empty"); } @Test void constructorNullHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, null)) - .withMessageContaining("Value must not be empty"); + .withMessageContaining("Value must not be empty"); } @Test void constructorEmptyHeaderValue() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderInterceptor(this.name, "")) - .withMessageContaining("Value must not be empty"); + .withMessageContaining("Value must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java index 824f5e911e..8b024eee90 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -98,7 +98,7 @@ class RemoteClientConfigurationTests { @Test void failIfNoSecret() { assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> configure("http://localhost", false)) - .withMessageContaining("required to secure your connection"); + .withMessageContaining("required to secure your connection"); } @Test @@ -115,14 +115,14 @@ class RemoteClientConfigurationTests { void liveReloadDisabled() { configure("spring.devtools.livereload.enabled:false"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); + .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test void remoteRestartDisabled() { configure("spring.devtools.remote.restart.enabled:false"); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); + .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); } private void configure(String... pairs) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index e894a13326..42eaabf10e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,7 +73,7 @@ class DispatcherFilterTests { @Test void dispatcherMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DispatcherFilter(null)) - .withMessageContaining("Dispatcher must not be null"); + .withMessageContaining("Dispatcher must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java index 984b55c6c4..45be879837 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,13 +63,13 @@ class DispatcherTests { @Test void accessManagerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(null, Collections.emptyList())) - .withMessageContaining("AccessManager must not be null"); + .withMessageContaining("AccessManager must not be null"); } @Test void mappersMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new Dispatcher(this.accessManager, null)) - .withMessageContaining("Mappers must not be null"); + .withMessageContaining("Mappers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java index a55c836139..1a234cad6e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -54,25 +54,25 @@ class HttpHeaderAccessManagerTests { @Test void headerNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET)) - .withMessageContaining("HeaderName must not be empty"); + .withMessageContaining("HeaderName must not be empty"); } @Test void headerNameMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager("", SECRET)) - .withMessageContaining("HeaderName must not be empty"); + .withMessageContaining("HeaderName must not be empty"); } @Test void expectedSecretMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null)) - .withMessageContaining("ExpectedSecret must not be empty"); + .withMessageContaining("ExpectedSecret must not be empty"); } @Test void expectedSecretMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpHeaderAccessManager(HEADER, "")) - .withMessageContaining("ExpectedSecret must not be empty"); + .withMessageContaining("ExpectedSecret must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java index 59ae3a8963..4adef39624 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ class HttpStatusHandlerTests { @Test void statusMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusHandler(null)) - .withMessageContaining("Status must not be null"); + .withMessageContaining("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index 807239827e..7febedbb17 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,19 +40,19 @@ class UrlHandlerMapperTests { @Test void requestUriMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper(null, this.handler)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void requestUriMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("", this.handler)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void requestUrlMustStartWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> new UrlHandlerMapper("tunnel", this.handler)) - .withMessageContaining("URL must start with '/'"); + .withMessageContaining("URL must start with '/'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java index e747b22c85..354fd1d7e3 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/ChangeableUrlsTests.java @@ -114,8 +114,8 @@ class ChangeableUrlsTests { File classpathJar = new File(this.tempDir, "classpath.jar"); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); - manifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), - StringUtils.arrayToDelimitedString(urls, " ")); + manifest.getMainAttributes() + .putValue(Attributes.Name.CLASS_PATH.toString(), StringUtils.arrayToDelimitedString(urls, " ")); new JarOutputStream(new FileOutputStream(classpathJar), manifest).close(); return classpathJar; } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index 39c60e3bdc..40c3e55233 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ class MainMethodTests { @Test void threadMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new MainMethod(null)) - .withMessageContaining("Thread must not be null"); + .withMessageContaining("Thread must not be null"); } @Test @@ -59,13 +59,13 @@ class MainMethodTests { @Test void missingArgsMainMethod() { assertThatIllegalStateException().isThrownBy(() -> new TestThread(MissingArgs::main).test()) - .withMessageContaining("Unable to find main method"); + .withMessageContaining("Unable to find main method"); } @Test void nonStatic() { assertThatIllegalStateException().isThrownBy(() -> new TestThread(() -> new NonStaticMain().main()).test()) - .withMessageContaining("Unable to find main method"); + .withMessageContaining("Unable to find main method"); } static class TestThread extends Thread { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index cd19dd5bbd..7c329dd786 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -75,7 +75,7 @@ class RestarterTests { void cantGetInstanceBeforeInitialize() { Restarter.clearInstance(); assertThatIllegalStateException().isThrownBy(Restarter::getInstance) - .withMessageContaining("Restarter has not been initialized"); + .withMessageContaining("Restarter has not been initialized"); } @Test @@ -102,7 +102,7 @@ class RestarterTests { @Test void addUrlsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addUrls(null)) - .withMessageContaining("Urls must not be null"); + .withMessageContaining("Urls must not be null"); } @Test @@ -119,7 +119,7 @@ class RestarterTests { @Test void addClassLoaderFilesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> Restarter.getInstance().addClassLoaderFiles(null)) - .withMessageContaining("ClassLoaderFiles must not be null"); + .withMessageContaining("ClassLoaderFiles must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java index 982c6318df..db89e0b2d7 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,25 +35,25 @@ class ClassLoaderFileTests { @Test void kindMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(null, null)) - .withMessageContaining("Kind must not be null"); + .withMessageContaining("Kind must not be null"); } @Test void addedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null)) - .withMessageContaining("Contents must not be null"); + .withMessageContaining("Contents must not be null"); } @Test void modifiedContentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null)) - .withMessageContaining("Contents must not be null"); + .withMessageContaining("Contents must not be null"); } @Test void deletedContentsMustBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10])) - .withMessageContaining("Contents must be null"); + .withMessageContaining("Contents must be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index ae5cbbcae9..a965dcefea 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java @@ -43,13 +43,13 @@ class ClassLoaderFilesTests { @Test void addFileNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile(null, mock(ClassLoaderFile.class))) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void addFileFileMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.files.addFile("test", null)) - .withMessageContaining("File must not be null"); + .withMessageContaining("File must not be null"); } @Test @@ -153,7 +153,7 @@ class ClassLoaderFilesTests { @Test void classLoaderFilesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFiles(null)) - .withMessageContaining("ClassLoaderFiles must not be null"); + .withMessageContaining("ClassLoaderFiles must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java index 5edfe7d931..488af96235 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java @@ -104,14 +104,14 @@ class RestartClassLoaderTests { @Test void parentMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RestartClassLoader(null, new URL[] {})) - .withMessageContaining("Parent must not be null"); + .withMessageContaining("Parent must not be null"); } @Test void updatedFilesMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) - .withMessageContaining("UpdatedFiles must not be null"); + .isThrownBy(() -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) + .withMessageContaining("UpdatedFiles must not be null"); } @Test @@ -189,7 +189,7 @@ class RestartClassLoaderTests { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); + .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); } @Test @@ -197,7 +197,7 @@ class RestartClassLoaderTests { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, new byte[10])); assertThatExceptionOfType(ClassFormatError.class) - .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); + .isThrownBy(() -> Class.forName(PACKAGE + ".Sample", false, this.reloadClassLoader)); } @Test @@ -222,13 +222,14 @@ class RestartClassLoaderTests { try (RestartClassLoader restartClassLoader = new RestartClassLoader(ExampleTransactional.class.getClassLoader(), new URL[] { this.sampleJarFile.toURI().toURL() }, this.updatedFiles)) { new ApplicationContextRunner().withClassLoader(restartClassLoader) - .withUserConfiguration(ProxyConfiguration.class).run((context) -> { - assertThat(context).hasNotFailed(); - ExampleTransactional transactional = context.getBean(ExampleTransactional.class); - assertThat(AopUtils.isCglibProxy(transactional)).isTrue(); - assertThat(transactional.getClass().getClassLoader()) - .isEqualTo(ExampleTransactional.class.getClassLoader()); - }); + .withUserConfiguration(ProxyConfiguration.class) + .run((context) -> { + assertThat(context).hasNotFailed(); + ExampleTransactional transactional = context.getBean(ExampleTransactional.class); + assertThat(AopUtils.isCglibProxy(transactional)).isTrue(); + assertThat(transactional.getClass().getClassLoader()) + .isEqualTo(ExampleTransactional.class.getClassLoader()); + }); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java index 25c6c7cb4c..8d0ec158fc 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class HttpRestartServerHandlerTests { @Test void serverMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServerHandler(null)) - .withMessageContaining("Server must not be null"); + .withMessageContaining("Server must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index 7c70e4c11f..d63349ab7e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,13 +64,13 @@ class HttpRestartServerTests { @Test void sourceDirectoryUrlFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((SourceDirectoryUrlFilter) null)) - .withMessageContaining("SourceDirectoryUrlFilter must not be null"); + .withMessageContaining("SourceDirectoryUrlFilter must not be null"); } @Test void restartServerMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpRestartServer((RestartServer) null)) - .withMessageContaining("RestartServer must not be null"); + .withMessageContaining("RestartServer must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java index 2f48b2f3f7..1305a65d48 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class RestartServerTests { @Test void sourceDirectoryUrlFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RestartServer((SourceDirectoryUrlFilter) null)) - .withMessageContaining("SourceDirectoryUrlFilter must not be null"); + .withMessageContaining("SourceDirectoryUrlFilter must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java index 5beb7c9c76..b44fafba53 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java @@ -73,26 +73,26 @@ class HttpTunnelConnectionTests { @Test void urlMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(null, this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection("", this.requestFactory)) - .withMessageContaining("URL must not be empty"); + .withMessageContaining("URL must not be empty"); } @Test void urlMustNotBeMalformed() { assertThatIllegalArgumentException() - .isThrownBy(() -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) - .withMessageContaining("Malformed URL 'htttttp:///ttest'"); + .isThrownBy(() -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) + .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test void requestFactoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelConnection(this.url, null)) - .withMessageContaining("RequestFactory must not be null"); + .withMessageContaining("RequestFactory must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java index a773e96001..491193368b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java @@ -46,13 +46,13 @@ class TunnelClientTests { @Test void listenPortMustNotBeNegative() { assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(-5, this.tunnelConnection)) - .withMessageContaining("ListenPort must be greater than or equal to 0"); + .withMessageContaining("ListenPort must be greater than or equal to 0"); } @Test void tunnelConnectionMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(1, null)) - .withMessageContaining("TunnelConnection must not be null"); + .withMessageContaining("TunnelConnection must not be null"); } @Test @@ -73,8 +73,9 @@ class TunnelClientTests { TunnelClient client = new TunnelClient(0, this.tunnelConnection); int port = client.start(); SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(this.tunnelConnection::getOpenedTimes, - (open) -> open == 1); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(this.tunnelConnection::getOpenedTimes, (open) -> open == 1); channel.close(); client.getServerThread().stopAcceptingConnections(); client.getServerThread().join(2000); @@ -87,8 +88,9 @@ class TunnelClientTests { TunnelClient client = new TunnelClient(0, this.tunnelConnection); int port = client.start(); SocketChannel channel = SocketChannel.open(new InetSocketAddress(port)); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(this.tunnelConnection::getOpenedTimes, - (times) -> times == 1); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(this.tunnelConnection::getOpenedTimes, (times) -> times == 1); assertThat(this.tunnelConnection.isOpen()).isTrue(); client.stop(); assertThat(this.tunnelConnection.isOpen()).isFalse(); diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java index 4d0499c8af..5907ee1845 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class HttpTunnelPayloadForwarderTests { @Test void targetChannelMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayloadForwarder(null)) - .withMessageContaining("TargetChannel must not be null"); + .withMessageContaining("TargetChannel must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index bc09a72c10..ca36ddaa70 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java @@ -51,13 +51,13 @@ class HttpTunnelPayloadTests { @Test void sequenceMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(0, ByteBuffer.allocate(1))) - .withMessageContaining("Sequence must be positive"); + .withMessageContaining("Sequence must be positive"); } @Test void dataMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelPayload(1, null)) - .withMessageContaining("Data must not be null"); + .withMessageContaining("Data must not be null"); } @Test @@ -98,7 +98,7 @@ class HttpTunnelPayloadTests { servletRequest.setContent("hello".getBytes()); HttpInputMessage request = new ServletServerHttpRequest(servletRequest); assertThatIllegalStateException().isThrownBy(() -> HttpTunnelPayload.get(request)) - .withMessageContaining("Missing sequence header"); + .withMessageContaining("Missing sequence header"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java index 50f8907fa8..b046248393 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class HttpTunnelServerHandlerTests { @Test void serverMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServerHandler(null)) - .withMessageContaining("Server must not be null"); + .withMessageContaining("Server must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index 895d26cd9c..24f1268d04 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -99,7 +99,7 @@ class HttpTunnelServerTests { @Test void serverConnectionIsRequired() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServer(null)) - .withMessageContaining("ServerConnection must not be null"); + .withMessageContaining("ServerConnection must not be null"); } @Test @@ -121,7 +121,7 @@ class HttpTunnelServerTests { @Test void longPollTimeoutMustBePositiveValue() { assertThatIllegalArgumentException().isThrownBy(() -> this.server.setLongPollTimeout(0)) - .withMessageContaining("LongPollTimeout must be a positive value"); + .withMessageContaining("LongPollTimeout must be a positive value"); } @Test @@ -239,12 +239,14 @@ class HttpTunnelServerTests { this.server.setLongPollTimeout(100); MockHttpConnection h1 = new MockHttpConnection(); this.server.handle(h1); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(h1.getServletResponse()::getStatus, - (status) -> status == 204); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(h1.getServletResponse()::getStatus, (status) -> status == 204); MockHttpConnection h2 = new MockHttpConnection(); this.server.handle(h2); - Awaitility.await().atMost(Duration.ofSeconds(30)).until(h2.getServletResponse()::getStatus, - (status) -> status == 204); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(h2.getServletResponse()::getStatus, (status) -> status == 204); this.serverChannel.disconnect(); this.server.getServerThread().join(JOIN_TIMEOUT); } @@ -264,7 +266,7 @@ class HttpTunnelServerTests { @Test void disconnectTimeoutMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> this.server.setDisconnectTimeout(0)) - .withMessageContaining("DisconnectTimeout must be a positive value"); + .withMessageContaining("DisconnectTimeout must be a positive value"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java index 9ac1d42baa..4862af3f5d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,11 +78,12 @@ class SocketTargetServerConnectionTests { try (ByteChannel channel = this.connection.open(10)) { long startTime = System.currentTimeMillis(); assertThatExceptionOfType(SocketTimeoutException.class) - .isThrownBy(() -> channel.read(ByteBuffer.allocate(5))).satisfies((ex) -> { - long runTime = System.currentTimeMillis() - startTime; - assertThat(runTime).isGreaterThanOrEqualTo(10L); - assertThat(runTime).isLessThan(10000L); - }); + .isThrownBy(() -> channel.read(ByteBuffer.allocate(5))) + .satisfies((ex) -> { + long runTime = System.currentTimeMillis() - startTime; + assertThat(runTime).isGreaterThanOrEqualTo(10L); + assertThat(runTime).isLessThan(10000L); + }); } } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java index bba395acac..961074e8e3 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -31,7 +31,7 @@ class StaticPortProviderTests { @Test void portMustBePositive() { assertThatIllegalArgumentException().isThrownBy(() -> new StaticPortProvider(0)) - .withMessageContaining("Port must be positive"); + .withMessageContaining("Port must be positive"); } @Test diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java index abb96d5d0b..082b8c2707 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/data/nosql/neo4j/connecting/MyBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -34,10 +34,13 @@ public class MyBean { // @fold:on // ... public String someMethod(String message) { try (Session session = this.driver.session()) { - return session.executeWrite((transaction) -> transaction - .run("CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)", - Values.parameters("message", message)) - .single().get(0).asString()); + return session.executeWrite( + (transaction) -> transaction + .run("CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)", + Values.parameters("message", message)) + .single() + .get(0) + .asString()); } } // @fold:off diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java index 03269ecf55..ca771b29fa 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/testing/MyServiceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -30,7 +30,7 @@ class MyServiceAutoConfigurationTests { // tag::runner[] private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MyServiceAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MyServiceAutoConfiguration.class)); // end::runner[] @@ -48,7 +48,7 @@ class MyServiceAutoConfigurationTests { @Test void serviceIsIgnoredIfLibraryIsNotPresent() { this.contextRunner.withClassLoader(new FilteredClassLoader(MyService.class)) - .run((context) -> assertThat(context).doesNotHaveBean("myService")); + .run((context) -> assertThat(context).doesNotHaveBean("myService")); } // end::test-classloader[] diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java index 3f108b5205..354009771c 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class MyJsonAssertJTests { void someTest() throws Exception { SomeObject value = new SomeObject(0.152f); assertThat(this.json.write(value)).extractingJsonPathNumberValue("@.test.numberValue") - .satisfies((number) -> assertThat(number.floatValue()).isCloseTo(0.15f, within(0.01f))); + .satisfies((number) -> assertThat(number.floatValue()).isCloseTo(0.15f, within(0.01f))); } // end::code[] diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java index 2ff2a08ea6..5e07dd2c85 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GraphQlIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -30,11 +30,13 @@ class GraphQlIntegrationTests { @Test void shouldGreetWithSpecificName(@Autowired HttpGraphQlTester graphQlTester) { HttpGraphQlTester authenticatedTester = graphQlTester.mutate() - .webTestClient( - (client) -> client.defaultHeaders((headers) -> headers.setBasicAuth("admin", "ilovespring"))) - .build(); - authenticatedTester.document("{ greeting(name: \"Alice\") } ").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Alice!"); + .webTestClient((client) -> client.defaultHeaders((headers) -> headers.setBasicAuth("admin", "ilovespring"))) + .build(); + authenticatedTester.document("{ greeting(name: \"Alice\") } ") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Alice!"); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java index 951bd126d0..a1de2f6e05 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/springbootapplications/springgraphqltests/GreetingControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -31,14 +31,20 @@ class GreetingControllerTests { @Test void shouldGreetWithSpecificName() { - this.graphQlTester.document("{ greeting(name: \"Alice\") } ").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Alice!"); + this.graphQlTester.document("{ greeting(name: \"Alice\") } ") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Alice!"); } @Test void shouldGreetWithDefaultName() { - this.graphQlTester.document("{ greeting } ").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Spring!"); + this.graphQlTester.document("{ greeting } ") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Spring!"); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java index f4dc7bb957..77847fdf40 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class MySpringBootTests { @Bean RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(1)) - .setReadTimeout(Duration.ofSeconds(1)); + .setReadTimeout(Duration.ofSeconds(1)); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java index e271157fae..7a13e2df9b 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/io/restclient/resttemplate/customization/MyRestTemplateBuilderConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -28,8 +28,9 @@ public class MyRestTemplateBuilderConfiguration { @Bean public RestTemplateBuilder restTemplateBuilder(RestTemplateBuilderConfigurer configurer) { - return configurer.configure(new RestTemplateBuilder()).setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2)); + return configurer.configure(new RestTemplateBuilder()) + .setConnectTimeout(Duration.ofSeconds(5)) + .setReadTimeout(Duration.ofSeconds(2)); } } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/nativeimage/introducinggraalvmnativeimages/understandingaotprocessing/sourcecodegeneration/MyConfiguration__BeanDefinitions.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/nativeimage/introducinggraalvmnativeimages/understandingaotprocessing/sourcecodegeneration/MyConfiguration__BeanDefinitions.java index da47a459d0..3bea7555e5 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/nativeimage/introducinggraalvmnativeimages/understandingaotprocessing/sourcecodegeneration/MyConfiguration__BeanDefinitions.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/nativeimage/introducinggraalvmnativeimages/understandingaotprocessing/sourcecodegeneration/MyConfiguration__BeanDefinitions.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,8 @@ public class MyConfiguration__BeanDefinitions { * Get the bean instance supplier for 'myBean'. */ private static BeanInstanceSupplier getMyBeanInstanceSupplier() { - return BeanInstanceSupplier.forFactoryMethod(MyConfiguration.class, "myBean").withGenerator( - (registeredBean) -> registeredBean.getBeanFactory().getBean(MyConfiguration.class).myBean()); + return BeanInstanceSupplier.forFactoryMethod(MyConfiguration.class, "myBean") + .withGenerator((registeredBean) -> registeredBean.getBeanFactory().getBean(MyConfiguration.class).myBean()); } /** diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java index 9df5ff0c53..8e5a25279a 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/graphql/transports/rsocket/RSocketGraphQlClientExample.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,8 @@ public class RSocketGraphQlClientExample { public void rsocketOverTcp() { // tag::request[] Mono book = this.graphQlClient.document("{ bookById(id: \"book-1\"){ id name pageCount author } }") - .retrieve("bookById").toEntity(Book.class); + .retrieve("bookById") + .toEntity(Book.class); // end::request[] book.block(Duration.ofSeconds(5)); } diff --git a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java index f97ad97c25..797773dc2a 100644 --- a/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java +++ b/spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/saml2/relyingparty/MySamlRelyingPartyConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -29,7 +29,7 @@ public class MySamlRelyingPartyConfiguration { http.authorizeHttpRequests().anyRequest().authenticated(); http.saml2Login(); http.saml2Logout((saml2) -> saml2.logoutRequest((request) -> request.logoutUrl("/SLOService.saml2")) - .logoutResponse((response) -> response.logoutUrl("/SLOService.saml2"))); + .logoutResponse((response) -> response.logoutUrl("/SLOService.saml2"))); return http.build(); } diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java index 6e3d9c6a3c..6740b9d9b6 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -36,33 +36,33 @@ import static org.assertj.core.api.Assertions.assertThat; class MyPropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Config.class); + .withUserConfiguration(Config.class); @Test void bindWithDefaultUnit() { this.contextRunner.withPropertyValues("my.session-timeout=40", "my.read-timeout=5000") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(40); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(40); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithExplicitUnit() { this.contextRunner.withPropertyValues("my.session-timeout=1h", "my.read-timeout=5s") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasMinutes(60); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasMinutes(60); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithIso8601Format() { this.contextRunner.withPropertyValues("my.session-timeout=PT15S", "my.read-timeout=PT0.5S") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(15); - assertThat(properties.getReadTimeout()).hasMillis(500); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(15); + assertThat(properties.getReadTimeout()).hasMillis(500); + })); } private ContextConsumer assertBinding(Consumer properties) { diff --git a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java index d5652489ff..cd1540d0ba 100644 --- a/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java +++ b/spring-boot-project/spring-boot-docs/src/test/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -36,33 +36,33 @@ import static org.assertj.core.api.Assertions.assertThat; class MyPropertiesTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(Config.class); + .withUserConfiguration(Config.class); @Test void bindWithDefaultUnit() { this.contextRunner.withPropertyValues("my.session-timeout=40", "my.read-timeout=5000") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(40); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(40); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithExplicitUnit() { this.contextRunner.withPropertyValues("my.session-timeout=1h", "my.read-timeout=5s") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasMinutes(60); - assertThat(properties.getReadTimeout()).hasMillis(5000); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasMinutes(60); + assertThat(properties.getReadTimeout()).hasMillis(5000); + })); } @Test void bindWithIso8601Format() { this.contextRunner.withPropertyValues("my.session-timeout=PT15S", "my.read-timeout=PT0.5S") - .run(assertBinding((properties) -> { - assertThat(properties.getSessionTimeout()).hasSeconds(15); - assertThat(properties.getReadTimeout()).hasMillis(500); - })); + .run(assertBinding((properties) -> { + assertThat(properties.getSessionTimeout()).hasSeconds(15); + assertThat(properties.getReadTimeout()).hasMillis(500); + })); } private ContextConsumer assertBinding(Consumer properties) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/observability/ObservabilityContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/observability/ObservabilityContextCustomizerFactory.java index e486874a8a..ab1791fb21 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/observability/ObservabilityContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/actuate/observability/ObservabilityContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -82,8 +82,10 @@ class ObservabilityContextCustomizerFactory implements ContextCustomizerFactory public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { if (this.disableMetrics) { - TestPropertyValues.of("management.defaults.metrics.export.enabled=false", - "management.simple.metrics.export.enabled=true").applyTo(context); + TestPropertyValues + .of("management.defaults.metrics.export.enabled=false", + "management.simple.metrics.export.enabled=true") + .applyTo(context); } if (this.disableTracing) { TestPropertyValues.of("management.tracing.enabled=false").applyTo(context); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java index c0fc1a76c2..4238e64b5d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -31,8 +31,10 @@ class DataCassandraTestContextBootstrapper extends SpringBootTestContextBootstra @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataCassandraTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataCassandraTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java index f25b62de58..86fb4c2dc6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -31,8 +31,10 @@ class DataCouchbaseTestContextBootstrapper extends SpringBootTestContextBootstra @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataCouchbaseTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataCouchbaseTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java index 77b276c969..e23e629505 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -31,8 +31,10 @@ class DataElasticsearchTestContextBootstrapper extends SpringBootTestContextBoot @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataElasticsearchTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataElasticsearchTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java index 691403e1cb..9c99f9b296 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class DataJdbcTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataJdbcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataJdbcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java index 66a74aaf8b..827c313c20 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class DataLdapTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataLdapTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataLdapTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java index 1c63e98ba1..6a973d302d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class DataMongoTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataMongoTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataMongoTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java index 0a958a7586..85bc9639d5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class DataNeo4jTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataNeo4jTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataNeo4jTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java index 3da527a338..26e1308e98 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/r2dbc/DataR2dbcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class DataR2dbcTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataR2dbcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataR2dbcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java index 98a9dec100..a5530b4bea 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class DataRedisTestContextBootstrapper extends SpringBootTestContextBootstrapper @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataRedisTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataRedisTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java index 5be894812a..8a9f0da2cf 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/StandardAnnotationCustomizableTypeExcludeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ public abstract class StandardAnnotationCustomizableTypeExcludeFilter testClass) { this.annotation = MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) - .get(getAnnotationType()); + .get(getAnnotationType()); } protected final MergedAnnotation getAnnotation() { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java index 407fb823e7..c687ce06c3 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFiltersContextCustomizerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class TypeExcludeFiltersContextCustomizerFactory implements ContextCustomizerFac return null; } AnnotationDescriptor descriptor = TestContextAnnotationUtils - .findAnnotationDescriptor(testClass, TypeExcludeFilters.class); + .findAnnotationDescriptor(testClass, TypeExcludeFilters.class); Class[] filterClasses = (descriptor != null) ? descriptor.getAnnotation().value() : NO_FILTERS; if (ObjectUtils.isEmpty(filterClasses)) { return null; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java index f6618ed17f..4f8971fe09 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/graphql/GraphQlTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2022 the original author or authors. + * Copyright 2020-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. @@ -30,7 +30,9 @@ class GraphQlTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { return MergedAnnotations.from(testClass, MergedAnnotations.SearchStrategy.INHERITED_ANNOTATIONS) - .get(GraphQlTest.class).getValue("properties", String[].class).orElse(null); + .get(GraphQlTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java index d91547ab4e..a2eebe37d6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class JdbcTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JdbcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(JdbcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java index d2be5ad9bd..770bdd79b0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class JooqTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JooqTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(JooqTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java index 6dc84ac874..55a2119879 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/json/JsonTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class JsonTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(JsonTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(JsonTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java index 3d30008d75..0fdbbb9c37 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class DataJpaTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(DataJpaTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(DataJpaTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java index f30495ea2e..5987729cd8 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,18 +64,20 @@ public class AnnotationsPropertySource extends EnumerablePropertySource } private void getProperties(Class source, Map properties) { - MergedAnnotations.from(source, SearchStrategy.SUPERCLASS).stream() - .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getType)).forEach((annotation) -> { - Class type = annotation.getType(); - MergedAnnotation typeMapping = MergedAnnotations.from(type).get(PropertyMapping.class, - MergedAnnotation::isDirectlyPresent); - String prefix = typeMapping.getValue(MergedAnnotation.VALUE, String.class).orElse(""); - SkipPropertyMapping defaultSkip = typeMapping.getValue("skip", SkipPropertyMapping.class) - .orElse(SkipPropertyMapping.YES); - for (Method attribute : type.getDeclaredMethods()) { - collectProperties(prefix, defaultSkip, annotation, attribute, properties); - } - }); + MergedAnnotations.from(source, SearchStrategy.SUPERCLASS) + .stream() + .filter(MergedAnnotationPredicates.unique(MergedAnnotation::getType)) + .forEach((annotation) -> { + Class type = annotation.getType(); + MergedAnnotation typeMapping = MergedAnnotations.from(type) + .get(PropertyMapping.class, MergedAnnotation::isDirectlyPresent); + String prefix = typeMapping.getValue(MergedAnnotation.VALUE, String.class).orElse(""); + SkipPropertyMapping defaultSkip = typeMapping.getValue("skip", SkipPropertyMapping.class) + .orElse(SkipPropertyMapping.YES); + for (Method attribute : type.getDeclaredMethods()) { + collectProperties(prefix, defaultSkip, annotation, attribute, properties); + } + }); if (TestContextAnnotationUtils.searchEnclosingClass(source)) { getProperties(source.getEnclosingClass(), properties); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java index 03a5911fb0..2dde81b33d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -51,8 +51,9 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { if (!this.propertySource.isEmpty()) { context.getEnvironment().getPropertySources().addFirst(this.propertySource); } - context.getBeanFactory().registerSingleton(PropertyMappingCheckBeanPostProcessor.class.getName(), - new PropertyMappingCheckBeanPostProcessor()); + context.getBeanFactory() + .registerSingleton(PropertyMappingCheckBeanPostProcessor.class.getName(), + new PropertyMappingCheckBeanPostProcessor()); } @Override @@ -76,10 +77,12 @@ class PropertyMappingContextCustomizer implements ContextCustomizer { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class beanClass = bean.getClass(); MergedAnnotations annotations = MergedAnnotations.from(beanClass, SearchStrategy.SUPERCLASS); - Set> components = annotations.stream(Component.class).map(this::getRoot) - .collect(Collectors.toSet()); - Set> propertyMappings = annotations.stream(PropertyMapping.class).map(this::getRoot) - .collect(Collectors.toSet()); + Set> components = annotations.stream(Component.class) + .map(this::getRoot) + .collect(Collectors.toSet()); + Set> propertyMappings = annotations.stream(PropertyMapping.class) + .map(this::getRoot) + .collect(Collectors.toSet()); if (!components.isEmpty() && !propertyMappings.isEmpty()) { throw new IllegalStateException("The @PropertyMapping " + getAnnotationsDescription(propertyMappings) + " cannot be used in combination with the @Component " diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java index 31f42ff2ca..87fd7a481c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,9 +62,9 @@ public class RestDocsAutoConfiguration { ObjectProvider configurationCustomizers, RestDocumentationContextProvider contextProvider) { MockMvcRestDocumentationConfigurer configurer = MockMvcRestDocumentation - .documentationConfiguration(contextProvider); + .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return configurer; } @@ -88,9 +88,9 @@ public class RestDocsAutoConfiguration { ObjectProvider configurationCustomizers, RestDocumentationContextProvider contextProvider) { RestAssuredRestDocumentationConfigurer configurer = RestAssuredRestDocumentation - .documentationConfiguration(contextProvider); + .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return new RequestSpecBuilder().addFilter(configurer).build(); } @@ -114,9 +114,9 @@ public class RestDocsAutoConfiguration { ObjectProvider configurationCustomizers, RestDocumentationContextProvider contextProvider) { WebTestClientRestDocumentationConfigurer configurer = WebTestClientRestDocumentation - .documentationConfiguration(contextProvider); + .documentationConfiguration(contextProvider); configurationCustomizers.orderedStream() - .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); + .forEach((configurationCustomizer) -> configurationCustomizer.customize(configurer)); return configurer; } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java index 493e897c62..7ef1e895ba 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocsRestAssuredBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,8 +43,8 @@ class RestDocsRestAssuredBuilderCustomizer implements InitializingBean { PropertyMapper map = PropertyMapper.get(); String host = this.properties.getUriHost(); map.from(this.properties::getUriScheme) - .when((scheme) -> StringUtils.hasText(scheme) && StringUtils.hasText(host)) - .to((scheme) -> this.delegate.baseUri(scheme + "://" + host)); + .when((scheme) -> StringUtils.hasText(scheme) && StringUtils.hasText(host)) + .to((scheme) -> this.delegate.baseUri(scheme + "://" + host)); map.from(this.properties::getUriPort).whenNonNull().to(this.delegate::port); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java index 36cb4227c1..6a56125e81 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/RestDocumentationContextProviderRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,9 +37,9 @@ class RestDocumentationContextProviderRegistrar implements ImportBeanDefinitionR @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map annotationAttributes = importingClassMetadata - .getAnnotationAttributes(AutoConfigureRestDocs.class.getName()); + .getAnnotationAttributes(AutoConfigureRestDocs.class.getName()); BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder - .genericBeanDefinition(ManualRestDocumentation.class); + .genericBeanDefinition(ManualRestDocumentation.class); String outputDir = (String) annotationAttributes.get("outputDir"); if (StringUtils.hasText(outputDir)) { definitionBuilder.addConstructorArgValue(outputDir); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java index 6e93cd07b6..aa76319d00 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/MockRestServiceServerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,7 +64,7 @@ public class MockRestServiceServerAutoConfiguration { private MockRestServiceServer createDeferredMockRestServiceServer(MockServerRestTemplateCustomizer customizer) throws Exception { Constructor constructor = MockRestServiceServer.class - .getDeclaredConstructor(RequestExpectationManager.class); + .getDeclaredConstructor(RequestExpectationManager.class); constructor.setAccessible(true); return constructor.newInstance(new DeferredRequestExpectationManager(customizer)); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java index b96c685b48..726489cae0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -30,8 +30,10 @@ class RestClientTestContextBootstrapper extends SpringBootTestContextBootstrappe @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(RestClientTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(RestClientTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java index 8f25e8c04e..da6d72dd5a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/reactive/WebFluxTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -38,8 +38,10 @@ class WebFluxTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebFluxTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebFluxTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java index 22eb70e798..6d429eb4fa 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -132,7 +132,7 @@ public class MockMvcAutoConfiguration { dispatcherServlet.setDispatchOptionsRequest(this.webMvcProperties.isDispatchOptionsRequest()); dispatcherServlet.setDispatchTraceRequest(this.webMvcProperties.isDispatchTraceRequest()); dispatcherServlet - .setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); + .setThrowExceptionIfNoHandlerFound(this.webMvcProperties.isThrowExceptionIfNoHandlerFound()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java index e19cedfec3..202cbb0ab5 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcWebDriverAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ public class MockMvcWebDriverAutoConfiguration { @ConditionalOnBean(MockMvc.class) public MockMvcHtmlUnitDriverBuilder mockMvcHtmlUnitDriverBuilder(MockMvc mockMvc, Environment environment) { return MockMvcHtmlUnitDriverBuilder.mockMvcSetup(mockMvc) - .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(environment, BrowserVersion.CHROME)); + .withDelegate(new LocalHostWebConnectionHtmlUnitDriver(environment, BrowserVersion.CHROME)); } @Bean diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java index 5cff3368f8..269d361500 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizer.java @@ -107,9 +107,10 @@ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomi private void addFilters(ConfigurableMockMvcBuilder builder) { FilterRegistrationBeans registrations = new FilterRegistrationBeans(this.context); - registrations.stream().map(AbstractFilterRegistrationBean.class::cast) - .filter(AbstractFilterRegistrationBean::isEnabled) - .forEach((registration) -> addFilter(builder, registration)); + registrations.stream() + .map(AbstractFilterRegistrationBean.class::cast) + .filter(AbstractFilterRegistrationBean::isEnabled) + .forEach((registration) -> addFilter(builder, registration)); } private void addFilter(ConfigurableMockMvcBuilder builder, AbstractFilterRegistrationBean registration) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java index c8a92f24b7..fc366bc2ca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,10 @@ class WebMvcTestContextBootstrapper extends SpringBootTestContextBootstrapper { @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebMvcTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebMvcTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java index d3d4bc0132..931e76e5ce 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -31,8 +31,10 @@ class WebServiceClientTestContextBootstrapper extends SpringBootTestContextBoots @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebServiceClientTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebServiceClientTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java index 817fbd073d..2e5cbe01f3 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -39,8 +39,10 @@ class WebServiceServerTestContextBootstrapper extends SpringBootTestContextBoots @Override protected String[] getProperties(Class testClass) { - return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).get(WebServiceServerTest.class) - .getValue("properties", String[].class).orElse(null); + return MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .get(WebServiceServerTest.class) + .getValue("properties", String[].class) + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java index d1c789359a..0cf44e791d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/AutoConfigurationImportedCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -40,7 +40,7 @@ public final class AutoConfigurationImportedCondition extends Condition { - assertThat(context).doesNotHaveBean(Tracer.class); - assertThatMetricsAreDisabled(context); - assertThatTracingIsDisabled(context); - }); + .withInitializer(applyCustomizer(customizer)) + .run((context) -> { + assertThat(context).doesNotHaveBean(Tracer.class); + assertThatMetricsAreDisabled(context); + assertThatTracingIsDisabled(context); + }); } } @@ -118,18 +119,19 @@ class ObservabilityContextCustomizerFactoryTests { void shouldBackOffOnCustomTracer() { ContextCustomizer customizer = createContextCustomizer(NoAnnotation.class); new ApplicationContextRunner().withConfiguration(UserConfigurations.of(CustomTracer.class)) - .withInitializer(applyCustomizer(customizer)).run((context) -> { - assertThat(context).hasSingleBean(Tracer.class); - assertThat(context).hasBean("customTracer"); - }); + .withInitializer(applyCustomizer(customizer)) + .run((context) -> { + assertThat(context).hasSingleBean(Tracer.class); + assertThat(context).hasBean("customTracer"); + }); } @Test void shouldNotRunIfAotIsEnabled() { ContextCustomizer customizer = createContextCustomizer(NoAnnotation.class); new ApplicationContextRunner().withSystemProperties("spring.aot.enabled:true") - .withInitializer(applyCustomizer(customizer)) - .run((context) -> assertThat(context).doesNotHaveBean(Tracer.class)); + .withInitializer(applyCustomizer(customizer)) + .run((context) -> assertThat(context).doesNotHaveBean(Tracer.class)); } @Test @@ -160,7 +162,7 @@ class ObservabilityContextCustomizerFactoryTests { private void assertThatMetricsAreDisabled(ConfigurableApplicationContext context) { assertThat(context.getEnvironment().getProperty("management.defaults.metrics.export.enabled")) - .isEqualTo("false"); + .isEqualTo("false"); assertThat(context.getEnvironment().getProperty("management.simple.metrics.export.enabled")).isEqualTo("true"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java index 7536126a75..b4987dfdad 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/cache/ImportsContextCustomizerFactoryWithAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -78,7 +78,8 @@ class ImportsContextCustomizerFactoryWithAutoConfigurationTests { private void executeTests(Class testClass) { LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectClass(testClass)).build(); + .selectors(DiscoverySelectors.selectClass(testClass)) + .build(); Launcher launcher = LauncherFactory.create(); launcher.execute(request); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java index 20c15f1e3a..6dbfc4e185 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/cassandra/DataCassandraTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,7 @@ class DataCassandraTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java index 1441227200..60619c0790 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,8 +48,9 @@ class DataCouchbaseTestIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME)); @DynamicPropertySource static void couchbaseProperties(DynamicPropertyRegistry registry) { @@ -71,7 +72,7 @@ class DataCouchbaseTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java index 8ce3bc0e9b..27be882a85 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,8 +46,9 @@ class DataCouchbaseTestReactiveIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME)); @DynamicPropertySource static void couchbaseProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java index ba8d393805..1e779b709b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/couchbase/DataCouchbaseTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,8 +47,9 @@ class DataCouchbaseTestWithIncludeFilterIntegrationTests { @Container static final CouchbaseContainer couchbase = new CouchbaseContainer(DockerImageNames.couchbase()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)) - .withBucket(new BucketDefinition(BUCKET_NAME)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)) + .withBucket(new BucketDefinition(BUCKET_NAME)); @DynamicPropertySource static void couchbaseProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java index 059b7061b3..6249aa0116 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,8 @@ class DataElasticsearchTestIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { @@ -65,7 +66,7 @@ class DataElasticsearchTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java index b0f2f6941a..9a15e17e98 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,8 @@ class DataElasticsearchTestPropertiesIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java index 794b42a2ce..19d28223bb 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,8 @@ class DataElasticsearchTestReactiveIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { @@ -63,7 +64,7 @@ class DataElasticsearchTestReactiveIntegrationTests { exampleDocument = this.exampleReactiveRepository.save(exampleDocument).block(Duration.ofSeconds(30)); assertThat(exampleDocument.getId()).isNotNull(); assertThat(this.elasticsearchTemplate.exists(exampleDocument.getId(), ExampleDocument.class) - .block(Duration.ofSeconds(30))).isTrue(); + .block(Duration.ofSeconds(30))).isTrue(); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java index 2c0112494a..18ebfef088 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/elasticsearch/DataElasticsearchTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,8 @@ class DataElasticsearchTestWithIncludeFilterIntegrationTests { @Container static final ElasticsearchContainer elasticsearch = new ElasticsearchContainer(DockerImageNames.elasticsearch()) - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void elasticsearchProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java index 81b8f7d030..5d4eb2d60c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,7 @@ class DataJdbcTestIntegrationTests { @Test void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java index 7528a5913c..b9ee34512c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java @@ -57,15 +57,15 @@ class DataLdapTestIntegrationTests { Optional entry = this.exampleRepository.findOne(ldapQuery); assertThat(entry).isPresent(); assertThat(entry.get().getDn()) - .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); + .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); assertThat(this.ldapTemplate.findOne(ldapQuery, ExampleEntry.class).getDn()) - .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); + .isEqualTo(LdapUtils.newLdapName("cn=Bob Smith,ou=company1,c=Sweden,dc=spring,dc=org")); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java index 3a3e5cdd6a..132eb9aa33 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class DataMongoTestIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private MongoTemplate mongoTemplate; @@ -68,7 +68,7 @@ class DataMongoTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @DynamicPropertySource diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java index 65003b8470..4259b537f7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class DataMongoTestReactiveIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private ReactiveMongoTemplate mongoTemplate; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java index 21e28dc89d..d2b99dfaf9 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class DataMongoTestWithIncludeFilterIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private ExampleService service; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java index a882d12fbf..d2ede5f559 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/TransactionalDataMongoTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class TransactionalDataMongoTestIntegrationTests { @Container static final MongoDBContainer mongoDB = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(5)); + .withStartupTimeout(Duration.ofMinutes(5)); @Autowired private ExampleRepository exampleRepository; diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java index fff1e253d5..72b13abbfd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java @@ -47,7 +47,8 @@ class DataNeo4jTestIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { @@ -75,7 +76,7 @@ class DataNeo4jTestIntegrationTests { @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java index e334c40563..37413c4434 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,8 @@ class DataNeo4jTestPropertiesIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java index 2cc6479e93..64ba554c95 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,8 @@ class DataNeo4jTestReactiveIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { @@ -74,15 +75,18 @@ class DataNeo4jTestReactiveIntegrationTests { @Test void testRepository() { - Mono.just(new ExampleGraph("Look, new @DataNeo4jTest with reactive!")).flatMap(this.exampleRepository::save) - .as(StepVerifier::create).expectNextCount(1).verifyComplete(); + Mono.just(new ExampleGraph("Look, new @DataNeo4jTest with reactive!")) + .flatMap(this.exampleRepository::save) + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); StepVerifier.create(this.neo4jTemplate.count(ExampleGraph.class)).expectNext(1L).verifyComplete(); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } @TestConfiguration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java index 69be31fe2f..85b46d43ae 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestWithIncludeFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,8 @@ class DataNeo4jTestWithIncludeFilterIntegrationTests { @Container static final Neo4jContainer neo4j = new Neo4jContainer<>(DockerImageNames.neo4j()).withoutAuthentication() - .withStartupAttempts(5).withStartupTimeout(Duration.ofMinutes(10)); + .withStartupAttempts(5) + .withStartupTimeout(Duration.ofMinutes(10)); @DynamicPropertySource static void neo4jProperties(DynamicPropertyRegistry registry) { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java index a3b6f98427..23debe499b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -72,14 +72,14 @@ class DataRedisTestIntegrationTests { PersonHash savedEntity = this.exampleRepository.save(personHash); assertThat(savedEntity.getId()).isNotNull(); assertThat(this.operations.execute((RedisConnection connection) -> connection.keyCommands() - .exists(("persons:" + savedEntity.getId()).getBytes(CHARSET)))).isTrue(); + .exists(("persons:" + savedEntity.getId()).getBytes(CHARSET)))).isTrue(); this.exampleRepository.deleteAll(); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java index db2d5e4732..9b80ed135d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestReactiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,17 +60,19 @@ class DataRedisTestReactiveIntegrationTests { @Test void testRepository() { String id = UUID.randomUUID().toString(); - StepVerifier.create(this.operations.opsForValue().set(id, "Hello World")).expectNext(Boolean.TRUE) - .verifyComplete(); + StepVerifier.create(this.operations.opsForValue().set(id, "Hello World")) + .expectNext(Boolean.TRUE) + .verifyComplete(); StepVerifier.create(this.operations.opsForValue().get(id)).expectNext("Hello World").verifyComplete(); - StepVerifier.create(this.operations.execute((action) -> action.serverCommands().flushDb())).expectNext("OK") - .verifyComplete(); + StepVerifier.create(this.operations.execute((action) -> action.serverCommands().flushDb())) + .expectNext("OK") + .verifyComplete(); } @Test void didNotInjectExampleService() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java index 3b05e4720d..c6d0c1c809 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/ExampleService.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ public class ExampleService { public boolean hasRecord(PersonHash personHash) { return this.operations.execute((RedisConnection connection) -> connection.keyCommands() - .exists(("persons:" + personHash.getId()).getBytes(CHARSET))); + .exists(("persons:" + personHash.getId()).getBytes(CHARSET))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java index 9708539009..693621b7a7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/graphql/tester/GraphQlTesterAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,8 +36,8 @@ import static org.mockito.Mockito.mock; */ class GraphQlTesterAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(JacksonAutoConfiguration.class, GraphQlTesterAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class, GraphQlTesterAutoConfiguration.class)); @Test void shouldNotContributeTesterIfGraphQlServiceNotPresent() { @@ -47,7 +47,7 @@ class GraphQlTesterAutoConfigurationTests { @Test void shouldContributeTester() { this.contextRunner.withUserConfiguration(CustomGraphQlServiceConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed().hasSingleBean(GraphQlTester.class)); + .run((context) -> assertThat(context).hasNotFailed().hasSingleBean(GraphQlTester.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java index 693db8f9dc..15c1ca839e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java @@ -73,7 +73,7 @@ class JdbcTestIntegrationTests { @Test void didNotInjectExampleRepository() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleRepository.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleRepository.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java index 202d356785..ee6297f510 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/TestDatabaseAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; class TestDatabaseAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test void replaceWithNoDataSourceAvailable() { @@ -65,8 +65,8 @@ class TestDatabaseAutoConfigurationTests { @Test void whenUsingAotGeneratedArtifactsEmbeddedDataSourceFactoryBeanIsNotDefined() { this.contextRunner.withUserConfiguration(ExistingDataSourceConfiguration.class) - .withSystemProperties("spring.aot.enabled=true") - .run((context) -> assertThat(context).doesNotHaveBean(EmbeddedDataSourceFactoryBean.class)); + .withSystemProperties("spring.aot.enabled=true") + .run((context) -> assertThat(context).doesNotHaveBean(EmbeddedDataSourceFactoryBean.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java index 8a34d70c07..da8bda872f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class JooqTestIntegrationTests { @Test void testDSLContext() { assertThat(this.dsl.selectCount().from("INFORMATION_SCHEMA.TABLES").fetchOne(0, Integer.class)) - .isGreaterThan(0); + .isGreaterThan(0); } @Test @@ -67,7 +67,7 @@ class JooqTestIntegrationTests { @Test void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java index b6214d651c..205ef537c0 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/json/JsonTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -98,7 +98,8 @@ class JsonTestIntegrationTests { ExampleJsonObjectWithView object = new ExampleJsonObjectWithView(); object.setValue("spring"); JsonContent content = this.jacksonWithViewJson - .forView(ExampleJsonObjectWithView.TestView.class).write(object); + .forView(ExampleJsonObjectWithView.TestView.class) + .write(object); assertThat(content).doesNotHaveJsonPathValue("id"); assertThat(content).isEqualToJson("example.json"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java index 92ccce3c95..baa1fc5cca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestAttributesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class DataJpaTestAttributesIntegrationTests { @Test void bootstrapModeIsSet() { assertThat(this.environment.getProperty("spring.data.jpa.repositories.bootstrap-mode")) - .isEqualTo(BootstrapMode.DEFERRED.name()); + .isEqualTo(BootstrapMode.DEFERRED.name()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java index 3f1d9e2631..e3e54de73f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -94,7 +94,7 @@ class DataJpaTestIntegrationTests { @Test void didNotInjectExampleComponent() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class)); } @Test @@ -110,7 +110,7 @@ class DataJpaTestIntegrationTests { @Test void bootstrapModeIsDefaultByDefault() { assertThat(this.applicationContext.getEnvironment().getProperty("spring.data.jpa.repositories.bootstrap-mode")) - .isEqualTo(BootstrapMode.DEFAULT.name()); + .isEqualTo(BootstrapMode.DEFAULT.name()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java index acef5aefb1..2bb4899c10 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestSchemaCredentialsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,8 @@ class DataJpaTestSchemaCredentialsIntegrationTests { String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName(); assertThat(product).isEqualTo("H2"); assertThat(new JdbcTemplate(this.dataSource).queryForList("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES", - String.class)).contains("EXAMPLE"); + String.class)) + .contains("EXAMPLE"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java index 5fda3b046f..9a0282b5e7 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestDatabaseAutoConfigurationNoEmbeddedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,15 +42,16 @@ import static org.mockito.Mockito.mock; class TestDatabaseAutoConfigurationNoEmbeddedTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(ExistingDataSourceConfiguration.class) - .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); + .withUserConfiguration(ExistingDataSourceConfiguration.class) + .withConfiguration(AutoConfigurations.of(TestDatabaseAutoConfiguration.class)); @Test void applyAnyReplace() { - this.contextRunner.run((context) -> assertThat(context).getFailure().isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Failed to replace DataSource with an embedded database for tests.") - .hasMessageContaining("If you want an embedded database please put a supported one on the classpath") - .hasMessageContaining("or tune the replace attribute of @AutoConfigureTestDatabase.")); + this.contextRunner.run((context) -> assertThat(context).getFailure() + .isInstanceOf(BeanCreationException.class) + .hasMessageContaining("Failed to replace DataSource with an embedded database for tests.") + .hasMessageContaining("If you want an embedded database please put a supported one on the classpath") + .hasMessageContaining("or tune the replace attribute of @AutoConfigureTestDatabase.")); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java index 37570b6306..8ec9c28b7d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -61,7 +61,7 @@ class TestEntityManagerTests { @Test void createWhenEntityManagerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestEntityManager(null)) - .withMessageContaining("EntityManagerFactory must not be null"); + .withMessageContaining("EntityManagerFactory must not be null"); } @Test @@ -191,8 +191,8 @@ class TestEntityManagerTests { given(this.entityManagerFactory.getPersistenceUnitUtil()).willReturn(this.persistenceUnitUtil); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); assertThatIllegalArgumentException().isThrownBy(() -> this.testEntityManager.getId(entity, Long.class)) - .withMessageContaining("ID mismatch: Object of class [java.lang.Integer] " - + "must be an instance of class java.lang.Long"); + .withMessageContaining("ID mismatch: Object of class [java.lang.Integer] " + + "must be an instance of class java.lang.Long"); } @Test @@ -213,7 +213,7 @@ class TestEntityManagerTests { @Test void getEntityManagerWhenNotSetShouldThrowException() { assertThatIllegalStateException().isThrownBy(this.testEntityManager::getEntityManager) - .withMessageContaining("No transactional EntityManager found"); + .withMessageContaining("No transactional EntityManager found"); } private void bindEntityManager() { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java index e71ceebf9d..32132a1b17 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class OverrideAutoConfigurationEnabledFalseIntegrationTests { ApplicationContext context = this.context; assertThat(context.getBean(ExampleTestConfig.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> context.getBean(ConfigurationPropertiesBindingPostProcessor.class)); + .isThrownBy(() -> context.getBean(ConfigurationPropertiesBindingPostProcessor.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java index d52d5730f1..01928c817f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class AnnotationsPropertySourceTests { @Test void createWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new AnnotationsPropertySource(null)) - .withMessageContaining("Property source must not be null"); + .withMessageContaining("Property source must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java index 6eb0280f5e..2eb02fbe1b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java @@ -92,9 +92,9 @@ class PropertyMappingContextCustomizerFactoryTests { context.register(ConfigMapping.class); customizer.customizeContext(context, null); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(context::refresh) - .withMessageContaining("The @PropertyMapping annotation " - + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " - + "cannot be used in combination with the @Component annotation @Configuration"); + .withMessageContaining("The @PropertyMapping annotation " + + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " + + "cannot be used in combination with the @Component annotation @Configuration"); } @NoMappingAnnotation diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 40d41b3c61..c543a3e2ec 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,8 @@ class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @Test void snippetGeneration() throws Exception { - this.mvc.perform(get("/")).andDo(this.documentationHandler + this.mvc.perform(get("/")) + .andDo(this.documentationHandler .document(links(linkWithRel("self").description("Canonical location of this resource")))); File defaultSnippetsDir = new File(this.generatedSnippets, "snippet-generation"); assertThat(defaultSnippetsDir).exists(); @@ -94,7 +95,7 @@ class MockMvcRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests { @Bean RestDocsMockMvcConfigurationCustomizer defaultSnippetsCustomizer() { return (configurer) -> configurer.snippets() - .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 4a83fc38b6..6089a8f773 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,9 +71,14 @@ class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests @Test void snippetGeneration() { given(this.documentationSpec) - .filter(document("default-snippets", - preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) - .when().port(this.port).get("/").then().assertThat().statusCode(is(200)); + .filter(document("default-snippets", + preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) + .when() + .port(this.port) + .get("/") + .then() + .assertThat() + .statusCode(is(200)); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))).contains("'https://api.example.com/'"); @@ -98,7 +103,7 @@ class RestAssuredRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests @Bean RestDocsRestAssuredConfigurationCustomizer defaultSnippetsCustomizer() { return (configurer) -> configurer.snippets() - .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java index 5d763f790b..3609318c99 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/RestAssuredRestDocsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,9 +63,14 @@ class RestAssuredRestDocsAutoConfigurationIntegrationTests { @Test void defaultSnippetsAreWritten() { given(this.documentationSpec) - .filter(document("default-snippets", - preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) - .when().port(this.port).get("/").then().assertThat().statusCode(is(200)); + .filter(document("default-snippets", + preprocessRequest(modifyUris().scheme("https").host("api.example.com").removePort()))) + .when() + .port(this.port) + .get("/") + .then() + .assertThat() + .statusCode(is(200)); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))).contains("'https://api.example.com/'"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java index 0eb8748481..b4f661c52f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -62,8 +62,13 @@ class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTest @Test void defaultSnippetsAreWritten() { - this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() - .consumeWith(document("default-snippets")); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.md"))).contains("'https://api.example.com/'"); @@ -88,7 +93,7 @@ class WebTestClientRestDocsAutoConfigurationAdvancedConfigurationIntegrationTest @Bean RestDocsWebTestClientConfigurationCustomizer defaultSnippetsCustomizer() { return (configurer) -> configurer.snippets() - .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); + .withAdditionalDefaults(responseFields(fieldWithPath("_links.self").description("Main URL"))); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java index c02e04d8e3..efe9f41a25 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/restdocs/WebTestClientRestDocsAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -55,8 +55,13 @@ class WebTestClientRestDocsAutoConfigurationIntegrationTests { @Test void defaultSnippetsAreWritten() { - this.webTestClient.get().uri("/").exchange().expectStatus().is2xxSuccessful().expectBody() - .consumeWith(document("default-snippets")); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody() + .consumeWith(document("default-snippets")); File defaultSnippetsDir = new File(this.generatedSnippets, "default-snippets"); assertThat(defaultSnippetsDir).exists(); assertThat(contentOf(new File(defaultSnippetsDir, "curl-request.adoc"))).contains("'https://api.example.com/'"); diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java index d76fe97b42..cc93138f82 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/security/MockMvcSecurityIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -57,9 +57,9 @@ class MockMvcSecurityIntegrationTests { @Test void okResponseWithBasicAuthCredentialsForKnownUser() throws Exception { this.mockMvc - .perform(get("/").header(HttpHeaders.AUTHORIZATION, - "Basic " + Base64.getEncoder().encodeToString("user:secret".getBytes()))) - .andExpect(status().isOk()); + .perform(get("/").header(HttpHeaders.AUTHORIZATION, + "Basic " + Base64.getEncoder().encodeToString("user:secret".getBytes()))) + .andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java index 52fcbdfdb7..68c31ee5bd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class AutoConfigureMockRestServiceServerEnabledFalseIntegrationTests { @Test void mockServerRestTemplateCustomizerShouldNotBeRegistered() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(MockServerRestTemplateCustomizer.class)); + .isThrownBy(() -> this.applicationContext.getBean(MockServerRestTemplateCustomizer.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java index b2df64ab71..3966b197e2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientRestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -55,8 +55,9 @@ class RestClientRestIntegrationTests { @Test void mockServerCallWithContent() { - this.server.expect(requestTo("/test")).andExpect(content().string("test")) - .andRespond(withSuccess("1", MediaType.TEXT_HTML)); + this.server.expect(requestTo("/test")) + .andExpect(content().string("test")) + .andRespond(withSuccess("1", MediaType.TEXT_HTML)); this.client.testPostWithBody("test"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java index c44fbbee7e..6ed3e63e46 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestNoComponentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -50,13 +50,13 @@ class RestClientTestNoComponentIntegrationTests { @Test void exampleRestClientIsNotInjected() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleRestClient.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleRestClient.class)); } @Test void examplePropertiesIsNotInjected() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleProperties.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleProperties.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java index 9645c05324..08e00159c6 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -50,22 +50,25 @@ class RestClientTestTwoComponentsIntegrationTests { @Test void serverShouldNotWork() { - assertThatIllegalStateException().isThrownBy( - () -> this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML))) - .withMessageContaining("Unable to use auto-configured"); + assertThatIllegalStateException() + .isThrownBy( + () -> this.server.expect(requestTo("/test")).andRespond(withSuccess("hello", MediaType.TEXT_HTML))) + .withMessageContaining("Unable to use auto-configured"); } @Test void client1RestCallViaCustomizer() { - this.customizer.getServer(this.client1.getRestTemplate()).expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + this.customizer.getServer(this.client1.getRestTemplate()) + .expect(requestTo("/test")) + .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); assertThat(this.client1.test()).isEqualTo("hello"); } @Test void client2RestCallViaCustomizer() { - this.customizer.getServer(this.client2.getRestTemplate()).expect(requestTo("/test")) - .andRespond(withSuccess("there", MediaType.TEXT_HTML)); + this.customizer.getServer(this.client2.getRestTemplate()) + .expect(requestTo("/test")) + .andRespond(withSuccess("there", MediaType.TEXT_HTML)); assertThat(this.client2.test()).isEqualTo("there"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java index d94e53df5d..0a8a708a2b 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestWithConfigurationPropertiesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class RestClientTestWithConfigurationPropertiesIntegrationTests { @Test void configurationPropertiesCanBeAddedAsComponent() { assertThat(this.applicationContext.getBeansOfType(ExampleProperties.class).keySet()) - .containsOnly("example-org.springframework.boot.test.autoconfigure.web.client.ExampleProperties"); + .containsOnly("example-org.springframework.boot.test.autoconfigure.web.client.ExampleProperties"); assertThat(this.applicationContext.getBean(ExampleProperties.class).getName()).isEqualTo("Hello"); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java index df78ddd033..5e79def6ca 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/WebTestClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ import static org.mockito.Mockito.mock; class WebTestClientAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebTestClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(WebTestClientAutoConfiguration.class)); @Test void shouldNotBeConfiguredWithoutWebHandler() { @@ -72,10 +72,11 @@ class WebTestClientAutoConfigurationTests { @Test void shouldCustomizeTimeout() { this.contextRunner.withUserConfiguration(BaseConfiguration.class) - .withPropertyValues("spring.test.webtestclient.timeout=15m").run((context) -> { - WebTestClient webTestClient = context.getBean(WebTestClient.class); - assertThat(webTestClient).hasFieldOrPropertyWithValue("responseTimeout", Duration.ofMinutes(15)); - }); + .withPropertyValues("spring.test.webtestclient.timeout=15m") + .run((context) -> { + WebTestClient webTestClient = context.getBean(WebTestClient.class); + assertThat(webTestClient).hasFieldOrPropertyWithValue("responseTimeout", Duration.ofMinutes(15)); + }); } @Test @@ -97,17 +98,17 @@ class WebTestClientAutoConfigurationTests { @SuppressWarnings("unchecked") void shouldNotApplySpringSecurityConfigurerWhenSpringSecurityNotOnClassPath() { FilteredClassLoader classLoader = new FilteredClassLoader(SecurityMockServerConfigurers.class); - this.contextRunner.withUserConfiguration(BaseConfiguration.class).withClassLoader(classLoader) - .run((context) -> { - WebTestClient webTestClient = context.getBean(WebTestClient.class); - WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils.getField(webTestClient, - "builder"); - WebHttpHandlerBuilder httpHandlerBuilder = (WebHttpHandlerBuilder) ReflectionTestUtils - .getField(builder, "httpHandlerBuilder"); - List filters = (List) ReflectionTestUtils.getField(httpHandlerBuilder, - "filters"); - assertThat(filters).isEmpty(); - }); + this.contextRunner.withUserConfiguration(BaseConfiguration.class) + .withClassLoader(classLoader) + .run((context) -> { + WebTestClient webTestClient = context.getBean(WebTestClient.class); + WebTestClient.Builder builder = (WebTestClient.Builder) ReflectionTestUtils.getField(webTestClient, + "builder"); + WebHttpHandlerBuilder httpHandlerBuilder = (WebHttpHandlerBuilder) ReflectionTestUtils.getField(builder, + "httpHandlerBuilder"); + List filters = (List) ReflectionTestUtils.getField(httpHandlerBuilder, "filters"); + assertThat(filters).isEmpty(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java index 4b5b33adab..97a54cbe09 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -85,7 +85,7 @@ class WebFluxTestAutoConfigurationIntegrationTests { @Test void oAuth2ResourceServerAutoConfigurationWasImported() { assertThat(this.applicationContext) - .has(importedAutoConfiguration(ReactiveOAuth2ResourceServerAutoConfiguration.class)); + .has(importedAutoConfiguration(ReactiveOAuth2ResourceServerAutoConfiguration.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java index 41b2184319..df5d8e54b2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/reactive/webclient/WebFluxTestConverterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,13 @@ class WebFluxTestConverterIntegrationTests { @Test void shouldFindConverter() { UUID id = UUID.randomUUID(); - this.webClient.get().uri("/two/" + id).exchange().expectStatus().isOk().expectBody(String.class) - .isEqualTo(id + "two"); + this.webClient.get() + .uri("/two/" + id) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(id + "two"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java index 73feb850ca..4c88271d30 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/MockMvcAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; class MockMvcAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MockMvcAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MockMvcAutoConfiguration.class)); @Test void registersDispatcherServletFromMockMvc() { @@ -62,7 +62,7 @@ class MockMvcAutoConfigurationTests { @Test void shouldNotRegisterWebTestClientIfWebFluxMissing() { this.contextRunner.withClassLoader(new FilteredClassLoader(WebClient.class)) - .run((context) -> assertThat(context).doesNotHaveBean(WebTestClient.class)); + .run((context) -> assertThat(context).doesNotHaveBean(WebTestClient.class)); } @Test @@ -71,7 +71,7 @@ class MockMvcAutoConfigurationTests { assertThat(context).hasSingleBean(WebTestClient.class); assertThat(context).hasBean("myWebTestClientCustomizer"); then(context.getBean("myWebTestClientCustomizer", WebTestClientBuilderCustomizer.class)).should() - .customize(any(WebTestClient.Builder.class)); + .customize(any(WebTestClient.Builder.class)); }); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java index 31b94d56ec..16c8126396 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/SpringBootMockMvcBuilderCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,7 +64,7 @@ class SpringBootMockMvcBuilderCustomizerTests { this.customizer = new SpringBootMockMvcBuilderCustomizer(context); this.customizer.customize(builder); FilterRegistrationBean registrationBean = (FilterRegistrationBean) context - .getBean("filterRegistrationBean"); + .getBean("filterRegistrationBean"); Filter testFilter = (Filter) context.getBean("testFilter"); Filter otherTestFilter = registrationBean.getFilter(); List filters = (List) ReflectionTestUtils.getField(builder, "filters"); @@ -98,7 +98,7 @@ class SpringBootMockMvcBuilderCustomizerTests { assertThat(delegate.allWritten).hasSize(10000); assertThat(delegate.allWritten) - .allSatisfy((written) -> assertThat(written).containsExactly("1", "2", "3", "4", "5")); + .allSatisfy((written) -> assertThat(written).containsExactly("1", "2", "3", "4", "5")); } private static final class CapturingLinesWriter implements LinesWriter { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java index 1dbd64074d..c6d3352278 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTestAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -76,7 +76,7 @@ class WebMvcTestAutoConfigurationIntegrationTests { void asyncTaskExecutorWithApplicationTaskExecutor() { assertThat(this.applicationContext.getBeansOfType(AsyncTaskExecutor.class)).hasSize(1); assertThat(this.applicationContext.getBean(RequestMappingHandlerAdapter.class)).extracting("taskExecutor") - .isSameAs(this.applicationContext.getBean("applicationTaskExecutor")); + .isSameAs(this.applicationContext.getBean("applicationTaskExecutor")); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java index 93ea749a7c..3dc1bd719a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ class WebMvcTestAllControllersIntegrationTests { @Test void shouldRunValidationFailure() { assertThatExceptionOfType(ServletException.class).isThrownBy(() -> this.mvc.perform(get("/three/invalid"))) - .withCauseInstanceOf(ConstraintViolationException.class); + .withCauseInstanceOf(ConstraintViolationException.class); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java index fe1e30cc56..f7f5c8e5fc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestCustomDispatcherServletIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,9 @@ class WebMvcTestCustomDispatcherServletIntegrationTests { @Test void dispatcherServletIsCustomized() throws Exception { - this.mvc.perform(get("/does-not-exist")).andExpect(status().isBadRequest()) - .andExpect(content().string("Invalid request: /does-not-exist")); + this.mvc.perform(get("/does-not-exist")) + .andExpect(status().isBadRequest()) + .andExpect(content().string("Invalid request: /does-not-exist")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java index f22ef521d9..735ebb950f 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestHateoasIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,13 +42,13 @@ class WebMvcTestHateoasIntegrationTests { @Test void plainResponse() throws Exception { this.mockMvc.perform(get("/hateoas/plain")) - .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json")); + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/json")); } @Test void hateoasResponse() throws Exception { this.mockMvc.perform(get("/hateoas/resource")) - .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json")); + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, "application/hal+json")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java index da07a8b300..7dcdb8ee99 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestNestedIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -61,8 +61,9 @@ class WebMvcTestNestedIntegrationTests { @Test void shouldFindController2() throws Exception { - WebMvcTestNestedIntegrationTests.this.mvc.perform(get("/two")).andExpect(content().string("hellotwo")) - .andExpect(status().isOk()); + WebMvcTestNestedIntegrationTests.this.mvc.perform(get("/two")) + .andExpect(content().string("hellotwo")) + .andExpect(status().isOk()); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java index 07754328ed..7482bb090c 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPageableIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -41,8 +41,9 @@ class WebMvcTestPageableIntegrationTests { @Test void shouldSupportPageable() throws Exception { - this.mvc.perform(get("/paged").param("page", "2").param("size", "42")).andExpect(status().isOk()) - .andExpect(content().string("2:42")); + this.mvc.perform(get("/paged").param("page", "2").param("size", "42")) + .andExpect(status().isOk()) + .andExpect(content().string("2:42")); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java index 539cfda167..ca3cb41e18 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestPrintDefaultIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,8 @@ class WebMvcTestPrintDefaultIntegrationTests { private void executeTests(Class testClass) { LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectClass(testClass)).build(); + .selectors(DiscoverySelectors.selectClass(testClass)) + .build(); Launcher launcher = LauncherFactory.create(); launcher.execute(request); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java index fb9851f392..e2ce3c0632 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -56,13 +56,13 @@ class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { @Test void shouldNotHaveWebDriver() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(WebDriver.class)); + .isThrownBy(() -> this.context.getBean(WebDriver.class)); } @Test void shouldNotHaveWebClient() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(WebClient.class)); + .isThrownBy(() -> this.context.getBean(WebClient.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java index 3c5b35930b..2aedc9496a 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureMockWebServiceServerEnabledIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ class AutoConfigureMockWebServiceServerEnabledIntegrationTests { @Test void mockWebServiceServerShouldNotBeRegistered() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(MockWebServiceServer.class)); + .isThrownBy(() -> this.applicationContext.getBean(MockWebServiceServer.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java index bd7f5c2355..2822c77621 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class AutoConfigureWebServiceClientWebServiceTemplateIntegrationTests { @Test void webServiceTemplateTest() { this.server.expect(payload(new StringSource(""))) - .andRespond(withPayload(new StringSource(""))); + .andRespond(withPayload(new StringSource(""))); this.webServiceTemplate.marshalSendAndReceive("https://example.com", new Request()); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java index 2cb674e1cd..c3bc31d3bd 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class WebServiceClientIntegrationTests { @Test void mockServerCall() { this.server.expect(payload(new StringSource(""))) - .andRespond(withPayload(new StringSource("200"))); + .andRespond(withPayload(new StringSource("200"))); assertThat(this.client.test()).extracting(Response::getStatus).isEqualTo(200); } @@ -56,14 +56,14 @@ class WebServiceClientIntegrationTests { void mockServerCall1() { this.server.expect(connectionTo("https://example1")).andRespond(withPayload(new StringSource(""))); assertThatExceptionOfType(SourceAssertionError.class).isThrownBy(this.client::test) - .withMessageContaining("Unexpected connection expected"); + .withMessageContaining("Unexpected connection expected"); } @Test void mockServerCall2() { this.server.expect(payload(new StringSource(""))).andRespond(withError("Invalid Request")); assertThatExceptionOfType(WebServiceTransportException.class).isThrownBy(this.client::test) - .withMessageContaining("Invalid Request"); + .withMessageContaining("Invalid Request"); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java index fdf01f2a13..9fd5372578 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/client/WebServiceClientNoComponentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -50,14 +50,14 @@ class WebServiceClientNoComponentIntegrationTests { @Test void exampleClientIsNotInjected() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.applicationContext.getBean(ExampleWebServiceClient.class)); + .isThrownBy(() -> this.applicationContext.getBean(ExampleWebServiceClient.class)); } @Test void manuallyCreateBean() { ExampleWebServiceClient client = new ExampleWebServiceClient(this.webServiceTemplateBuilder); this.server.expect(payload(new StringSource(""))) - .andRespond(withPayload(new StringSource("200"))); + .andRespond(withPayload(new StringSource("200"))); assertThat(client.test()).extracting(Response::getStatus).isEqualTo(200); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java index ac279e87a0..5cd68084a2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/MockWebServiceClientAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class MockWebServiceClientAutoConfigurationTests { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(MockWebServiceClientAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(MockWebServiceClientAutoConfiguration.class)); @Test void shouldRegisterMockWebServiceClient() { @@ -45,7 +45,7 @@ class MockWebServiceClientAutoConfigurationTests { FilteredClassLoader classLoader = new FilteredClassLoader(MockWebServiceClient.class); this.contextRunner.withClassLoader(classLoader) - .run((context) -> assertThat(context).doesNotHaveBean(MockWebServiceClient.class)); + .run((context) -> assertThat(context).doesNotHaveBean(MockWebServiceClient.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java index 6261d8e099..7bafe07819 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/webservices/server/WebServiceServerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -38,9 +38,8 @@ class WebServiceServerIntegrationTests { @Test void payloadRootMethod() { this.mock - .sendRequest( - RequestCreators.withPayload(new StringSource("Hello"))) - .andExpect(ResponseMatchers.payload(new StringSource("42"))); + .sendRequest(RequestCreators.withPayload(new StringSource("Hello"))) + .andExpect(ResponseMatchers.payload(new StringSource("42"))); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java index b11c7b9e46..1e673f8f2b 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java @@ -153,7 +153,9 @@ public class SpringBootContextLoader extends AbstractContextLoader implements Ao Assert.state(mergedConfig.getParent() == null, () -> "UseMainMethod.%s cannot be used with @ContextHierarchy tests".formatted(useMainMethod)); Class springBootConfiguration = Arrays.stream(mergedConfig.getClasses()) - .filter(this::isSpringBootConfiguration).findFirst().orElse(null); + .filter(this::isSpringBootConfiguration) + .findFirst() + .orElse(null); Assert.state(springBootConfiguration != null || useMainMethod == UseMainMethod.WHEN_AVAILABLE, "Cannot use main method as no @SpringBootConfiguration-annotated class is available"); Method mainMethod = (springBootConfiguration != null) @@ -174,7 +176,7 @@ public class SpringBootContextLoader extends AbstractContextLoader implements Ao private boolean isSpringBootConfiguration(Class candidate) { return MergedAnnotations.from(candidate, SearchStrategy.TYPE_HIERARCHY) - .isPresent(SpringBootConfiguration.class); + .isPresent(SpringBootConfiguration.class); } private void configure(MergedContextConfiguration mergedConfig, SpringApplication application) { @@ -296,7 +298,7 @@ public class SpringBootContextLoader extends AbstractContextLoader implements Ao } initializers.addAll(application.getInitializers()); for (Class> initializerClass : mergedConfig - .getContextInitializerClasses()) { + .getContextInitializerClasses()) { initializers.add(BeanUtils.instantiateClass(initializerClass)); } if (mergedConfig.getParent() != null) { @@ -554,7 +556,8 @@ public class SpringBootContextLoader extends AbstractContextLoader implements Ao throw ex; } List rootContexts = this.contexts.stream() - .filter((context) -> context.getParent() == null).toList(); + .filter((context) -> context.getParent() == null) + .toList(); Assert.state(!rootContexts.isEmpty(), "No root application context located"); Assert.state(rootContexts.size() == 1, "No unique root application context located"); return rootContexts.get(0); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTest.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTest.java index 9dd0551b95..95a053363f 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTest.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -187,6 +187,7 @@ public @interface SpringBootTest { * Enumeration of how the main method of the * {@link SpringBootConfiguration @SpringBootConfiguration}-annotated class is used * when creating and running the {@link SpringApplication} under test. + * * @since 3.0.0 */ enum UseMainMethod { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestAotProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestAotProcessor.java index b7815cf680..f8d00feeb3 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestAotProcessor.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestAotProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,11 +49,17 @@ public class SpringBootTestAotProcessor extends TestAotProcessor { int requiredArgs = 6; Assert.isTrue(args.length >= requiredArgs, () -> "Usage: %s " - .formatted(TestAotProcessor.class.getName())); - Set classpathRoots = Arrays.stream(args[0].split(File.pathSeparator)).map(Paths::get) - .collect(Collectors.toSet()); - Settings settings = Settings.builder().sourceOutput(Paths.get(args[1])).resourceOutput(Paths.get(args[2])) - .classOutput(Paths.get(args[3])).groupId(args[4]).artifactId(args[5]).build(); + .formatted(TestAotProcessor.class.getName())); + Set classpathRoots = Arrays.stream(args[0].split(File.pathSeparator)) + .map(Paths::get) + .collect(Collectors.toSet()); + Settings settings = Settings.builder() + .sourceOutput(Paths.get(args[1])) + .resourceOutput(Paths.get(args[2])) + .classOutput(Paths.get(args[3])) + .groupId(args[4]) + .artifactId(args[5]) + .build(); new SpringBootTestAotProcessor(classpathRoots, settings).process(); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java index dda859f0eb..0f812a30eb 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -127,7 +127,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr protected List getDefaultTestExecutionListeners() { List listeners = new ArrayList<>(super.getDefaultTestExecutionListeners()); List postProcessors = SpringFactoriesLoader - .loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader()); + .loadFactories(DefaultTestExecutionListenersPostProcessor.class, getClass().getClassLoader()); for (DefaultTestExecutionListenersPostProcessor postProcessor : postProcessors) { listeners = postProcessor.postProcessDefaultTestExecutionListeners(listeners); } @@ -184,7 +184,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr TestPropertySourceUtils.convertInlinedPropertiesToMap(configuration.getPropertySourceProperties())); Binder binder = new Binder(source); return binder.bind("spring.main.web-application-type", Bindable.of(WebApplicationType.class)) - .orElseGet(this::deduceWebApplicationType); + .orElseGet(this::deduceWebApplicationType); } private WebApplicationType deduceWebApplicationType() { @@ -211,8 +211,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr */ protected String determineResourceBasePath(MergedContextConfiguration configuration) { return MergedAnnotations.from(configuration.getTestClass(), SearchStrategy.TYPE_HIERARCHY) - .get(WebAppConfiguration.class).getValue(MergedAnnotation.VALUE, String.class) - .orElse("src/main/webapp"); + .get(WebAppConfiguration.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse("src/main/webapp"); } private boolean isWebEnvironmentSupported(MergedContextConfiguration mergedConfig) { @@ -250,7 +251,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr private Class findConfigurationClass(Class testClass) { String propertyName = "%s.SpringBootConfiguration.%s" - .formatted(SpringBootTestContextBootstrapper.class.getName(), testClass.getName()); + .formatted(SpringBootTestContextBootstrapper.class.getName(), testClass.getName()); String foundClassName = this.aotTestAttributes.getString(propertyName); if (foundClassName != null) { return ClassUtils.resolveClassName(foundClassName, testClass.getClassLoader()); @@ -265,7 +266,7 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr private boolean containsNonTestComponent(Class[] classes) { for (Class candidate : classes) { if (!MergedAnnotations.from(candidate, SearchStrategy.INHERITED_ANNOTATIONS) - .isPresent(TestConfiguration.class)) { + .isPresent(TestConfiguration.class)) { return true; } } @@ -351,8 +352,9 @@ public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstr protected void verifyConfiguration(Class testClass) { SpringBootTest springBootTest = getAnnotation(testClass); - if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment()) && MergedAnnotations - .from(testClass, SearchStrategy.INHERITED_ANNOTATIONS).isPresent(WebAppConfiguration.class)) { + if (springBootTest != null && isListeningOnPort(springBootTest.webEnvironment()) + && MergedAnnotations.from(testClass, SearchStrategy.INHERITED_ANNOTATIONS) + .isPresent(WebAppConfiguration.class)) { throw new IllegalStateException("@WebAppConfiguration should only be used " + "with @SpringBootTest when @SpringBootTest is configured with a " + "mock web environment. Please remove @WebAppConfiguration or reconfigure @SpringBootTest."); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java index d4c13e5613..317593cb68 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -223,7 +223,7 @@ public class ApplicationContextAssert throwAssertionError(contextFailedToStartWhenExpecting("to get beans names with type:%n <%s>", type)); } return Assertions.assertThat(getApplicationContext().getBeanNamesForType(type)) - .as("Bean names of type <%s> from <%s>", type, getApplicationContext()); + .as("Bean names of type <%s> from <%s>", type, getApplicationContext()); } /** @@ -359,8 +359,8 @@ public class ApplicationContextAssert "%nExpecting:%n <%s>%nto contain a bean of name:%n <%s> (%s)%nbut found:%n <%s> of type <%s>", getApplicationContext(), name, type, bean, bean.getClass())); } - return Assertions.assertThat((T) bean).as("Bean of name <%s> and type <%s> from <%s>", name, type, - getApplicationContext()); + return Assertions.assertThat((T) bean) + .as("Bean of name <%s> and type <%s> from <%s>", name, type, getApplicationContext()); } private Object findBean(String name) { @@ -411,7 +411,7 @@ public class ApplicationContextAssert throwAssertionError(contextFailedToStartWhenExpecting("to get beans of type:%n <%s>", type)); } return Assertions.assertThat(scope.getBeansOfType(getApplicationContext(), type)) - .as("Beans of type <%s> from <%s>", type, getApplicationContext()); + .as("Beans of type <%s> from <%s>", type, getApplicationContext()); } /** diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java index 6ed4a08305..685fb11714 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -96,9 +96,9 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan + this.startupFailure.getClass().getName() + "]"; } ToStringCreator builder = new ToStringCreator(this.applicationContext) - .append("id", this.applicationContext.getId()) - .append("applicationName", this.applicationContext.getApplicationName()) - .append("beanDefinitionCount", this.applicationContext.getBeanDefinitionCount()); + .append("id", this.applicationContext.getId()) + .append("applicationName", this.applicationContext.getApplicationName()) + .append("beanDefinitionCount", this.applicationContext.getBeanDefinitionCount()); return "Started application " + builder; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java index 01b46d68b4..a011778fdb 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -338,7 +338,7 @@ public abstract class AbstractApplicationContextRunner consumer) { withContextClassLoader(this.runnerConfiguration.classLoader, () -> this.runnerConfiguration.systemProperties - .applyToSystemProperties(() -> consumeAssertableContext(true, consumer))); + .applyToSystemProperties(() -> consumeAssertableContext(true, consumer))); return (SELF) this; } @@ -354,7 +354,7 @@ public abstract class AbstractApplicationContextRunner consumer) { withContextClassLoader(this.runnerConfiguration.classLoader, () -> this.runnerConfiguration.systemProperties - .applyToSystemProperties(() -> consumeAssertableContext(false, consumer))); + .applyToSystemProperties(() -> consumeAssertableContext(false, consumer))); return (SELF) this; } @@ -396,7 +396,7 @@ public abstract class AbstractApplicationContextRunner extends AbstractJsonMarshalTester { @Override protected JsonContent getJsonContent(String json) { - Configuration configuration = Configuration.builder().jsonProvider(new JacksonJsonProvider(this.objectMapper)) - .mappingProvider(new JacksonMappingProvider(this.objectMapper)).build(); + Configuration configuration = Configuration.builder() + .jsonProvider(new JacksonJsonProvider(this.objectMapper)) + .mappingProvider(new JacksonMappingProvider(this.objectMapper)) + .build(); return new JsonContent<>(getResourceLoadClass(), getType(), json, configuration); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java index 567a29bcec..0deea2e35f 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,10 +67,12 @@ class DefinitionsParser { private void parseElement(AnnotatedElement element, Class source) { MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.SUPERCLASS); - annotations.stream(MockBean.class).map(MergedAnnotation::synthesize) - .forEach((annotation) -> parseMockBeanAnnotation(annotation, element, source)); - annotations.stream(SpyBean.class).map(MergedAnnotation::synthesize) - .forEach((annotation) -> parseSpyBeanAnnotation(annotation, element, source)); + annotations.stream(MockBean.class) + .map(MergedAnnotation::synthesize) + .forEach((annotation) -> parseMockBeanAnnotation(annotation, element, source)); + annotations.stream(SpyBean.class) + .map(MergedAnnotation::synthesize) + .forEach((annotation) -> parseSpyBeanAnnotation(annotation, element, source)); } private void parseMockBeanAnnotation(MockBean annotation, AnnotatedElement element, Class source) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java index 8b874e0618..ff6cdff238 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -129,9 +129,13 @@ class MockDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()).append("typeToMock", this.typeToMock) - .append("extraInterfaces", this.extraInterfaces).append("answer", this.answer) - .append("serializable", this.serializable).append("reset", getReset()).toString(); + return new ToStringCreator(this).append("name", getName()) + .append("typeToMock", this.typeToMock) + .append("extraInterfaces", this.extraInterfaces) + .append("answer", this.answer) + .append("serializable", this.serializable) + .append("reset", getReset()) + .toString(); } T createMock() { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java index 55fb5e8dbb..7c3814849e 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -83,7 +83,7 @@ public class MockitoPostProcessor implements InstantiationAwareBeanPostProcessor private static final String BEAN_NAME = MockitoPostProcessor.class.getName(); private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions - .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); + .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); private static final BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java index a46c659594..c2bfbf6e1e 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -108,7 +108,7 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener parser.parse(testContext.getTestClass()); if (!parser.getDefinitions().isEmpty()) { MockitoPostProcessor postProcessor = testContext.getApplicationContext() - .getBean(MockitoPostProcessor.class); + .getBean(MockitoPostProcessor.class); for (Definition definition : parser.getDefinitions()) { Field field = parser.getField(definition); if (field != null) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java index dbfc28f636..947bdf1ada 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -79,8 +79,10 @@ class SpyDefinition extends Definition { @Override public String toString() { - return new ToStringCreator(this).append("name", getName()).append("typeToSpy", this.typeToSpy) - .append("reset", getReset()).toString(); + return new ToStringCreator(this).append("name", getName()) + .append("typeToSpy", this.typeToSpy) + .append("reset", getReset()) + .toString(); } T createSpy(Object instance) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java index d98cc20932..41972da975 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessor implements EnvironmentPos @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MapPropertySource source = (MapPropertySource) environment.getPropertySources() - .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); if (source == null || isTestServerPortFixed(source, environment) || isTestManagementPortConfigured(source)) { return; } @@ -70,10 +70,14 @@ class SpringBootTestRandomPortEnvironmentPostProcessor implements EnvironmentPos } private Integer getPropertyAsInteger(ConfigurableEnvironment environment, String property, Integer defaultValue) { - return environment.getPropertySources().stream().filter( - (source) -> !source.getName().equals(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME)) - .map((source) -> getPropertyAsInteger(source, property, environment)).filter(Objects::nonNull) - .findFirst().orElse(defaultValue); + return environment.getPropertySources() + .stream() + .filter((source) -> !source.getName() + .equals(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME)) + .map((source) -> getPropertyAsInteger(source, property, environment)) + .filter(Objects::nonNull) + .findFirst() + .orElse(defaultValue); } private Integer getPropertyAsInteger(PropertySource source, String property, diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java index 0679a40189..dca0856b70 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java @@ -964,12 +964,12 @@ public class TestRestTemplate { private URI resolveUri(RequestEntity entity) { if (entity instanceof UriTemplateRequestEntity templatedUriEntity) { if (templatedUriEntity.getVars() != null) { - return this.restTemplate.getUriTemplateHandler().expand(templatedUriEntity.getUriTemplate(), - templatedUriEntity.getVars()); + return this.restTemplate.getUriTemplateHandler() + .expand(templatedUriEntity.getUriTemplate(), templatedUriEntity.getVars()); } else if (templatedUriEntity.getVarsMap() != null) { - return this.restTemplate.getUriTemplateHandler().expand(templatedUriEntity.getUriTemplate(), - templatedUriEntity.getVarsMap()); + return this.restTemplate.getUriTemplateHandler() + .expand(templatedUriEntity.getUriTemplate(), templatedUriEntity.getVarsMap()); } throw new IllegalStateException( "No variables specified for URI template: " + templatedUriEntity.getUriTemplate()); @@ -1046,7 +1046,8 @@ public class TestRestTemplate { } if (readTimeout != null) { SocketConfig socketConfig = SocketConfig.custom() - .setSoTimeout((int) readTimeout.toMillis(), TimeUnit.MILLISECONDS).build(); + .setSoTimeout((int) readTimeout.toMillis(), TimeUnit.MILLISECONDS) + .build(); builder.setDefaultSocketConfig(socketConfig); } return builder.build(); @@ -1055,9 +1056,11 @@ public class TestRestTemplate { private SSLConnectionSocketFactory createSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .build(); - return SSLConnectionSocketFactoryBuilder.create().setSslContext(sslContext) - .setTlsVersions(TLS.V_1_3, TLS.V_1_2).build(); + .build(); + return SSLConnectionSocketFactoryBuilder.create() + .setSslContext(sslContext) + .setTlsVersions(TLS.V_1_3, TLS.V_1_2) + .build(); } @Override diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java index 550b612576..fa7cb7cbc4 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { return; } SpringBootTest springBootTest = TestContextAnnotationUtils - .findMergedAnnotation(mergedContextConfiguration.getTestClass(), SpringBootTest.class); + .findMergedAnnotation(mergedContextConfiguration.getTestClass(), SpringBootTest.class); if (springBootTest.webEnvironment().isEmbedded()) { registerTestRestTemplate(context); } @@ -150,7 +150,7 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { private boolean isSslEnabled(ApplicationContext context) { try { AbstractServletWebServerFactory webServerFactory = context - .getBean(AbstractServletWebServerFactory.class); + .getBean(AbstractServletWebServerFactory.class); return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled(); } catch (NoSuchBeanDefinitionException ex) { diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java index 7bc6d6aad0..f7f18d2c14 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -215,7 +215,7 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private boolean isSslEnabled(ApplicationContext context) { try { AbstractReactiveWebServerFactory webServerFactory = context - .getBean(AbstractReactiveWebServerFactory.class); + .getBean(AbstractReactiveWebServerFactory.class); return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled(); } catch (NoSuchBeanDefinitionException ex) { @@ -225,7 +225,8 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private void customizeWebTestClientBuilder(WebTestClient.Builder clientBuilder, ApplicationContext context) { for (WebTestClientBuilderCustomizer customizer : context - .getBeansOfType(WebTestClientBuilderCustomizer.class).values()) { + .getBeansOfType(WebTestClientBuilderCustomizer.class) + .values()) { customizer.customize(clientBuilder); } } @@ -233,9 +234,10 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private void customizeWebTestClientCodecs(WebTestClient.Builder clientBuilder, ApplicationContext context) { Collection codecCustomizers = context.getBeansOfType(CodecCustomizer.class).values(); if (!CollectionUtils.isEmpty(codecCustomizers)) { - clientBuilder.exchangeStrategies(ExchangeStrategies.builder().codecs( - (codecs) -> codecCustomizers.forEach((codecCustomizer) -> codecCustomizer.customize(codecs))) - .build()); + clientBuilder.exchangeStrategies(ExchangeStrategies.builder() + .codecs((codecs) -> codecCustomizers + .forEach((codecCustomizer) -> codecCustomizer.customize(codecs))) + .build()); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java index f4f28c50b8..08858cbca4 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests.java @@ -69,8 +69,15 @@ abstract class AbstractSpringBootTestEmbeddedReactiveWebEnvironmentTests { @Test void runAndTestHttpEndpoint() { assertThat(this.port).isNotEqualTo(8080).isNotZero(); - WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).responseTimeout(Duration.ofMinutes(5)) - .build().get().uri("/").exchange().expectBody(String.class).isEqualTo("Hello World"); + WebTestClient.bindToServer() + .baseUrl("http://localhost:" + this.port) + .responseTimeout(Duration.ofMinutes(5)) + .build() + .get() + .uri("/") + .exchange() + .expectBody(String.class) + .isEqualTo("Hello World"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java index fbbac39d87..e0da18ec12 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,13 +37,13 @@ class AnnotatedClassFinderTests { @Test void findFromClassWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromClass((Class) null)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test void findFromPackageWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.finder.findFromPackage((String) null)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java index a488d433e4..4f0eede1c7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class FilteredClassLoaderTests { try (FilteredClassLoader classLoader = new FilteredClassLoader( FilteredClassLoaderTests.class.getPackage().getName())) { assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); + .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); } } @@ -52,7 +52,7 @@ class FilteredClassLoaderTests { void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader(FilteredClassLoaderTests.class)) { assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); + .isThrownBy(() -> Class.forName(getClass().getName(), false, classLoader)); } } @@ -117,7 +117,7 @@ class FilteredClassLoaderTests { Class hiddenClass = FilteredClassLoaderTests.class; try (FilteredClassLoader classLoader = new FilteredClassLoader(hiddenClass)) { assertThatIllegalArgumentException() - .isThrownBy(() -> classLoader.publicDefineClass(hiddenClass.getName(), new byte[] {}, null)); + .isThrownBy(() -> classLoader.publicDefineClass(hiddenClass.getName(), new byte[] {}, null)); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java index a1ce41e80d..16219c6060 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class ImportsContextCustomizerFactoryIntegrationTests { @Test void testItselfIsNotABean() { assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(getClass())); + .isThrownBy(() -> this.context.getBean(getClass())); } @Component diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java index bdf7592c86..48794759f0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java @@ -77,8 +77,8 @@ class ImportsContextCustomizerFactoryTests { @Test void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null)) - .withMessageContaining("Test classes cannot include @Bean methods"); + .isThrownBy(() -> this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null)) + .withMessageContaining("Test classes cannot include @Bean methods"); } @Test @@ -93,7 +93,7 @@ class ImportsContextCustomizerFactoryTests { @Test void selfAnnotatingAnnotationDoesNotCauseStackOverflow() { assertThat(this.factory.createContextCustomizer(TestWithImportAndSelfAnnotatingAnnotation.class, null)) - .isNotNull(); + .isNotNull(); } static class TestWithNoImport { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java index 28673bb532..f047bf9840 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,37 +47,37 @@ class ImportsContextCustomizerTests { @Test void importSelectorsCouldUseAnyAnnotations() { assertThat(new ImportsContextCustomizer(FirstImportSelectorAnnotatedClass.class)) - .isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class)); + .isNotEqualTo(new ImportsContextCustomizer(SecondImportSelectorAnnotatedClass.class)); } @Test void determinableImportSelector() { assertThat(new ImportsContextCustomizer(FirstDeterminableImportSelectorAnnotatedClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondDeterminableImportSelectorAnnotatedClass.class)); } @Test void customizersForTestClassesWithDifferentKotlinMetadataAreEqual() { assertThat(new ImportsContextCustomizer(FirstKotlinAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondKotlinAnnotatedTestClass.class)); } @Test void customizersForTestClassesWithDifferentSpockFrameworkAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockFrameworkAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondSpockFrameworkAnnotatedTestClass.class)); } @Test void customizersForTestClassesWithDifferentSpockLangAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstSpockLangAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondSpockLangAnnotatedTestClass.class)); } @Test void customizersForTestClassesWithDifferentJUnitAnnotationsAreEqual() { assertThat(new ImportsContextCustomizer(FirstJUnitAnnotatedTestClass.class)) - .isEqualTo(new ImportsContextCustomizer(SecondJUnitAnnotatedTestClass.class)); + .isEqualTo(new ImportsContextCustomizer(SecondJUnitAnnotatedTestClass.class)); } @Import(TestImportSelector.class) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderAotTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderAotTests.java index e3b4c2dd8d..3943ff254f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderAotTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderAotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,8 +59,9 @@ class SpringBootContextLoaderAotTests { TestContextAotGenerator generator = new TestContextAotGenerator(generatedFiles); Class testClass = ExampleTest.class; generator.processAheadOfTime(Stream.of(testClass)); - TestCompiler.forSystem().with(CompilerFiles.from(generatedFiles)) - .compile(ThrowingConsumer.of((compiled) -> assertCompiledTest(testClass))); + TestCompiler.forSystem() + .with(CompilerFiles.from(generatedFiles)) + .compile(ThrowingConsumer.of((compiled) -> assertCompiledTest(testClass))); } private void assertCompiledTest(Class testClass) throws Exception { @@ -71,9 +72,9 @@ class SpringBootContextLoaderAotTests { TestContextBootstrapper testContextBootstrapper = BootstrapUtils.resolveTestContextBootstrapper(testClass); MergedContextConfiguration mergedConfig = testContextBootstrapper.buildMergedContextConfiguration(); ApplicationContextInitializer contextInitializer = aotContextInitializers - .getContextInitializer(testClass); + .getContextInitializer(testClass); ConfigurableApplicationContext context = (ConfigurableApplicationContext) ((AotContextLoader) mergedConfig - .getContextLoader()).loadContextForAotRuntime(mergedConfig, contextInitializer); + .getContextLoader()).loadContextForAotRuntime(mergedConfig, contextInitializer); assertThat(context).isExactlyInstanceOf(GenericApplicationContext.class); String[] beanNames = context.getBeanNamesForType(ExampleBean.class); BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition(beanNames[0]); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java index 3c72a59eb0..6715719eab 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java @@ -142,7 +142,7 @@ class SpringBootContextLoaderTests { @Test void testPropertyValuesShouldTakePrecedenceWhenInlinedPropertiesPresentAndProfilesActive() { TestContext context = new ExposedTestContextManager(ActiveProfileWithInlinedProperties.class) - .getExposedTestContext(); + .getExposedTestContext(); StandardEnvironment environment = (StandardEnvironment) context.getApplicationContext().getEnvironment(); TestPropertyValues.of("key=thisValue").applyTo(environment); assertThat(environment.getProperty("key")).isEqualTo("thisValue"); @@ -153,9 +153,11 @@ class SpringBootContextLoaderTests { void propertySourceOrdering() { TestContext context = new ExposedTestContextManager(PropertySourceOrdering.class).getExposedTestContext(); ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getApplicationContext() - .getEnvironment(); - List names = environment.getPropertySources().stream().map(PropertySource::getName) - .collect(Collectors.toCollection(ArrayList::new)); + .getEnvironment(); + List names = environment.getPropertySources() + .stream() + .map(PropertySource::getName) + .collect(Collectors.toCollection(ArrayList::new)); String last = names.remove(names.size() - 1); assertThat(names).containsExactly("configurationProperties", "Inlined Test Properties", "commandLineArgs", "servletConfigInitParams", "servletContextInitParams", "systemProperties", "systemEnvironment", @@ -166,29 +168,30 @@ class SpringBootContextLoaderTests { @Test void whenEnvironmentChangesWebApplicationTypeToNoneThenContextTypeChangesAccordingly() { TestContext context = new ExposedTestContextManager(ChangingWebApplicationTypeToNone.class) - .getExposedTestContext(); + .getExposedTestContext(); assertThat(context.getApplicationContext()).isNotInstanceOf(WebApplicationContext.class); } @Test void whenEnvironmentChangesWebApplicationTypeToReactiveThenContextTypeChangesAccordingly() { TestContext context = new ExposedTestContextManager(ChangingWebApplicationTypeToReactive.class) - .getExposedTestContext(); + .getExposedTestContext(); assertThat(context.getApplicationContext()).isInstanceOf(GenericReactiveWebApplicationContext.class); } @Test void whenUseMainMethodAlwaysAndMainMethodThrowsException() { TestContext testContext = new ExposedTestContextManager(UseMainMethodAlwaysAndMainMethodThrowsException.class) - .getExposedTestContext(); - assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext).havingCause() - .withMessageContaining("ThrownFromMain"); + .getExposedTestContext(); + assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext) + .havingCause() + .withMessageContaining("ThrownFromMain"); } @Test void whenUseMainMethodWhenAvailableAndNoMainMethod() { TestContext testContext = new ExposedTestContextManager(UseMainMethodWhenAvailableAndNoMainMethod.class) - .getExposedTestContext(); + .getExposedTestContext(); ApplicationContext applicationContext = testContext.getApplicationContext(); assertThat(applicationContext.getEnvironment().getActiveProfiles()).isEmpty(); } @@ -196,7 +199,7 @@ class SpringBootContextLoaderTests { @Test void whenUseMainMethodWhenAvailableAndMainMethod() { TestContext testContext = new ExposedTestContextManager(UseMainMethodWhenAvailableAndMainMethod.class) - .getExposedTestContext(); + .getExposedTestContext(); ApplicationContext applicationContext = testContext.getApplicationContext(); assertThat(applicationContext.getEnvironment().getActiveProfiles()).contains("frommain"); } @@ -211,35 +214,36 @@ class SpringBootContextLoaderTests { @Test void whenUseMainMethodWithBeanThrowingException() { TestContext testContext = new ExposedTestContextManager(UseMainMethodWithBeanThrowingException.class) - .getExposedTestContext(); - assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext).havingCause() - .satisfies((exception) -> { - assertThat(exception).isInstanceOf(BeanCreationException.class); - assertThat(exception) - .isSameAs(ContextLoaderApplicationContextFailureProcessor.contextLoadException); - }); + .getExposedTestContext(); + assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext) + .havingCause() + .satisfies((exception) -> { + assertThat(exception).isInstanceOf(BeanCreationException.class); + assertThat(exception).isSameAs(ContextLoaderApplicationContextFailureProcessor.contextLoadException); + }); assertThat(ContextLoaderApplicationContextFailureProcessor.failedContext).isNotNull(); } @Test void whenNoMainMethodWithBeanThrowingException() { TestContext testContext = new ExposedTestContextManager(NoMainMethodWithBeanThrowingException.class) - .getExposedTestContext(); - assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext).havingCause() - .satisfies((exception) -> { - assertThat(exception).isInstanceOf(BeanCreationException.class); - assertThat(exception) - .isSameAs(ContextLoaderApplicationContextFailureProcessor.contextLoadException); - }); + .getExposedTestContext(); + assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext) + .havingCause() + .satisfies((exception) -> { + assertThat(exception).isInstanceOf(BeanCreationException.class); + assertThat(exception).isSameAs(ContextLoaderApplicationContextFailureProcessor.contextLoadException); + }); assertThat(ContextLoaderApplicationContextFailureProcessor.failedContext).isNotNull(); } @Test void whenUseMainMethodWithContextHierarchyThrowsException() { TestContext testContext = new ExposedTestContextManager(UseMainMethodWithContextHierarchy.class) - .getExposedTestContext(); - assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext).havingCause() - .withMessage("UseMainMethod.ALWAYS cannot be used with @ContextHierarchy tests"); + .getExposedTestContext(); + assertThatIllegalStateException().isThrownBy(testContext::getApplicationContext) + .havingCause() + .withMessage("UseMainMethod.ALWAYS cannot be used with @ContextHierarchy tests"); } private String[] getActiveProfiles(Class testClass) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java index 341dce2b6e..f2a1ce9711 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentMockTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,7 +62,7 @@ class SpringBootTestWebEnvironmentMockTests { @Test void validateWebApplicationContextIsSet() { WebApplicationContext fromServletContext = WebApplicationContextUtils - .getWebApplicationContext(this.servletContext); + .getWebApplicationContext(this.servletContext); assertThat(fromServletContext).isSameAs(this.context); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java index 2f85db9af4..00cd359c85 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWebEnvironmentRandomPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class SpringBootTestWebEnvironmentRandomPortTests extends AbstractSpringBootTest @Test void testRestTemplateShouldUseBuilder() { assertThat(getRestTemplate().getRestTemplate().getMessageConverters()) - .hasAtLeastOneElementOfType(MyConverter.class); + .hasAtLeastOneElementOfType(MyConverter.class); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java index c2a32af3fb..3ed88de6be 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class SpringBootTestWithClassesIntegrationTests { void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); + .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java index a52fd7b831..0983f849b1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ class SpringBootTestWithContextConfigurationIntegrationTests { void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); + .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java index 2a859b2b8a..9820b5a2ed 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithTestPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -65,7 +65,7 @@ class SpringBootTestWithTestPropertySourceTests { @Test void propertyFromPropertySourcePropertiesOverridesPropertyFromPropertySourceLocations() { assertThat(this.config.propertySourceInlinedOverridesPropertySourceLocation) - .isEqualTo("property-source-inlined"); + .isEqualTo("property-source-inlined"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java index 95d56f7abc..719eb30323 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/TestConfigurationTests.java @@ -34,14 +34,14 @@ class TestConfigurationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultTestConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultTestConfiguration.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", true); } @Test void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(NoBeanMethodProxyingTestConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingTestConfiguration.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", false); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java index cfddb93fd3..8547e0f2ca 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java @@ -64,37 +64,38 @@ class ApplicationContextAssertProviderTests { void getWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test void getWhenTypeIsClassShouldThrowException() { assertThatIllegalArgumentException().isThrownBy( () -> ApplicationContextAssertProvider.get(null, ApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test void getWhenContextTypeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, - ApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("Type must be an interface"); + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContextClass.class, + ApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("Type must be an interface"); } @Test void getWhenContextTypeIsClassShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy(() -> ApplicationContextAssertProvider - .get(TestAssertProviderApplicationContext.class, null, this.mockContextSupplier)) - .withMessageContaining("ContextType must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, null, + this.mockContextSupplier)) + .withMessageContaining("ContextType must not be null"); } @Test void getWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, - StaticApplicationContext.class, this.mockContextSupplier)) - .withMessageContaining("ContextType must be an interface"); + .isThrownBy(() -> ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, + StaticApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("ContextType must be an interface"); } @Test @@ -109,8 +110,9 @@ class ApplicationContextAssertProviderTests { void getWhenContextFailsShouldReturnProxyThatThrowsExceptions() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThat((Object) context).isNotNull(); - assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")).withCause(this.startupFailure) - .withMessageContaining("failed to start"); + assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")) + .withCause(this.startupFailure) + .withMessageContaining("failed to start"); } @Test @@ -123,7 +125,8 @@ class ApplicationContextAssertProviderTests { void getSourceContextWhenContextFailsShouldThrowException() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThatIllegalStateException().isThrownBy(context::getSourceApplicationContext) - .withCause(this.startupFailure).withMessageContaining("failed to start"); + .withCause(this.startupFailure) + .withMessageContaining("failed to start"); } @Test @@ -136,8 +139,9 @@ class ApplicationContextAssertProviderTests { void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() { ApplicationContextAssertProvider context = get(this.startupFailureSupplier); assertThatIllegalStateException() - .isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class)) - .withCause(this.startupFailure).withMessageContaining("failed to start"); + .isThrownBy(() -> context.getSourceApplicationContext(ApplicationContext.class)) + .withCause(this.startupFailure) + .withMessageContaining("failed to start"); } @Test @@ -172,7 +176,7 @@ class ApplicationContextAssertProviderTests { void toStringWhenContextStartsShouldReturnSimpleString() { ApplicationContextAssertProvider context = get(this.mockContextSupplier); assertThat(context.toString()).startsWith("Started application [ConfigurableApplicationContext.MockitoMock") - .endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]"); + .endsWith("id = [null], applicationName = [null], beanDefinitionCount = 0]"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java index 2c06cc99ca..1990c5c633 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,7 +62,7 @@ class ApplicationContextAssertTests { @Test void createWhenApplicationContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContextAssert<>(null, null)) - .withMessageContaining("ApplicationContext must not be null"); + .withMessageContaining("ApplicationContext must not be null"); } @Test @@ -84,15 +84,15 @@ class ApplicationContextAssertTests { @Test void hasBeanWhenHasNoBeanShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasBean("foo")) - .withMessageContaining("no such bean"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasBean("foo")) + .withMessageContaining("no such bean"); } @Test void hasBeanWhenNotStartedShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo")) - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo")) + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -104,8 +104,8 @@ class ApplicationContextAssertTests { @Test void hasSingleBeanWhenHasNoBeansShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) - .withMessageContaining("to have a single bean of type"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("to have a single bean of type"); } @Test @@ -113,16 +113,16 @@ class ApplicationContextAssertTests { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) - .withMessageContaining("but found:"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("but found:"); } @Test void hasSingleBeanWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) - .withMessageContaining("to have a single bean of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) + .withMessageContaining("to have a single bean of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -130,8 +130,8 @@ class ApplicationContextAssertTests { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) - .withMessageContaining("but found:"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("but found:"); } @Test @@ -150,24 +150,24 @@ class ApplicationContextAssertTests { void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + .withMessageContaining("but found"); } @Test void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) - .withMessageContaining("not to have any beans of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) + .withMessageContaining("not to have any beans of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test void doesNotHaveBeanOfTypeWhenInParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -185,15 +185,16 @@ class ApplicationContextAssertTests { void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) + .withMessageContaining("but found"); } @Test void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) - .withMessageContaining("not to have any beans of name").withMessageContaining("failed to start"); + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .withMessageContaining("not to have any beans of name") + .withMessageContaining("failed to start"); } @Test @@ -211,9 +212,9 @@ class ApplicationContextAssertTests { @Test void getBeanNamesWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) - .withMessageContaining("not to have any beans of name") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .withMessageContaining("not to have any beans of name") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -232,8 +233,8 @@ class ApplicationContextAssertTests { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -246,9 +247,9 @@ class ApplicationContextAssertTests { @Test void getBeanOfTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class)) - .withMessageContaining("to contain bean of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class)) + .withMessageContaining("to contain bean of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -268,8 +269,8 @@ class ApplicationContextAssertTests { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) - .withMessageContaining("but found"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -293,9 +294,9 @@ class ApplicationContextAssertTests { @Test void getBeanOfNameWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo")) - .withMessageContaining("to contain a bean of name") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo")) + .withMessageContaining("to contain a bean of name") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -313,16 +314,16 @@ class ApplicationContextAssertTests { void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class)) - .withMessageContaining("of type"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean("foo", String.class)) + .withMessageContaining("of type"); } @Test void getBeanOfNameAndTypeWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class)) - .withMessageContaining("to contain a bean of name") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", Foo.class)) + .withMessageContaining("to contain a bean of name") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -340,9 +341,9 @@ class ApplicationContextAssertTests { @Test void getBeansWhenFailedToStartShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class)) - .withMessageContaining("to get beans of type") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class)) + .withMessageContaining("to get beans of type") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -367,8 +368,8 @@ class ApplicationContextAssertTests { @Test void getFailureWhenDidNotFailShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).getFailure()) - .withMessageContaining("context started"); + .isThrownBy(() -> assertThat(getAssert(this.context)).getFailure()) + .withMessageContaining("context started"); } @Test @@ -379,16 +380,16 @@ class ApplicationContextAssertTests { @Test void hasFailedWhenNotFailedShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.context)).hasFailed()) - .withMessageContaining("to have failed"); + .isThrownBy(() -> assertThat(getAssert(this.context)).hasFailed()) + .withMessageContaining("to have failed"); } @Test void hasNotFailedWhenFailedShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed()) - .withMessageContaining("to have not failed") - .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed()) + .withMessageContaining("to have not failed") + .withMessageContaining(String.format("but context failed to start:%n java.lang.RuntimeException")); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java index 7ab204f96f..91189ce2a9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ class AssertableApplicationContextTests { @Test void getShouldReturnProxy() { AssertableApplicationContext context = AssertableApplicationContext - .get(() -> mock(ConfigurableApplicationContext.class)); + .get(() -> mock(ConfigurableApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableApplicationContext.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java index 8e84cbf9b0..b84b776bbd 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableReactiveWebApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ class AssertableReactiveWebApplicationContextTests { @Test void getShouldReturnProxy() { AssertableReactiveWebApplicationContext context = AssertableReactiveWebApplicationContext - .get(() -> mock(ConfigurableReactiveWebApplicationContext.class)); + .get(() -> mock(ConfigurableReactiveWebApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableReactiveWebApplicationContext.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java index 2387d7f419..53873f9c47 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/AssertableWebApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ class AssertableWebApplicationContextTests { @Test void getShouldReturnProxy() { AssertableWebApplicationContext context = AssertableWebApplicationContext - .get(() -> mock(ConfigurableWebApplicationContext.class)); + .get(() -> mock(ConfigurableWebApplicationContext.class)); assertThat(context).isInstanceOf(ConfigurableWebApplicationContext.class); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java index dc20356094..db724a374a 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -43,10 +43,10 @@ class SpringBootTestContextBootstrapperTests { @Test void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() { assertThatIllegalStateException() - .isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) - .withMessageContaining("@WebAppConfiguration should only be used with " - + "@SpringBootTest when @SpringBootTest is configured with a mock web " - + "environment. Please remove @WebAppConfiguration or reconfigure @SpringBootTest."); + .isThrownBy(() -> buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) + .withMessageContaining("@WebAppConfiguration should only be used with " + + "@SpringBootTest when @SpringBootTest is configured with a mock web " + + "environment. Please remove @WebAppConfiguration or reconfigure @SpringBootTest."); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java index 3c8ac98ec2..394eea1578 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/TestTypeExcludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class TestTypeExcludeFilterTests { @Test void matchesJUnit4TestClass() throws Exception { assertThat(this.filter.match(getMetadataReader(TestTypeExcludeFilterTests.class), this.metadataReaderFactory)) - .isTrue(); + .isTrue(); } @Test @@ -53,13 +53,13 @@ class TestTypeExcludeFilterTests { @Test void matchesJUnitJupiterRepeatedTestClass() throws Exception { assertThat(this.filter.match(getMetadataReader(JupiterRepeatedTestExample.class), this.metadataReaderFactory)) - .isTrue(); + .isTrue(); } @Test void matchesJUnitJupiterTestFactoryClass() throws Exception { assertThat(this.filter.match(getMetadataReader(JupiterTestFactoryExample.class), this.metadataReaderFactory)) - .isTrue(); + .isTrue(); } @Test @@ -70,19 +70,22 @@ class TestTypeExcludeFilterTests { @Test void matchesNestedConfigurationClassWithoutTestMethodsIfItHasRunWith() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractTestWithConfigAndRunWith.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } @Test void matchesNestedConfigurationClassWithoutTestMethodsIfItHasExtendWith() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndExtendWith.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } @Test void matchesNestedConfigurationClassWithoutTestMethodsIfItHasTestable() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractJupiterTestWithConfigAndTestable.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } @Test @@ -98,7 +101,8 @@ class TestTypeExcludeFilterTests { @Test void matchesNestedConfigurationClassWithoutTestNgAnnotation() throws Exception { assertThat(this.filter.match(getMetadataReader(AbstractTestNgTestWithConfig.Config.class), - this.metadataReaderFactory)).isTrue(); + this.metadataReaderFactory)) + .isTrue(); } private MetadataReader getMetadataReader(Class source) throws IOException { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java index ad38068f6f..cd309da536 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java @@ -73,7 +73,7 @@ abstract class AbstractApplicationContextRunnerTests assertThat(System.getProperties()).containsEntry(key, "value")); + .run((context) -> assertThat(System.getProperties()).containsEntry(key, "value")); assertThat(System.getProperties()).doesNotContainKey(key); } @@ -81,8 +81,9 @@ abstract class AbstractApplicationContextRunnerTests assertThat(context).hasFailed()); + get().withSystemProperties(key + "=value") + .withUserConfiguration(FailingConfig.class) + .run((context) -> assertThat(context).hasFailed()); assertThat(System.getProperties()).doesNotContainKey(key); } @@ -93,7 +94,7 @@ abstract class AbstractApplicationContextRunnerTests assertThat(System.getProperties()).containsEntry(key, "newValue")); + .run((context) -> assertThat(System.getProperties()).containsEntry(key, "newValue")); assertThat(System.getProperties().getProperty(key)).isEqualTo("value"); } finally { @@ -108,7 +109,7 @@ abstract class AbstractApplicationContextRunnerTests assertThat(context).hasBean("foo").hasBean("bar")); + get().withUserConfiguration(FooConfig.class) + .withConfiguration(UserConfigurations.of(BarConfig.class)) + .run((context) -> assertThat(context).hasBean("foo").hasBean("bar")); } @Test @@ -162,30 +164,32 @@ abstract class AbstractApplicationContextRunnerTests assertThatExceptionOfType(ClassNotFoundException.class) - .isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader()))); + .run((context) -> assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> ClassUtils.forName(Gson.class.getName(), context.getClassLoader()))); } @Test void runWithClassLoaderShouldSetClassLoaderOnConditionContext() { get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName())) - .withUserConfiguration(ConditionalConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class)); + .withUserConfiguration(ConditionalConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ConditionalConfig.class)); } @Test void consecutiveRunWithFilteredClassLoaderShouldHaveBeanWithLazyProperties() { - get().withClassLoader(new FilteredClassLoader(Gson.class)).withUserConfiguration(LazyConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); + get().withClassLoader(new FilteredClassLoader(Gson.class)) + .withUserConfiguration(LazyConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); - get().withClassLoader(new FilteredClassLoader(Gson.class)).withUserConfiguration(LazyConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); + get().withClassLoader(new FilteredClassLoader(Gson.class)) + .withUserConfiguration(LazyConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ExampleBeanWithLazyProperties.class)); } @Test void thrownRuleWorksWithCheckedException() { get().run((context) -> assertThatIOException().isThrownBy(() -> throwCheckedException("Expected message")) - .withMessageContaining("Expected message")); + .withMessageContaining("Expected message")); } @Test @@ -193,57 +197,62 @@ abstract class AbstractApplicationContextRunnerTests 42).run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure()).isInstanceOf(BeanDefinitionStoreException.class) - .hasMessageContaining("Invalid bean definition with name 'foo'") - .hasMessageContaining("@Bean definition illegally overridden by existing bean definition"); + .hasMessageContaining("Invalid bean definition with name 'foo'") + .hasMessageContaining("@Bean definition illegally overridden by existing bean definition"); }); } @Test void runDisablesCircularReferencesByDefault() { get().withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class) - .run((context) -> { - assertThat(context).hasFailed(); - assertThat(context).getFailure().hasRootCauseInstanceOf(BeanCurrentlyInCreationException.class); - }); + .run((context) -> { + assertThat(context).hasFailed(); + assertThat(context).getFailure().hasRootCauseInstanceOf(BeanCurrentlyInCreationException.class); + }); } @Test void circularReferencesCanBeAllowed() { get().withAllowCircularReferences(true) - .withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class) - .run((context) -> assertThat(context).hasNotFailed()); + .withUserConfiguration(ExampleConsumerConfiguration.class, ExampleProducerConfiguration.class) + .run((context) -> assertThat(context).hasNotFailed()); } @Test void runWithUserBeanShouldBeRegisteredInOrder() { - get().withAllowBeanDefinitionOverriding(true).withBean(String.class, () -> "one") - .withBean(String.class, () -> "two").withBean(String.class, () -> "three").run((context) -> { - assertThat(context).hasBean("string"); - assertThat(context.getBean("string")).isEqualTo("three"); - }); + get().withAllowBeanDefinitionOverriding(true) + .withBean(String.class, () -> "one") + .withBean(String.class, () -> "two") + .withBean(String.class, () -> "three") + .run((context) -> { + assertThat(context).hasBean("string"); + assertThat(context.getBean("string")).isEqualTo("three"); + }); } @Test void runWithConfigurationsAndUserBeanShouldRegisterUserBeanLast() { - get().withAllowBeanDefinitionOverriding(true).withUserConfiguration(FooConfig.class) - .withBean("foo", String.class, () -> "overridden").run((context) -> { - assertThat(context).hasBean("foo"); - assertThat(context.getBean("foo")).isEqualTo("overridden"); - }); + get().withAllowBeanDefinitionOverriding(true) + .withUserConfiguration(FooConfig.class) + .withBean("foo", String.class, () -> "overridden") + .run((context) -> { + assertThat(context).hasBean("foo"); + assertThat(context.getBean("foo")).isEqualTo("overridden"); + }); } @Test void changesMadeByInitializersShouldBeVisibleToRegisteredClasses() { get().withInitializer((context) -> context.getEnvironment().setActiveProfiles("test")) - .withUserConfiguration(ProfileConfig.class) - .run((context) -> assertThat(context).hasSingleBean(ProfileConfig.class)); + .withUserConfiguration(ProfileConfig.class) + .run((context) -> assertThat(context).hasSingleBean(ProfileConfig.class)); } @Test void prepareDoesNotRefreshContext() { get().withUserConfiguration(FooConfig.class).prepare((context) -> { assertThatIllegalStateException().isThrownBy(() -> context.getBean(String.class)) - .withMessageContaining("not been refreshed"); + .withMessageContaining("not been refreshed"); context.getSourceApplicationContext().refresh(); assertThat(context.getBean(String.class)).isEqualTo("foo"); }); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java index 5c19d70a6f..dc3bdb1138 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ContextConsumerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,7 +60,7 @@ class ContextConsumerTests { ContextConsumer firstConsumer = (context) -> assertThat(predicate.test(42)).isFalse(); ContextConsumer secondConsumer = (context) -> assertThat(predicate.test(24)).isFalse(); assertThatThrownBy(() -> firstConsumer.andThen(secondConsumer).accept(mock(ApplicationContext.class))) - .isInstanceOf(AssertionError.class); + .isInstanceOf(AssertionError.class); then(predicate).should().test(42); then(predicate).shouldHaveNoMoreInteractions(); } @@ -70,7 +70,7 @@ class ContextConsumerTests { ContextConsumer consumer = (context) -> { }; assertThatIllegalArgumentException().isThrownBy(() -> consumer.andThen(null)) - .withMessage("After must not be null"); + .withMessage("After must not be null"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/graphql/tester/HttpGraphQlTesterContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/graphql/tester/HttpGraphQlTesterContextCustomizerTests.java index f1e3c780e1..f148202feb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/graphql/tester/HttpGraphQlTesterContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/graphql/tester/HttpGraphQlTesterContextCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,17 +43,18 @@ class HttpGraphQlTesterContextCustomizerTests { @Test void whenContextIsNotABeanDefinitionRegistryHttpGraphQlTesterIsRegistered() { new ApplicationContextRunner(HttpGraphQlTesterContextCustomizerTests.TestApplicationContext::new) - .withInitializer(this::applyHttpGraphQlTesterContextCustomizer) - .run((context) -> assertThat(context).hasSingleBean(HttpGraphQlTester.class)); + .withInitializer(this::applyHttpGraphQlTesterContextCustomizer) + .run((context) -> assertThat(context).hasSingleBean(HttpGraphQlTester.class)); } @Test void whenUsingAotGeneratedArtifactsHttpGraphQlTesterIsNotRegistered() { new ApplicationContextRunner().withSystemProperties("spring.aot.enabled:true") - .withInitializer(this::applyHttpGraphQlTesterContextCustomizer).run((context) -> { - assertThat(context).doesNotHaveBean(HttpGraphQlTesterRegistrar.class); - assertThat(context).doesNotHaveBean(HttpGraphQlTester.class); - }); + .withInitializer(this::applyHttpGraphQlTesterContextCustomizer) + .run((context) -> { + assertThat(context).doesNotHaveBean(HttpGraphQlTesterRegistrar.class); + assertThat(context).doesNotHaveBean(HttpGraphQlTester.class); + }); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java index 8f27bf9ebd..87f6d33ffa 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -91,14 +91,14 @@ abstract class AbstractJsonMarshalTesterTests { @Test void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class))) - .withMessageContaining("ResourceLoadClass must not be null"); + .isThrownBy(() -> createTester(null, ResolvableType.forClass(ExampleObject.class))) + .withMessageContaining("ResourceLoadClass must not be null"); } @Test void createWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> createTester(getClass(), null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java index 804f643229..50602dd5c7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class BasicJsonTesterTests { @Test void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new BasicJsonTester(null)) - .withMessageContaining("ResourceLoadClass must not be null"); + .withMessageContaining("ResourceLoadClass must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java index 049e9e0fc4..eebd6569bb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -44,8 +44,8 @@ class DuplicateJsonObjectContextCustomizerFactoryTests { @Test void warningForMultipleVersions() { - new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null).customizeContext(null, - null); + new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null) + .customizeContext(null, null); assertThat(this.output).contains("Found multiple occurrences of org.json.JSONObject on the class path:"); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java index d007b5ff1e..ed1aca17d8 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -77,7 +77,7 @@ class GsonTesterIntegrationTests { void stringLiteral() throws Exception { String stringWithSpecialCharacters = "myString"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") - .isEqualTo(stringWithSpecialCharacters); + .isEqualTo(stringWithSpecialCharacters); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java index 7ca858e7f0..62fe8f3df9 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,14 +37,14 @@ class GsonTesterTests extends AbstractJsonMarshalTesterTests { @Test void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create())) - .withMessageContaining("TestInstance must not be null"); + .withMessageContaining("TestInstance must not be null"); } @Test void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) - .withMessageContaining("Marshaller must not be null"); + .isThrownBy(() -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java index f71c171a28..5a97f9f7c0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterIntegrationTests.java @@ -81,7 +81,7 @@ class JacksonTesterIntegrationTests { JacksonTester.initFields(this, new ObjectMapper()); String stringWithSpecialCharacters = "myString"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") - .isEqualTo(stringWithSpecialCharacters); + .isEqualTo(stringWithSpecialCharacters); } @Test @@ -95,7 +95,7 @@ class JacksonTesterIntegrationTests { // restores the symmetry. See gh-15727 String stringWithSpecialCharacters = "\u0006\u007F"; assertThat(this.stringJson.write(stringWithSpecialCharacters)).extractingJsonPathStringValue("@") - .isEqualTo(stringWithSpecialCharacters); + .isEqualTo(stringWithSpecialCharacters); } @Test @@ -105,7 +105,7 @@ class JacksonTesterIntegrationTests { object.setName("Spring"); object.setAge(123); JsonContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) - .write(object); + .write(object); assertThat(content).extractingJsonPathStringValue("@.name").isEqualTo("Spring"); assertThat(content).doesNotHaveJsonPathValue("age"); } @@ -115,7 +115,7 @@ class JacksonTesterIntegrationTests { JacksonTester.initFields(this, JsonMapper.builder().disable(MapperFeature.DEFAULT_VIEW_INCLUSION).build()); ByteArrayResource resource = new ByteArrayResource(JSON.getBytes()); ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) - .read(resource); + .read(resource); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isZero(); } @@ -125,7 +125,7 @@ class JacksonTesterIntegrationTests { JacksonTester.initFields(this, JsonMapper.builder().disable(MapperFeature.DEFAULT_VIEW_INCLUSION).build()); Reader reader = new StringReader(JSON); ObjectContent content = this.jsonWithView.forView(ExampleObjectWithView.TestView.class) - .read(reader); + .read(reader); assertThat(content.getObject().getName()).isEqualTo("Spring"); assertThat(content.getObject().getAge()).isZero(); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java index 67f240ba43..366ba5ae7b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,14 +36,14 @@ class JacksonTesterTests extends AbstractJsonMarshalTesterTests { @Test void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper())) - .withMessageContaining("TestInstance must not be null"); + .withMessageContaining("TestInstance must not be null"); } @Test void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null)) - .withMessageContaining("Marshaller must not be null"); + .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java index 4b915c3500..9de1ab9b7e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -85,7 +85,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT)); } @Test @@ -96,7 +96,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo("different.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo("different.json")); } @Test @@ -107,7 +107,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(DIFFERENT.getBytes())); } @Test @@ -118,7 +118,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenFileIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createFile(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createFile(DIFFERENT))); } @Test @@ -129,7 +129,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createInputStream(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createInputStream(DIFFERENT))); } @Test @@ -140,7 +140,7 @@ class JsonContentAssertTests { @Test void isEqualToWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createResource(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualTo(createResource(DIFFERENT))); } @Test @@ -151,13 +151,13 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenNullActualShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(null)).isEqualToJson(SOURCE)); + .isThrownBy(() -> assertThat(forJson(null)).isEqualToJson(SOURCE)); } @Test void isEqualToJsonWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT)); } @Test @@ -168,7 +168,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json")); } @Test @@ -179,7 +179,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass())); } @Test @@ -190,7 +190,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes())); } @Test @@ -201,7 +201,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenFileIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT))); } @Test @@ -212,7 +212,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT))); } @Test @@ -223,7 +223,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT))); } @Test @@ -234,7 +234,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenStringIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME)); } @Test @@ -245,7 +245,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenResourcePathIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json")); } @Test @@ -256,7 +256,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenResourcePathAndClassIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson("lenient-same.json", getClass())); } @Test @@ -267,7 +267,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenBytesAreNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(LENIENT_SAME.getBytes())); } @Test @@ -278,7 +278,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenFileIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createFile(LENIENT_SAME))); } @Test @@ -289,7 +289,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenInputStreamIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createInputStream(LENIENT_SAME))); } @Test @@ -300,7 +300,7 @@ class JsonContentAssertTests { @Test void isStrictlyEqualToJsonWhenResourceIsNotMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isStrictlyEqualToJson(createResource(LENIENT_SAME))); } @Test @@ -311,7 +311,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenStringIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, JSONCompareMode.LENIENT)); } @Test @@ -322,7 +322,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathIsNotMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", JSONCompareMode.LENIENT)); } @Test @@ -343,8 +343,8 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenBytesAreNotMatchingAndLenientShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), JSONCompareMode.LENIENT)); } @Test @@ -388,7 +388,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenStringIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT, COMPARATOR)); } @Test @@ -399,7 +399,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", COMPARATOR)); } @Test @@ -410,7 +410,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourcePathAndClassAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson("different.json", getClass(), COMPARATOR)); } @Test @@ -421,7 +421,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenBytesAreNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(DIFFERENT.getBytes(), COMPARATOR)); } @Test @@ -432,7 +432,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenFileIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createFile(DIFFERENT), COMPARATOR)); } @Test @@ -443,7 +443,7 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenInputStreamIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createInputStream(DIFFERENT), COMPARATOR)); } @Test @@ -454,13 +454,13 @@ class JsonContentAssertTests { @Test void isEqualToJsonWhenResourceIsNotMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isEqualToJson(createResource(DIFFERENT), COMPARATOR)); } @Test void isNotEqualToWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME)); } @Test @@ -476,7 +476,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo("lenient-same.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo("lenient-same.json")); } @Test @@ -487,7 +487,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(LENIENT_SAME.getBytes())); } @Test @@ -498,7 +498,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenFileIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createFile(LENIENT_SAME))); } @Test @@ -509,7 +509,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createInputStream(LENIENT_SAME))); } @Test @@ -520,7 +520,7 @@ class JsonContentAssertTests { @Test void isNotEqualToWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualTo(createResource(LENIENT_SAME))); } @Test @@ -531,7 +531,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME)); } @Test @@ -547,7 +547,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json")); } @Test @@ -558,7 +558,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", getClass())); } @Test @@ -569,7 +569,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes())); } @Test @@ -580,7 +580,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenFileIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME))); } @Test @@ -591,7 +591,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createInputStream(LENIENT_SAME))); } @Test @@ -602,7 +602,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME))); } @Test @@ -613,7 +613,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenStringIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE)); } @Test @@ -624,7 +624,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenResourcePathIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json")); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json")); } @Test @@ -635,7 +635,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenResourcePathAndClassAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson("source.json", getClass())); } @Test @@ -646,7 +646,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenBytesAreMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes())); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(SOURCE.getBytes())); } @Test @@ -657,7 +657,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenFileIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createFile(SOURCE))); } @Test @@ -668,7 +668,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenInputStreamIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createInputStream(SOURCE))); } @Test @@ -679,7 +679,7 @@ class JsonContentAssertTests { @Test void isNotStrictlyEqualToJsonWhenResourceIsMatchingShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE))); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotStrictlyEqualToJson(createResource(SOURCE))); } @Test @@ -690,7 +690,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenStringIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, JSONCompareMode.LENIENT)); } @Test @@ -712,7 +712,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathAndClassAreMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT)); + .isNotEqualToJson("lenient-same.json", getClass(), JSONCompareMode.LENIENT)); } @Test @@ -745,7 +745,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenInputStreamIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT)); + .isNotEqualToJson(createInputStream(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test @@ -756,7 +756,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourceIsMatchingAndLenientShouldFail() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(forJson(SOURCE)) - .isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT)); + .isNotEqualToJson(createResource(LENIENT_SAME), JSONCompareMode.LENIENT)); } @Test @@ -767,7 +767,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenStringIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME, COMPARATOR)); } @Test @@ -778,7 +778,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourcePathIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson("lenient-same.json", COMPARATOR)); } @Test @@ -800,7 +800,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenBytesAreMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(LENIENT_SAME.getBytes(), COMPARATOR)); } @Test @@ -811,7 +811,7 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenFileIsMatchingAndComparatorShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR)); + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createFile(LENIENT_SAME), COMPARATOR)); } @Test @@ -832,8 +832,8 @@ class JsonContentAssertTests { @Test void isNotEqualToJsonWhenResourceIsMatchingAndComparatorShouldFail() { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - () -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR)); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SOURCE)).isNotEqualToJson(createResource(LENIENT_SAME), COMPARATOR)); } @Test @@ -855,8 +855,8 @@ class JsonContentAssertTests { void hasJsonPathForNotPresent() { String expression = "missing"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPath(expression)) - .withMessageContaining("No JSON path \"" + expression + "\" found"); + .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPath(expression)) + .withMessageContaining("No JSON path \"" + expression + "\" found"); } @Test @@ -878,16 +878,16 @@ class JsonContentAssertTests { void hasJsonPathValueForANullValue() { String expression = "nullname"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) - .withMessageContaining("No value at JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) + .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test void hasJsonPathValueForMissingValue() { String expression = "missing"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) - .withMessageContaining("No value at JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).hasJsonPathValue(expression)) + .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test @@ -899,8 +899,8 @@ class JsonContentAssertTests { void hasJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) - .withMessageContaining("No value at JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) + .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test @@ -912,16 +912,16 @@ class JsonContentAssertTests { void doesNotHaveJsonPathForNull() { String expression = "nullname"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) - .withMessageContaining("Expecting no JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) + .withMessageContaining("Expecting no JSON path \"" + expression + "\""); } @Test void doesNotHaveJsonPathForPresent() { String expression = "valuename"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) - .withMessageContaining("Expecting no JSON path \"" + expression + "\""); + .isThrownBy(() -> assertThat(forJson(NULLS)).doesNotHaveJsonPath(expression)) + .withMessageContaining("Expecting no JSON path \"" + expression + "\""); } @Test @@ -933,25 +933,25 @@ class JsonContentAssertTests { void doesNotHaveJsonPathValueForAnEmptyArray() { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: []"); } @Test void doesNotHaveJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: {}"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + "\" but found: {}"); } @Test void doesNotHaveJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) - .withMessageContaining( - "Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining( + "Expected no value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test @@ -988,17 +988,17 @@ class JsonContentAssertTests { void hasEmptyJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) - .withMessageContaining( - "Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) + .withMessageContaining( + "Expected an empty value at JSON path \"" + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test void hasEmptyJsonPathValueForWhitespace() { String expression = "$.whitespace"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) - .withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) + .withMessageContaining("Expected an empty value at JSON path \"" + expression + "\" but found: ' '"); } @Test @@ -1035,32 +1035,32 @@ class JsonContentAssertTests { void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test void doesNotHaveEmptyJsonPathValueForAnEmptyString() { String expression = "$.emptyString"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: ''"); } @Test void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() { String expression = "$.emptyArray"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: []"); } @Test void doesNotHaveEmptyJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) - .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); + .isThrownBy(() -> assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + expression + "\" but found: {}"); } @Test @@ -1077,8 +1077,8 @@ class JsonContentAssertTests { void hasJsonPathStringValueForNonString() { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) - .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: true"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: true"); } @Test @@ -1090,8 +1090,8 @@ class JsonContentAssertTests { void hasJsonPathNumberValueForNonNumber() { String expression = "$.bool"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) - .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: true"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: true"); } @Test @@ -1103,8 +1103,8 @@ class JsonContentAssertTests { void hasJsonPathBooleanValueForNonBoolean() { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) - .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 5"); } @Test @@ -1121,8 +1121,8 @@ class JsonContentAssertTests { void hasJsonPathArrayValueForNonArray() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) - .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1139,8 +1139,8 @@ class JsonContentAssertTests { void hasJsonPathMapValueForNonMap() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) - .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1172,8 +1172,8 @@ class JsonContentAssertTests { void extractingJsonPathStringValueForWrongType() { String expression = "$.num"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression)) - .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: 5"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + "\" but found: 5"); } @Test @@ -1190,8 +1190,8 @@ class JsonContentAssertTests { void extractingJsonPathNumberValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression)) - .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1208,8 +1208,8 @@ class JsonContentAssertTests { void extractingJsonPathBooleanValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression)) - .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1231,8 +1231,8 @@ class JsonContentAssertTests { void extractingJsonPathArrayValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) - .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); } @Test @@ -1254,8 +1254,8 @@ class JsonContentAssertTests { void extractingJsonPathMapValueForWrongType() { String expression = "$.str"; assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) - .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); + .isThrownBy(() -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java index e6338feba3..1c3b27265e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -38,23 +38,23 @@ class JsonContentTests { @Test void createWhenResourceLoadClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new JsonContent(null, TYPE, JSON, Configuration.defaultConfiguration())) - .withMessageContaining("ResourceLoadClass must not be null"); + .isThrownBy(() -> new JsonContent(null, TYPE, JSON, Configuration.defaultConfiguration())) + .withMessageContaining("ResourceLoadClass must not be null"); } @Test void createWhenJsonIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JsonContent(getClass(), TYPE, null, Configuration.defaultConfiguration())) - .withMessageContaining("JSON must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new JsonContent(getClass(), TYPE, null, Configuration.defaultConfiguration())) + .withMessageContaining("JSON must not be null"); } @Test void createWhenConfigurationIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new JsonContent(getClass(), TYPE, JSON, null)) - .withMessageContaining("Configuration must not be null"); + .isThrownBy(() -> new JsonContent(getClass(), TYPE, JSON, null)) + .withMessageContaining("Configuration must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java index 99dcd9ca51..524196cea3 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,14 +37,14 @@ class JsonbTesterTests extends AbstractJsonMarshalTesterTests { @Test void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create())) - .withMessageContaining("TestInstance must not be null"); + .withMessageContaining("TestInstance must not be null"); } @Test void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) - .withMessageContaining("Marshaller must not be null"); + .isThrownBy(() -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java index 6fe815d3b4..9c059f1083 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentAssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class ObjectContentAssertTests { @Test void isEqualToWhenObjectsAreDifferentShouldFail() { assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> assertThat(forObject(SOURCE)).isEqualTo(DIFFERENT)); + .isThrownBy(() -> assertThat(forObject(SOURCE)).isEqualTo(DIFFERENT)); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java index 9d183335f8..8d83219da6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class ObjectContentTests { @Test void createWhenObjectIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectContent(TYPE, null)) - .withMessageContaining("Object must not be null"); + .withMessageContaining("Object must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java index b94032f6a5..a2874788f7 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -80,7 +80,7 @@ class DefinitionsParserTests { MockDefinition fieldDefinition = getMockDefinition(1); assertThat(fieldDefinition.getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); QualifierDefinition qualifier = QualifierDefinition - .forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); + .forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); } @@ -94,7 +94,7 @@ class DefinitionsParserTests { @Test void parseMockBeanMissingClassToMock() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class)) - .withMessageContaining("Unable to deduce type to mock"); + .withMessageContaining("Unable to deduce type to mock"); } @Test @@ -108,7 +108,7 @@ class DefinitionsParserTests { @Test void parseMockBeanMultipleClassesWithName() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMultipleClassesWithName.class)) - .withMessageContaining("The name attribute can only be used when mocking a single class"); + .withMessageContaining("The name attribute can only be used when mocking a single class"); } @Test @@ -146,7 +146,7 @@ class DefinitionsParserTests { assertThat(classDefinition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); SpyDefinition fieldDefinition = getSpyDefinition(1); QualifierDefinition qualifier = QualifierDefinition - .forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); + .forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); assertThat(fieldDefinition.getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); } @@ -161,7 +161,7 @@ class DefinitionsParserTests { @Test void parseSpyBeanMissingClassToMock() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class)) - .withMessageContaining("Unable to deduce type to spy"); + .withMessageContaining("Unable to deduce type to spy"); } @Test @@ -175,7 +175,7 @@ class DefinitionsParserTests { @Test void parseSpyBeanMultipleClassesWithName() { assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class)) - .withMessageContaining("The name attribute can only be used when spying a single class"); + .withMessageContaining("The name attribute can only be used when spying a single class"); } private MockDefinition getMockDefinition(int index) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java index f610873ad8..fca0b7799d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java @@ -54,7 +54,7 @@ class MockBeanContextCachingTests { @SuppressWarnings("unchecked") void clearCache() { Map contexts = (Map) ReflectionTestUtils - .getField(this.contextCache, "contextMap"); + .getField(this.contextCache, "contextMap"); for (ApplicationContext context : contexts.values()) { if (context instanceof ConfigurableApplicationContext configurableContext) { configurableContext.close(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java index 10bf8046d7..51afa721e6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java @@ -41,8 +41,8 @@ class MockDefinitionTests { @Test void classToMockMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null)) - .withMessageContaining("TypeToMock must not be null"); + .isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null)) + .withMessageContaining("TypeToMock must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java index 36873c22b6..4e6a066063 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -58,8 +58,8 @@ class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleBeans.class); assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace but found [example1, example2]"); + .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace but found [example1, example2]"); } @Test @@ -68,8 +68,8 @@ class MockitoPostProcessorTests { MockitoPostProcessor.register(context); context.register(MultipleQualifiedBeans.class); assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace but found [example1, example3]"); + .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace but found [example1, example3]"); } @Test @@ -94,7 +94,7 @@ class MockitoPostProcessorTests { assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isTrue(); assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isTrue(); assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()) - .isFalse(); + .isFalse(); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java index 7c66530168..0f05739d8f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -88,7 +88,7 @@ class MockitoTestExecutionListenerTests { TestContext mockTestContext = mockTestContext(instance); given(mockTestContext.getApplicationContext()).willReturn(this.applicationContext); given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) - .willReturn(Boolean.TRUE); + .willReturn(Boolean.TRUE); this.listener.beforeTestMethod(mockTestContext); then(this.postProcessor).should().inject(this.fieldCaptor.capture(), eq(instance), any(MockDefinition.class)); assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean"); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java index bc4356abc5..70a59acf68 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java @@ -65,14 +65,14 @@ class QualifierDefinitionTests { @Test void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() { QualifierDefinition definition = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier")); assertThat(definition).isNull(); } @Test void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() { QualifierDefinition definition = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); assertThat(definition).isNotNull(); } @@ -97,26 +97,29 @@ class QualifierDefinitionTests { @Test void hashCodeAndEqualsShouldWorkOnDifferentClasses() { QualifierDefinition directQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); QualifierDefinition directQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier")); + .forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier")); QualifierDefinition differentDirectQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); QualifierDefinition differentDirectQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); + .forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); QualifierDefinition customQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier")); + .forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier")); QualifierDefinition customQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier")); + .forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier")); assertThat(directQualifier1).hasSameHashCodeAs(directQualifier2); assertThat(differentDirectQualifier1).hasSameHashCodeAs(differentDirectQualifier2); assertThat(customQualifier1).hasSameHashCodeAs(customQualifier2); - assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1).isEqualTo(differentDirectQualifier2) - .isNotEqualTo(directQualifier2); - assertThat(directQualifier1).isEqualTo(directQualifier1).isEqualTo(directQualifier2) - .isNotEqualTo(differentDirectQualifier1); - assertThat(customQualifier1).isEqualTo(customQualifier1).isEqualTo(customQualifier2) - .isNotEqualTo(differentDirectQualifier1); + assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1) + .isEqualTo(differentDirectQualifier2) + .isNotEqualTo(directQualifier2); + assertThat(directQualifier1).isEqualTo(directQualifier1) + .isEqualTo(directQualifier2) + .isNotEqualTo(differentDirectQualifier1); + assertThat(customQualifier1).isEqualTo(customQualifier1) + .isEqualTo(customQualifier2) + .isNotEqualTo(differentDirectQualifier1); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java index 84392334c5..335d3f104b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java @@ -42,7 +42,7 @@ class SpyDefinitionTests { @Test void classToSpyMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new SpyDefinition(null, null, null, true, null)) - .withMessageContaining("TypeToSpy must not be null"); + .withMessageContaining("TypeToSpy must not be null"); } @Test @@ -81,14 +81,14 @@ class SpyDefinitionTests { void createSpyWhenNullInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(null)) - .withMessageContaining("Instance must not be null"); + .withMessageContaining("Instance must not be null"); } @Test void createSpyWhenWrongInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null))) - .withMessageContaining("must be an instance of"); + .withMessageContaining("must be an instance of"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java index ed239713fc..b4ac8ac6b3 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/util/TestPropertyValuesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -103,7 +103,7 @@ class TestPropertyValuesTests { TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ"); assertThat(this.environment.getPropertySources() - .contains("test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isTrue(); + .contains("test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isTrue(); } @Test @@ -118,7 +118,7 @@ class TestPropertyValuesTests { TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP, "other"); TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT, "other"); assertThat(this.environment.getPropertySources().get("other")) - .isInstanceOf(SystemEnvironmentPropertySource.class); + .isInstanceOf(SystemEnvironmentPropertySource.class); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ"); assertThat(this.environment.getProperty("hello.world")).isNull(); } @@ -133,8 +133,10 @@ class TestPropertyValuesTests { @Test void andShouldChainAndAddSingleKeyValue() { - TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing").applyTo(this.environment, - Type.MAP); + TestPropertyValues.of("foo.bar=baz") + .and("hello.world=hi") + .and("bling.blah=bing") + .applyTo(this.environment, Type.MAP); assertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz"); assertThat(this.environment.getProperty("hello.world")).isEqualTo("hi"); assertThat(this.environment.getProperty("bling.blah")).isEqualTo("bing"); @@ -151,7 +153,7 @@ class TestPropertyValuesTests { @Test void applyToSystemPropertiesWithRunnableShouldSetSystemProperties() { TestPropertyValues.of("foo=bar") - .applyToSystemProperties(() -> assertThat(System.getProperty("foo")).isEqualTo("bar")); + .applyToSystemProperties(() -> assertThat(System.getProperty("foo")).isEqualTo("bar")); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java index 685057e8f9..e3ee27b5e3 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessorTests.java @@ -115,7 +115,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { // is null in app properties addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8080"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8080"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEmpty(); @@ -125,7 +125,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDifferentInProduction() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -135,7 +135,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenTestServerPortIsZeroAndManagementPortMinusOne() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("-1"); @@ -145,7 +145,7 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenTestServerPortIsZeroAndManagementPortIsAnInteger() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -155,10 +155,10 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenManagementServerPortPlaceholderPresentShouldResolvePlaceholder() { addTestPropertySource("0", null); MapPropertySource testPropertySource = (MapPropertySource) this.propertySources - .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); testPropertySource.getSource().put("port", "9090"); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); this.postProcessor.postProcessEnvironment(this.environment, null); assertThat(this.environment.getProperty("server.port")).isEqualTo("0"); assertThat(this.environment.getProperty("management.server.port")).isEqualTo("0"); @@ -168,17 +168,17 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { void postProcessWhenManagementServerPortPlaceholderAbsentShouldFail() { addTestPropertySource("0", null); this.propertySources - .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); + .addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "${port}"))); assertThatIllegalArgumentException() - .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) - .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); + .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) + .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); } @Test void postProcessWhenServerPortPlaceholderPresentShouldResolvePlaceholder() { addTestPropertySource("0", null); MapPropertySource testPropertySource = (MapPropertySource) this.propertySources - .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .get(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); testPropertySource.getSource().put("port", "8080"); Map source = new HashMap<>(); source.put("server.port", "${port}"); @@ -197,8 +197,8 @@ class SpringBootTestRandomPortEnvironmentPostProcessorTests { source.put("management.server.port", "9090"); this.propertySources.addLast(new MapPropertySource("other", source)); assertThatIllegalArgumentException() - .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) - .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); + .isThrownBy(() -> this.postProcessor.postProcessEnvironment(this.environment, null)) + .withMessage("Could not resolve placeholder 'port' in value \"${port}\""); } private void addTestPropertySource(String serverPort, String managementPort) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java index 85d0e57b84..48b6313837 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,21 +43,21 @@ class LocalHostUriTemplateHandlerTests { @Test void createWhenEnvironmentIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostUriTemplateHandler(null)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test void createWhenSchemeIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) - .withMessageContaining("Scheme must not be null"); + .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) + .withMessageContaining("Scheme must not be null"); } @Test void createWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null)) - .withMessageContaining("Handler must not be null"); + .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null)) + .withMessageContaining("Handler must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java index 32824c2f67..b92a359f60 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,22 +53,22 @@ class MockServerRestTemplateCustomizerTests { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer(); customizer.customize(new RestTemplate()); assertThat(customizer.getServer()).extracting("expectationManager") - .isInstanceOf(SimpleRequestExpectationManager.class); + .isInstanceOf(SimpleRequestExpectationManager.class); } @Test void createWhenExpectationManagerClassIsNullShouldThrowException() { Class expectationManager = null; assertThatIllegalArgumentException().isThrownBy(() -> new MockServerRestTemplateCustomizer(expectationManager)) - .withMessageContaining("ExpectationManager must not be null"); + .withMessageContaining("ExpectationManager must not be null"); } @Test void createWhenExpectationManagerSupplierIsNullShouldThrowException() { Supplier expectationManagerSupplier = null; assertThatIllegalArgumentException() - .isThrownBy(() -> new MockServerRestTemplateCustomizer(expectationManagerSupplier)) - .withMessageContaining("ExpectationManagerSupplier must not be null"); + .isThrownBy(() -> new MockServerRestTemplateCustomizer(expectationManagerSupplier)) + .withMessageContaining("ExpectationManagerSupplier must not be null"); } @Test @@ -77,7 +77,7 @@ class MockServerRestTemplateCustomizerTests { UnorderedRequestExpectationManager.class); customizer.customize(new RestTemplate()); assertThat(customizer.getServer()).extracting("expectationManager") - .isInstanceOf(UnorderedRequestExpectationManager.class); + .isInstanceOf(UnorderedRequestExpectationManager.class); } @Test @@ -86,7 +86,7 @@ class MockServerRestTemplateCustomizerTests { UnorderedRequestExpectationManager::new); customizer.customize(new RestTemplate()); assertThat(customizer.getServer()).extracting("expectationManager") - .isInstanceOf(UnorderedRequestExpectationManager.class); + .isInstanceOf(UnorderedRequestExpectationManager.class); } @Test @@ -95,7 +95,7 @@ class MockServerRestTemplateCustomizerTests { UnorderedRequestExpectationManager.class); customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(customizer.getServer()).extracting("expectationManager") - .isInstanceOf(RootUriRequestExpectationManager.class); + .isInstanceOf(RootUriRequestExpectationManager.class); } @Test @@ -103,7 +103,7 @@ class MockServerRestTemplateCustomizerTests { this.customizer.setDetectRootUri(false); this.customizer.customize(new RestTemplateBuilder().rootUri("https://example.com").build()); assertThat(this.customizer.getServer()).extracting("expectationManager") - .isInstanceOf(SimpleRequestExpectationManager.class); + .isInstanceOf(SimpleRequestExpectationManager.class); } @@ -118,8 +118,8 @@ class MockServerRestTemplateCustomizerTests { @Test void getServerWhenNoServersAreBoundShouldThrowException() { assertThatIllegalStateException().isThrownBy(this.customizer::getServer) - .withMessageContaining("Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); + .withMessageContaining("Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); } @Test @@ -127,8 +127,8 @@ class MockServerRestTemplateCustomizerTests { this.customizer.customize(new RestTemplate()); this.customizer.customize(new RestTemplate()); assertThatIllegalStateException().isThrownBy(this.customizer::getServer) - .withMessageContaining("Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); + .withMessageContaining("Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java index 2fb9be5158..94d4519940 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/NoTestRestTemplateBeanChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,8 @@ class NoTestRestTemplateBeanChecker implements ImportSelector, BeanFactoryAware @Override public void setBeanFactory(BeanFactory beanFactory) { assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, - TestRestTemplate.class)).isEmpty(); + TestRestTemplate.class)) + .isEmpty(); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java index 20c33bfdf8..55808bebb0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,13 +71,13 @@ class RootUriRequestExpectationManagerTests { @Test void createWhenRootUriIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(null, this.delegate)) - .withMessageContaining("RootUri must not be null"); + .withMessageContaining("RootUri must not be null"); } @Test void createWhenExpectationManagerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null)) - .withMessageContaining("ExpectationManager must not be null"); + .withMessageContaining("ExpectationManager must not be null"); } @Test @@ -112,9 +112,9 @@ class RootUriRequestExpectationManagerTests { ClientHttpRequest request = mock(ClientHttpRequest.class); given(request.getURI()).willReturn(new URI(this.uri + "/hello")); given(this.delegate.validateRequest(any(ClientHttpRequest.class))) - .willThrow(new AssertionError("Request URI expected: was:")); + .willThrow(new AssertionError("Request URI expected: was:")); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.manager.validateRequest(request)) - .withMessageContaining("Request URI expected:"); + .withMessageContaining("Request URI expected:"); } @Test @@ -168,8 +168,8 @@ class RootUriRequestExpectationManagerTests { MockRestServiceServer server = RootUriRequestExpectationManager.bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> restTemplate.getForEntity("https://spring.io/hello", String.class)) - .withMessageContaining("expected: but was:"); + .isThrownBy(() -> restTemplate.getForEntity("https://spring.io/hello", String.class)) + .withMessageContaining("expected: but was:"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java index a598ef0cb4..6c5d5fc8d0 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,17 +42,18 @@ class TestRestTemplateContextCustomizerTests { @Test void whenContextIsNotABeanDefinitionRegistryTestRestTemplateIsRegistered() { new ApplicationContextRunner(TestApplicationContext::new) - .withInitializer(this::applyTestRestTemplateContextCustomizer) - .run((context) -> assertThat(context).hasSingleBean(TestRestTemplate.class)); + .withInitializer(this::applyTestRestTemplateContextCustomizer) + .run((context) -> assertThat(context).hasSingleBean(TestRestTemplate.class)); } @Test void whenUsingAotGeneratedArtifactsTestRestTemplateIsNotRegistered() { new ApplicationContextRunner().withSystemProperties("spring.aot.enabled:true") - .withInitializer(this::applyTestRestTemplateContextCustomizer).run((context) -> { - assertThat(context).doesNotHaveBean(TestRestTemplateRegistrar.class); - assertThat(context).doesNotHaveBean(TestRestTemplate.class); - }); + .withInitializer(this::applyTestRestTemplateContextCustomizer) + .run((context) -> { + assertThat(context).doesNotHaveBean(TestRestTemplateRegistrar.class); + assertThat(context).doesNotHaveBean(TestRestTemplate.class); + }); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java index 5085f9be0d..53cb7b8366 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java @@ -81,7 +81,7 @@ class TestRestTemplateTests { void simple() { // The Apache client is on the classpath so we get the fully-fledged factory assertThat(new TestRestTemplate().getRestTemplate().getRequestFactory()) - .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); + .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test @@ -89,7 +89,7 @@ class TestRestTemplateTests { RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(OkHttp3ClientHttpRequestFactory.class); TestRestTemplate testRestTemplate = new TestRestTemplate(builder); assertThat(testRestTemplate.getRestTemplate().getRequestFactory()) - .isInstanceOf(OkHttp3ClientHttpRequestFactory.class); + .isInstanceOf(OkHttp3ClientHttpRequestFactory.class); } @Test @@ -133,7 +133,8 @@ class TestRestTemplateTests { void options() { TestRestTemplate template = new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS); CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template - .getRestTemplate().getRequestFactory(); + .getRestTemplate() + .getRequestFactory(); RequestConfig config = factory.createRequestConfig(); assertThat(config.isRedirectsEnabled()).isTrue(); } @@ -154,7 +155,8 @@ class TestRestTemplateTests { method.getParameterTypes()); assertThat(equivalent).as("Method %s not found", method).isNotNull(); assertThat(Modifier.isPublic(equivalent.getModifiers())) - .as("Method %s should have been public", equivalent).isTrue(); + .as("Method %s should have been public", equivalent) + .isTrue(); try { equivalent.invoke(restTemplate, mockArguments(method.getParameterTypes())); } @@ -269,14 +271,14 @@ class TestRestTemplateTests { @Test void exchangeWithRequestEntityAndClassHandlesRelativeUris() throws IOException { verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate - .exchange(new RequestEntity(HttpMethod.GET, relativeUri), String.class)); + .exchange(new RequestEntity(HttpMethod.GET, relativeUri), String.class)); } @Test void exchangeWithRequestEntityAndParameterizedTypeReferenceHandlesRelativeUris() throws IOException { - verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate.exchange( - new RequestEntity(HttpMethod.GET, relativeUri), new ParameterizedTypeReference() { - })); + verifyRelativeUriHandling((testRestTemplate, relativeUri) -> testRestTemplate + .exchange(new RequestEntity(HttpMethod.GET, relativeUri), new ParameterizedTypeReference() { + })); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java index 46c461341a..74ba020c6d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class LocalHostWebClientTests { @Test void createWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebClient(null)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java index 22e0d1d6e3..b9634ddc60 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,20 +64,20 @@ class LocalHostWebConnectionHtmlUnitDriverTests { @Test void createWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true)) - .withMessageContaining("Environment must not be null"); + .withMessageContaining("Environment must not be null"); } @Test void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME)) + .withMessageContaining("Environment must not be null"); } @Test @@ -86,8 +86,8 @@ class LocalHostWebConnectionHtmlUnitDriverTests { given(capabilities.getBrowserName()).willReturn("htmlunit"); given(capabilities.getBrowserVersion()).willReturn("chrome"); assertThatIllegalArgumentException() - .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities)) + .withMessageContaining("Environment must not be null"); } @Test @@ -95,8 +95,8 @@ class LocalHostWebConnectionHtmlUnitDriverTests { MockEnvironment environment = new MockEnvironment(); LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); driver.get("/test"); - then(this.webClient).should().getPage(any(TopLevelWindow.class), - requestToUrl(new URL("http://localhost:8080/test"))); + then(this.webClient).should() + .getPage(any(TopLevelWindow.class), requestToUrl(new URL("http://localhost:8080/test"))); } @Test @@ -105,8 +105,8 @@ class LocalHostWebConnectionHtmlUnitDriverTests { environment.setProperty("local.server.port", "8181"); LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment); driver.get("/test"); - then(this.webClient).should().getPage(any(TopLevelWindow.class), - requestToUrl(new URL("http://localhost:8181/test"))); + then(this.webClient).should() + .getPage(any(TopLevelWindow.class), requestToUrl(new URL("http://localhost:8181/test"))); } private WebRequest requestToUrl(URL url) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java index 2c8a28db62..6caa9d7431 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/NoWebTestClientBeanChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,8 @@ class NoWebTestClientBeanChecker implements ImportSelector, BeanFactoryAware { @Override public void setBeanFactory(BeanFactory beanFactory) { assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, - WebTestClient.class)).isEmpty(); + WebTestClient.class)) + .isEmpty(); } @Override diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerTests.java index d14dd54e18..1d97fb8107 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,17 +43,18 @@ class WebTestClientContextCustomizerTests { @Test void whenContextIsNotABeanDefinitionRegistryWebTestClientIsRegistered() { new ApplicationContextRunner(TestApplicationContext::new) - .withInitializer(this::applyWebTestClientContextCustomizer) - .run((context) -> assertThat(context).hasSingleBean(WebTestClient.class)); + .withInitializer(this::applyWebTestClientContextCustomizer) + .run((context) -> assertThat(context).hasSingleBean(WebTestClient.class)); } @Test void whenUsingAotGeneratedArtifactsWebTestClientIsNotRegistered() { new ApplicationContextRunner().withSystemProperties("spring.aot.enabled:true") - .withInitializer(this::applyWebTestClientContextCustomizer).run((context) -> { - assertThat(context).doesNotHaveBean(WebTestClientRegistrar.class); - assertThat(context).doesNotHaveBean(WebTestClient.class); - }); + .withInitializer(this::applyWebTestClientContextCustomizer) + .run((context) -> { + assertThat(context).doesNotHaveBean(WebTestClientRegistrar.class); + assertThat(context).doesNotHaveBean(WebTestClient.class); + }); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java index 64b1b2de59..2137997890 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,25 +84,25 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { private void addConditionPropertyGenerators(List generators) { String annotationPackage = "org.springframework.boot.autoconfigure.condition"; generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnClass") - .withAnnotation(new OnClassConditionValueExtractor())); + .withAnnotation(new OnClassConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnBean") - .withAnnotation(new OnBeanConditionValueExtractor())); + .withAnnotation(new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnSingleCandidate") - .withAnnotation(new OnBeanConditionValueExtractor())); + .withAnnotation(new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnWebApplication") - .withAnnotation(ValueExtractor.allFrom("type"))); + .withAnnotation(ValueExtractor.allFrom("type"))); } private void addAutoConfigurePropertyGenerators(List generators) { String annotationPackage = "org.springframework.boot.autoconfigure"; generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureBefore", true) - .withAnnotation(ValueExtractor.allFrom("value", "name")) - .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); + .withAnnotation(ValueExtractor.allFrom("value", "name")) + .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureAfter", true) - .withAnnotation(ValueExtractor.allFrom("value", "name")) - .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); + .withAnnotation(ValueExtractor.allFrom("value", "name")) + .withAnnotation("AutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureOrder") - .withAnnotation(ValueExtractor.allFrom("value"))); + .withAnnotation(ValueExtractor.allFrom("value"))); } @Override @@ -207,7 +207,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { Object value = annotationValue.getValue(); if (value instanceof List) { return ((List) value).stream() - .map((annotation) -> extractValue(annotation.getValue())); + .map((annotation) -> extractValue(annotation.getValue())); } return Stream.of(extractValue(value)); } @@ -248,7 +248,7 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { public List getValues(AnnotationMirror annotation) { Map attributes = new LinkedHashMap<>(); annotation.getElementValues() - .forEach((key, value) -> attributes.put(key.getSimpleName().toString(), value)); + .forEach((key, value) -> attributes.put(key.getSimpleName().toString(), value)); if (attributes.containsKey("name")) { return Collections.emptyList(); } @@ -274,8 +274,9 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } private int compare(Object o1, Object o2) { - return Comparator.comparing(this::isSpringClass).thenComparing(String.CASE_INSENSITIVE_ORDER) - .compare(o1.toString(), o2.toString()); + return Comparator.comparing(this::isSpringClass) + .thenComparing(String.CASE_INSENSITIVE_ORDER) + .compare(o1.toString(), o2.toString()); } private boolean isSpringClass(String type) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java index 4985ef6aef..e660563f71 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,9 +47,9 @@ class AutoConfigureAnnotationProcessorTests { "java.io.InputStream,org.springframework.boot.autoconfigureprocessor." + "TestClassConfiguration$Nested,org.springframework.foo"); assertThat(properties) - .containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration"); + .containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration"); assertThat(properties) - .containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration$Nested"); + .containsKey("org.springframework.boot.autoconfigureprocessor.TestClassConfiguration$Nested"); assertThat(properties).containsEntry( "org.springframework.boot.autoconfigureprocessor.TestClassConfiguration.ConditionalOnBean", "java.io.OutputStream"); @@ -156,7 +156,7 @@ class AutoConfigureAnnotationProcessorTests { TestCompiler compiler = TestCompiler.forSystem().withProcessors(processor).withSources(sourceFile); compiler.compile((compiled) -> { InputStream propertiesFile = compiled.getClassLoader() - .getResourceAsStream(AutoConfigureAnnotationProcessor.PROPERTIES_PATH); + .getResourceAsStream(AutoConfigureAnnotationProcessor.PROPERTIES_PATH); consumer.accept(propertiesFile); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java index 0214f8f74e..35bf6ce3c1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/test/java/org/springframework/boot/autoconfigureprocessor/TestAutoConfigureAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,21 +45,21 @@ public class TestAutoConfigureAnnotationProcessor extends AutoConfigureAnnotatio List generators = new ArrayList<>(); String annotationPackage = "org.springframework.boot.autoconfigureprocessor"; generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnClass") - .withAnnotation("TestConditionalOnClass", new OnClassConditionValueExtractor())); + .withAnnotation("TestConditionalOnClass", new OnClassConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnBean") - .withAnnotation("TestConditionalOnBean", new OnBeanConditionValueExtractor())); + .withAnnotation("TestConditionalOnBean", new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnSingleCandidate") - .withAnnotation("TestConditionalOnSingleCandidate", new OnBeanConditionValueExtractor())); + .withAnnotation("TestConditionalOnSingleCandidate", new OnBeanConditionValueExtractor())); generators.add(PropertyGenerator.of(annotationPackage, "ConditionalOnWebApplication") - .withAnnotation("TestConditionalOnWebApplication", ValueExtractor.allFrom("type"))); + .withAnnotation("TestConditionalOnWebApplication", ValueExtractor.allFrom("type"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureBefore", true) - .withAnnotation("TestAutoConfigureBefore", ValueExtractor.allFrom("value", "name")) - .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); + .withAnnotation("TestAutoConfigureBefore", ValueExtractor.allFrom("value", "name")) + .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("before", "beforeName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureAfter", true) - .withAnnotation("TestAutoConfigureAfter", ValueExtractor.allFrom("value", "name")) - .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); + .withAnnotation("TestAutoConfigureAfter", ValueExtractor.allFrom("value", "name")) + .withAnnotation("TestAutoConfiguration", ValueExtractor.allFrom("after", "afterName"))); generators.add(PropertyGenerator.of(annotationPackage, "AutoConfigureOrder") - .withAnnotation("TestAutoConfigureOrder", ValueExtractor.allFrom("value"))); + .withAnnotation("TestAutoConfigureOrder", ValueExtractor.allFrom("value"))); return generators; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java index d67b0000da..e649586e18 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpack.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -62,7 +62,7 @@ class BuilderBuildpack implements Buildpack { static Buildpack resolve(BuildpackResolverContext context, BuildpackReference reference) { boolean unambiguous = reference.hasPrefix(PREFIX); BuilderReference builderReference = BuilderReference - .of(unambiguous ? reference.getSubReference(PREFIX) : reference.toString()); + .of(unambiguous ? reference.getSubReference(PREFIX) : reference.toString()); BuildpackMetadata buildpackMetadata = findBuildpackMetadata(context, builderReference); if (unambiguous) { Assert.isTrue(buildpackMetadata != null, () -> "Buildpack '" + reference + "' not found in builder"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java index 1816b0d987..3b269c0421 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -118,8 +118,9 @@ final class BuildpackLayersMetadata extends MappedObject { private static Buildpacks fromJson(JsonNode node) { Buildpacks buildpacks = new Buildpacks(); - node.fields().forEachRemaining((field) -> buildpacks.addBuildpackVersions(field.getKey(), - BuildpackVersions.fromJson(field.getValue()))); + node.fields() + .forEachRemaining((field) -> buildpacks.addBuildpackVersions(field.getKey(), + BuildpackVersions.fromJson(field.getValue()))); return buildpacks; } @@ -139,8 +140,9 @@ final class BuildpackLayersMetadata extends MappedObject { private static BuildpackVersions fromJson(JsonNode node) { BuildpackVersions versions = new BuildpackVersions(); - node.fields().forEachRemaining((field) -> versions.addBuildpackVersion(field.getKey(), - BuildpackLayerDetails.fromJson(field.getValue()))); + node.fields() + .forEachRemaining((field) -> versions.addBuildpackVersion(field.getKey(), + BuildpackLayerDetails.fromJson(field.getValue()))); return versions; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java index 8220e2294f..a798b226e6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ final class ImageBuildpack implements Buildpack { private boolean buildpackExistsInBuilder(BuildpackResolverContext context, List imageLayers) { BuildpackLayerDetails buildpackLayerDetails = context.getBuildpackLayersMetadata() - .getBuildpack(this.coordinates.getId(), this.coordinates.getVersion()); + .getBuildpack(this.coordinates.getId(), this.coordinates.getVersion()); String layerDiffId = (buildpackLayerDetails != null) ? buildpackLayerDetails.getLayerDiffId() : null; return (layerDiffId != null) && imageLayers.stream().map(LayerId::toString).anyMatch(layerDiffId::equals); } @@ -98,7 +98,7 @@ final class ImageBuildpack implements Buildpack { boolean unambiguous = reference.hasPrefix(PREFIX); try { ImageReference imageReference = ImageReference - .of((unambiguous) ? reference.getSubReference(PREFIX) : reference.toString()); + .of((unambiguous) ? reference.getSubReference(PREFIX) : reference.toString()); return new ImageBuildpack(context, imageReference); } catch (IllegalArgumentException ex) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java index b787880b4a..b31cacf0e3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -239,8 +239,8 @@ class Lifecycle implements Closeable { } try { TarArchive applicationContent = this.request.getApplicationContent(this.builder.getBuildOwner()); - return this.docker.container().create(config, - ContainerContent.of(applicationContent, Directory.APPLICATION)); + return this.docker.container() + .create(config, ContainerContent.of(applicationContent, Directory.APPLICATION)); } finally { this.applicationVolumePopulated = true; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java index 375879263f..3db3f48f66 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/LifecycleVersion.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -28,7 +28,8 @@ import org.springframework.util.Assert; class LifecycleVersion implements Comparable { private static final Comparator COMPARATOR = Comparator.comparingInt(LifecycleVersion::getMajor) - .thenComparingInt(LifecycleVersion::getMinor).thenComparing(LifecycleVersion::getPatch); + .thenComparingInt(LifecycleVersion::getMinor) + .thenComparing(LifecycleVersion::getPatch); private final int major; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java index 6ebdfb8fa7..6a27db1059 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -339,7 +339,7 @@ public class DockerApi { URI createUri = buildUrl("/containers/create"); try (Response response = http().post(createUri, "application/json", config::writeTo)) { return ContainerReference - .of(SharedObjectMapper.get().readTree(response.getContent()).at("/Id").asText()); + .of(SharedObjectMapper.get().readTree(response.getContent()).at("/Id").asText()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java index dce9126235..ee1ab5cae7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageArchive.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,10 +56,10 @@ import org.springframework.util.Assert; public class ImageArchive implements TarArchive { private static final Instant WINDOWS_EPOCH_PLUS_SECOND = OffsetDateTime.of(1980, 1, 1, 0, 0, 1, 0, ZoneOffset.UTC) - .toInstant(); + .toInstant(); private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_ZONED_DATE_TIME - .withZone(ZoneOffset.UTC); + .withZone(ZoneOffset.UTC); private static final String EMPTY_LAYER_NAME_PREFIX = "blank_"; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java index c4ebb66520..c843097d10 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Regex.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -66,7 +66,7 @@ final class Regex implements CharSequence { static final Pattern TAG = Regex.of("^[\\w][\\w.-]{0,127}").compile(); static final Pattern DIGEST = Regex.of("^[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[A-Fa-f0-9]]{32,}") - .compile(); + .compile(); private final String value; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java index 95601854df..1afb601232 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionTests.java @@ -35,19 +35,19 @@ class ApiVersionTests { @Test void parseWhenVersionIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ApiVersion.parse(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void parseWhenVersionIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ApiVersion.parse("")) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void parseWhenVersionDoesNotMatchPatternThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ApiVersion.parse("bad")) - .withMessage("Malformed version number 'bad'"); + .withMessage("Malformed version number 'bad'"); } @Test @@ -65,8 +65,8 @@ class ApiVersionTests { @Test void assertSupportsWhenDoesNotSupportThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ApiVersion.parse("1.2").assertSupports(ApiVersion.parse("1.3"))) - .withMessage("Detected platform API version '1.3' does not match supported version '1.2'"); + .isThrownBy(() -> ApiVersion.parse("1.2").assertSupports(ApiVersion.parse("1.3"))) + .withMessage("Detected platform API version '1.3' does not match supported version '1.2'"); } @Test @@ -129,7 +129,7 @@ class ApiVersionTests { private boolean supportsAny(String v1, String... others) { return ApiVersion.parse(v1) - .supportsAny(Arrays.stream(others).map(ApiVersion::parse).toArray(ApiVersion[]::new)); + .supportsAny(Arrays.stream(others).map(ApiVersion::parse).toArray(ApiVersion[]::new)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java index 96640e8299..1028f49ea3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ApiVersionsTests.java @@ -63,8 +63,8 @@ class ApiVersionsTests { @Test void findLatestWhenNoneSupportedThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ApiVersions.parse("1.1", "1.2").findLatestSupported("1.3", "1.4")).withMessage( - "Detected platform API versions '1.3,1.4' are not included in supported versions '1.1,1.2'"); + .isThrownBy(() -> ApiVersions.parse("1.1", "1.2").findLatestSupported("1.3", "1.4")) + .withMessage("Detected platform API versions '1.3,1.4' are not included in supported versions '1.1,1.2'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java index dd17afe4d1..c16232cfa9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildOwnerTests.java @@ -47,7 +47,7 @@ class BuildOwnerTests { @Test void fromEnvWhenEnvIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildOwner.fromEnv(null)) - .withMessage("Env must not be null"); + .withMessage("Env must not be null"); } @Test @@ -55,7 +55,7 @@ class BuildOwnerTests { Map env = new LinkedHashMap<>(); env.put("CNB_GROUP_ID", "456"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Missing 'CNB_USER_ID' value from the builder environment '" + env + "'"); + .withMessage("Missing 'CNB_USER_ID' value from the builder environment '" + env + "'"); } @Test @@ -63,7 +63,7 @@ class BuildOwnerTests { Map env = new LinkedHashMap<>(); env.put("CNB_USER_ID", "123"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Missing 'CNB_GROUP_ID' value from the builder environment '" + env + "'"); + .withMessage("Missing 'CNB_GROUP_ID' value from the builder environment '" + env + "'"); } @Test @@ -72,7 +72,7 @@ class BuildOwnerTests { env.put("CNB_USER_ID", "nope"); env.put("CNB_GROUP_ID", "456"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Malformed 'CNB_USER_ID' value 'nope' in the builder environment '" + env + "'"); + .withMessage("Malformed 'CNB_USER_ID' value 'nope' in the builder environment '" + env + "'"); } @Test @@ -81,7 +81,7 @@ class BuildOwnerTests { env.put("CNB_USER_ID", "123"); env.put("CNB_GROUP_ID", "nope"); assertThatIllegalStateException().isThrownBy(() -> BuildOwner.fromEnv(env)) - .withMessage("Malformed 'CNB_GROUP_ID' value 'nope' in the builder environment '" + env + "'"); + .withMessage("Malformed 'CNB_GROUP_ID' value 'nope' in the builder environment '" + env + "'"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java index d06d8d855d..f5ef8aa7ff 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildRequestTests.java @@ -78,32 +78,33 @@ class BuildRequestTests { @Test void forJarFileWhenJarFileIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildRequest.forJarFile(null)) - .withMessage("JarFile must not be null"); + .withMessage("JarFile must not be null"); } @Test void forJarFileWhenJarFileIsMissingThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> BuildRequest.forJarFile(new File(this.tempDir, "missing.jar"))) - .withMessage("JarFile must exist"); + .isThrownBy(() -> BuildRequest.forJarFile(new File(this.tempDir, "missing.jar"))) + .withMessage("JarFile must exist"); } @Test void forJarFileWhenJarFileIsDirectoryThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildRequest.forJarFile(this.tempDir)) - .withMessage("JarFile must be a file"); + .withMessage("JarFile must be a file"); } @Test void withBuilderUpdatesBuilder() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) - .withBuilder(ImageReference.of("spring/builder")); + .withBuilder(ImageReference.of("spring/builder")); assertThat(request.getBuilder()).hasToString("docker.io/spring/builder:latest"); } @Test void withBuilderWhenHasDigestUpdatesBuilder() throws IOException { - BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")).withBuilder(ImageReference + BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) + .withBuilder(ImageReference .of("spring/builder@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")); assertThat(request.getBuilder()).hasToString( "docker.io/spring/builder@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); @@ -112,13 +113,14 @@ class BuildRequestTests { @Test void withRunImageUpdatesRunImage() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) - .withRunImage(ImageReference.of("example.com/custom/run-image:latest")); + .withRunImage(ImageReference.of("example.com/custom/run-image:latest")); assertThat(request.getRunImage()).hasToString("example.com/custom/run-image:latest"); } @Test void withRunImageWhenHasDigestUpdatesRunImage() throws IOException { - BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")).withRunImage(ImageReference + BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")) + .withRunImage(ImageReference .of("example.com/custom/run-image@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")); assertThat(request.getRunImage()).hasToString( "example.com/custom/run-image@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); @@ -157,14 +159,14 @@ class BuildRequestTests { void withEnvWhenKeyIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withEnv(null, "test")) - .withMessage("Name must not be empty"); + .withMessage("Name must not be empty"); } @Test void withEnvWhenValueIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withEnv("test", null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -181,7 +183,7 @@ class BuildRequestTests { void withBuildpacksWhenBuildpacksIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withBuildpacks((List) null)) - .withMessage("Buildpacks must not be null"); + .withMessage("Buildpacks must not be null"); } @Test @@ -198,7 +200,7 @@ class BuildRequestTests { void withBindingsWhenBindingsIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withBindings((List) null)) - .withMessage("Bindings must not be null"); + .withMessage("Bindings must not be null"); } @Test @@ -223,7 +225,7 @@ class BuildRequestTests { void withTagsWhenTagsIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withTags((List) null)) - .withMessage("Tags must not be null"); + .withMessage("Tags must not be null"); } @Test @@ -238,7 +240,7 @@ class BuildRequestTests { void withBuildVolumeCacheWhenCacheIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withBuildCache(null)) - .withMessage("BuildCache must not be null"); + .withMessage("BuildCache must not be null"); } @Test @@ -253,7 +255,7 @@ class BuildRequestTests { void withLaunchVolumeCacheWhenCacheIsNullThrowsException() throws IOException { BuildRequest request = BuildRequest.forJarFile(writeTestJarFile("my-app-0.0.1.jar")); assertThatIllegalArgumentException().isThrownBy(() -> request.withLaunchCache(null)) - .withMessage("LaunchCache must not be null"); + .withMessage("LaunchCache must not be null"); } private void hasExpectedJarContent(TarArchive archive) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java index 0907c1a2c2..d19666afdb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:paketo-buildpacks/spring-boot@3.5.0"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -61,7 +61,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:paketo-buildpacks/spring-boot"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -70,7 +70,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("paketo-buildpacks/spring-boot@3.5.0"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -79,7 +79,7 @@ class BuilderBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("paketo-buildpacks/spring-boot"); Buildpack buildpack = BuilderBuildpack.resolve(this.resolverContext, reference); assertThat(buildpack.getCoordinates()) - .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); + .isEqualTo(BuildpackCoordinates.of("paketo-buildpacks/spring-boot", "3.5.0")); assertThatNoLayersAreAdded(buildpack); } @@ -87,16 +87,16 @@ class BuilderBuildpackTests extends AbstractJsonTests { void resolveWhenFullyQualifiedBuildpackWithVersionNotInBuilderThrowsException() { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack1@1.2.3"); assertThatIllegalArgumentException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("'urn:cnb:builder:example/buildpack1@1.2.3'") - .withMessageContaining("not found in builder"); + .withMessageContaining("'urn:cnb:builder:example/buildpack1@1.2.3'") + .withMessageContaining("not found in builder"); } @Test void resolveWhenFullyQualifiedBuildpackWithoutVersionNotInBuilderThrowsException() { BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack1"); assertThatIllegalArgumentException().isThrownBy(() -> BuilderBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("'urn:cnb:builder:example/buildpack1'") - .withMessageContaining("not found in builder"); + .withMessageContaining("'urn:cnb:builder:example/buildpack1'") + .withMessageContaining("not found in builder"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java index b7dd6bf767..f5c0c0c7b5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -51,28 +51,28 @@ class BuilderMetadataTests extends AbstractJsonTests { assertThat(metadata.getLifecycle().getApi().getPlatform()).isEqualTo("0.3"); assertThat(metadata.getCreatedBy().getName()).isEqualTo("Pack CLI"); assertThat(metadata.getCreatedBy().getVersion()) - .isEqualTo("v0.9.0 (git sha: d42c384a39f367588f2653f2a99702db910e5ad7)"); + .isEqualTo("v0.9.0 (git sha: d42c384a39f367588f2653f2a99702db910e5ad7)"); assertThat(metadata.getBuildpacks()).extracting(BuildpackMetadata::getId, BuildpackMetadata::getVersion) - .contains(tuple("paketo-buildpacks/java", "4.10.0")) - .contains(tuple("paketo-buildpacks/spring-boot", "3.5.0")) - .contains(tuple("paketo-buildpacks/executable-jar", "3.1.3")) - .contains(tuple("paketo-buildpacks/graalvm", "4.1.0")) - .contains(tuple("paketo-buildpacks/java-native-image", "4.7.0")) - .contains(tuple("paketo-buildpacks/spring-boot-native-image", "2.0.1")) - .contains(tuple("paketo-buildpacks/bellsoft-liberica", "6.2.0")); + .contains(tuple("paketo-buildpacks/java", "4.10.0")) + .contains(tuple("paketo-buildpacks/spring-boot", "3.5.0")) + .contains(tuple("paketo-buildpacks/executable-jar", "3.1.3")) + .contains(tuple("paketo-buildpacks/graalvm", "4.1.0")) + .contains(tuple("paketo-buildpacks/java-native-image", "4.7.0")) + .contains(tuple("paketo-buildpacks/spring-boot-native-image", "2.0.1")) + .contains(tuple("paketo-buildpacks/bellsoft-liberica", "6.2.0")); } @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuilderMetadata.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test void fromImageWhenImageConfigIsNullThrowsException() { Image image = mock(Image.class); assertThatIllegalArgumentException().isThrownBy(() -> BuilderMetadata.fromImage(image)) - .withMessage("ImageConfig must not be null"); + .withMessage("ImageConfig must not be null"); } @Test @@ -82,7 +82,7 @@ class BuilderMetadataTests extends AbstractJsonTests { given(image.getConfig()).willReturn(imageConfig); given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a")); assertThatIllegalArgumentException().isThrownBy(() -> BuilderMetadata.fromImage(image)) - .withMessage("No 'io.buildpacks.builder.metadata' label found in image config labels 'alpha'"); + .withMessage("No 'io.buildpacks.builder.metadata' label found in image config labels 'alpha'"); } @Test @@ -127,7 +127,7 @@ class BuilderMetadataTests extends AbstractJsonTests { String label = imageConfigCopy.getLabels().get("io.buildpacks.builder.metadata"); BuilderMetadata metadataCopy = BuilderMetadata.fromJson(label); assertThat(metadataCopy.getStack().getRunImage().getImage()) - .isEqualTo(metadata.getStack().getRunImage().getImage()); + .isEqualTo(metadata.getStack().getRunImage().getImage()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java index 32ad37e113..c9c522a2dd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,7 +64,7 @@ class BuilderTests { @Test void createWhenLogIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Builder((BuildLog) null)) - .withMessage("Log must not be null"); + .withMessage("Log must not be null"); } @Test @@ -77,7 +77,7 @@ class BuilderTests { void buildWhenRequestIsNullThrowsException() { Builder builder = new Builder(); assertThatIllegalArgumentException().isThrownBy(() -> builder.build(null)) - .withMessage("Request must not be null"); + .withMessage("Request must not be null"); } @Test @@ -87,19 +87,19 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); builder.build(request); assertThat(out.toString()).contains("Running creator"); assertThat(out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); ArgumentCaptor archive = ArgumentCaptor.forClass(ImageArchive.class); - then(docker.image()).should().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - isNull()); - then(docker.image()).should().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - isNull()); + then(docker.image()).should() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull()); + then(docker.image()).should() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull()); then(docker.image()).should().load(archive.capture(), any()); then(docker.image()).should().remove(archive.getValue().getTag(), true); then(docker.image()).shouldHaveNoMoreInteractions(); @@ -112,26 +112,31 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token") - .withPublishRegistryTokenAuthentication("publish token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); - given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(runImage)); + .withBuilderRegistryTokenAuthentication("builder token") + .withPublishRegistryTokenAuthentication("publish token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); + given(docker.image() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest().withPublish(true); builder.build(request); assertThat(out.toString()).contains("Running creator"); assertThat(out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); ArgumentCaptor archive = ArgumentCaptor.forClass(ImageArchive.class); - then(docker.image()).should().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().push(eq(request.getName()), any(), - eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .push(eq(request.getName()), any(), + eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); then(docker.image()).should().load(archive.capture(), any()); then(docker.image()).should().remove(archive.getValue().getTag(), true); then(docker.image()).shouldHaveNoMoreInteractions(); @@ -144,9 +149,9 @@ class BuilderTests { Image builderImage = loadImage("image-with-no-run-image-tag.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of("gcr.io/paketo-buildpacks/builder:latest")), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:latest")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withBuilder(ImageReference.of("gcr.io/paketo-buildpacks/builder")); builder.build(request); @@ -164,10 +169,12 @@ class BuilderTests { Image builderImage = loadImage("image-with-run-image-digest.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); - given(docker.image().pull(eq(ImageReference.of( - "docker.io/cloudfoundry/run@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")), - any(), isNull())).willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(builderImage)); + given(docker.image() + .pull(eq(ImageReference + .of("docker.io/cloudfoundry/run@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d")), + any(), isNull())) + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); builder.build(request); @@ -185,9 +192,9 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("example.com/custom/run:latest")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withRunImage(ImageReference.of("example.com/custom/run:latest")); builder.build(request); @@ -205,13 +212,13 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))) - .willReturn(builderImage); + .willReturn(builderImage); given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))) - .willReturn(runImage); + .willReturn(runImage); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withPullPolicy(PullPolicy.NEVER); builder.build(request); @@ -231,13 +238,13 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))) - .willReturn(builderImage); + .willReturn(builderImage); given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))) - .willReturn(runImage); + .willReturn(runImage); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withPullPolicy(PullPolicy.ALWAYS); builder.build(request); @@ -257,15 +264,17 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); - given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))).willThrow( - new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) - .willReturn(builderImage); - given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))).willThrow( - new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) - .willReturn(runImage); + .willAnswer(withPulledImage(runImage)); + given(docker.image().inspect(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)))) + .willThrow( + new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) + .willReturn(builderImage); + given(docker.image().inspect(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")))) + .willThrow( + new DockerEngineException("docker://localhost/", new URI("example"), 404, "NOT FOUND", null, null)) + .willReturn(runImage); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withPullPolicy(PullPolicy.IF_NOT_PRESENT); builder.build(request); @@ -285,9 +294,9 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest().withTags(ImageReference.of("my-application:1.2.3")); builder.build(request); @@ -307,14 +316,16 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token") - .withPublishRegistryTokenAuthentication("publish token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); - given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(runImage)); + .withBuilderRegistryTokenAuthentication("builder token") + .withPublishRegistryTokenAuthentication("publish token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); + given(docker.image() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest().withPublish(true).withTags(ImageReference.of("my-application:1.2.3")); builder.build(request); @@ -322,15 +333,19 @@ class BuilderTests { assertThat(out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); assertThat(out.toString()).contains("Successfully created image tag 'docker.io/library/my-application:1.2.3'"); - then(docker.image()).should().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); - then(docker.image()).should().push(eq(request.getName()), any(), - eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .push(eq(request.getName()), any(), + eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); then(docker.image()).should().tag(eq(request.getName()), eq(ImageReference.of("my-application:1.2.3"))); - then(docker.image()).should().push(eq(ImageReference.of("my-application:1.2.3")), any(), - eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); + then(docker.image()).should() + .push(eq(ImageReference.of("my-application:1.2.3")), any(), + eq(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())); ArgumentCaptor archive = ArgumentCaptor.forClass(ImageArchive.class); then(docker.image()).should().load(archive.capture(), any()); then(docker.image()).should().remove(archive.getValue().getTag(), true); @@ -344,13 +359,14 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image-with-bad-stack.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); - assertThatIllegalStateException().isThrownBy(() -> builder.build(request)).withMessage( - "Run image stack 'org.cloudfoundry.stacks.cfwindowsfs3' does not match builder stack 'io.buildpacks.stacks.bionic'"); + assertThatIllegalStateException().isThrownBy(() -> builder.build(request)) + .withMessage( + "Run image stack 'org.cloudfoundry.stacks.cfwindowsfs3' does not match builder stack 'io.buildpacks.stacks.bionic'"); } @Test @@ -360,13 +376,13 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildRequest request = getTestRequest(); assertThatExceptionOfType(BuilderException.class).isThrownBy(() -> builder.build(request)) - .withMessage("Builder lifecycle 'creator' failed with status code 9"); + .withMessage("Builder lifecycle 'creator' failed with status code 9"); } @Test @@ -375,14 +391,16 @@ class BuilderTests { DockerApi docker = mockDockerApi(); Image builderImage = loadImage("image-with-run-image-different-registry.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); + .withBuilderRegistryTokenAuthentication("builder token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest(); - assertThatIllegalStateException().isThrownBy(() -> builder.build(request)).withMessage( - "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); + assertThatIllegalStateException().isThrownBy(() -> builder.build(request)) + .withMessage( + "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); } @Test @@ -391,14 +409,16 @@ class BuilderTests { DockerApi docker = mockDockerApi(); Image builderImage = loadImage("image.json"); DockerConfiguration dockerConfiguration = new DockerConfiguration() - .withBuilderRegistryTokenAuthentication("builder token"); - given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), - eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) - .willAnswer(withPulledImage(builderImage)); + .withBuilderRegistryTokenAuthentication("builder token"); + given(docker.image() + .pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), + eq(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader()))) + .willAnswer(withPulledImage(builderImage)); Builder builder = new Builder(BuildLog.to(out), docker, dockerConfiguration); BuildRequest request = getTestRequest().withRunImage(ImageReference.of("example.com/custom/run:latest")); - assertThatIllegalStateException().isThrownBy(() -> builder.build(request)).withMessage( - "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); + assertThatIllegalStateException().isThrownBy(() -> builder.build(request)) + .withMessage( + "Run image 'example.com/custom/run:latest' must be pulled from the 'docker.io' authenticated registry"); } @Test @@ -408,15 +428,15 @@ class BuilderTests { Image builderImage = loadImage("image.json"); Image runImage = loadImage("run-image.json"); given(docker.image().pull(eq(ImageReference.of(BuildRequest.DEFAULT_BUILDER_IMAGE_NAME)), any(), isNull())) - .willAnswer(withPulledImage(builderImage)); + .willAnswer(withPulledImage(builderImage)); given(docker.image().pull(eq(ImageReference.of("docker.io/cloudfoundry/run:base-cnb")), any(), isNull())) - .willAnswer(withPulledImage(runImage)); + .willAnswer(withPulledImage(runImage)); Builder builder = new Builder(BuildLog.to(out), docker, null); BuildpackReference reference = BuildpackReference.of("urn:cnb:builder:example/buildpack@1.2.3"); BuildRequest request = getTestRequest().withBuildpacks(reference); assertThatIllegalArgumentException().isThrownBy(() -> builder.build(request)) - .withMessageContaining("'urn:cnb:builder:example/buildpack@1.2.3'") - .withMessageContaining("not found in builder"); + .withMessageContaining("'urn:cnb:builder:example/buildpack@1.2.3'") + .withMessageContaining("not found in builder"); } private DockerApi mockDockerApi() throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java index b13df8f155..5a2820a85f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackCoordinatesTests.java @@ -43,7 +43,7 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { @Test void fromToml() throws IOException { BuildpackCoordinates coordinates = BuildpackCoordinates - .fromToml(createTomlStream("example/buildpack1", "0.0.1", true, false), this.archive); + .fromToml(createTomlStream("example/buildpack1", "0.0.1", true, false), this.archive); assertThat(coordinates.getId()).isEqualTo("example/buildpack1"); assertThat(coordinates.getVersion()).isEqualTo("0.0.1"); } @@ -52,17 +52,17 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { void fromTomlWhenMissingDescriptorThrowsException() { ByteArrayInputStream coordinates = new ByteArrayInputStream("".getBytes()); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") - .withMessageContaining(this.archive.toString()); + .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") + .withMessageContaining(this.archive.toString()); } @Test void fromTomlWhenMissingIDThrowsException() throws IOException { try (InputStream coordinates = createTomlStream(null, null, true, false)) { assertThatIllegalArgumentException() - .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must contain ID") - .withMessageContaining(this.archive.toString()); + .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) + .withMessageContaining("Buildpack descriptor must contain ID") + .withMessageContaining(this.archive.toString()); } } @@ -70,9 +70,9 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { void fromTomlWhenMissingVersionThrowsException() throws IOException { try (InputStream coordinates = createTomlStream("example/buildpack1", null, true, false)) { assertThatIllegalArgumentException() - .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must contain version") - .withMessageContaining(this.archive.toString()); + .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) + .withMessageContaining("Buildpack descriptor must contain version") + .withMessageContaining(this.archive.toString()); } } @@ -80,9 +80,9 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { void fromTomlWhenMissingStacksAndOrderThrowsException() throws IOException { try (InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", false, false)) { assertThatIllegalArgumentException() - .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must contain either 'stacks' or 'order'") - .withMessageContaining(this.archive.toString()); + .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) + .withMessageContaining("Buildpack descriptor must contain either 'stacks' or 'order'") + .withMessageContaining(this.archive.toString()); } } @@ -90,16 +90,16 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { void fromTomlWhenContainsBothStacksAndOrderThrowsException() throws IOException { try (InputStream coordinates = createTomlStream("example/buildpack1", "0.0.1", true, true)) { assertThatIllegalArgumentException() - .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) - .withMessageContaining("Buildpack descriptor must not contain both 'stacks' and 'order'") - .withMessageContaining(this.archive.toString()); + .isThrownBy(() -> BuildpackCoordinates.fromToml(coordinates, this.archive)) + .withMessageContaining("Buildpack descriptor must not contain both 'stacks' and 'order'") + .withMessageContaining(this.archive.toString()); } } @Test void fromBuildpackMetadataWhenMetadataIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.fromBuildpackMetadata(null)) - .withMessage("BuildpackMetadata must not be null"); + .withMessage("BuildpackMetadata must not be null"); } @Test @@ -113,7 +113,7 @@ class BuildpackCoordinatesTests extends AbstractJsonTests { @Test void ofWhenIdIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackCoordinates.of(null, null)) - .withMessage("ID must not be empty"); + .withMessage("ID must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java index 779c1607d3..31d692f849 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackLayersMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,11 +42,11 @@ class BuildpackLayersMetadataTests extends AbstractJsonTests { Image image = Image.of(getContent("buildpack-image.json")); BuildpackLayersMetadata metadata = BuildpackLayersMetadata.fromImage(image); assertThat(metadata.getBuildpack("example/hello-moon", "0.0.3")).extracting("homepage", "layerDiffId") - .containsExactly("https://github.com/example/tree/main/buildpacks/hello-moon", - "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); + .containsExactly("https://github.com/example/tree/main/buildpacks/hello-moon", + "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); assertThat(metadata.getBuildpack("example/hello-world", "0.0.2")).extracting("homepage", "layerDiffId") - .containsExactly("https://github.com/example/tree/main/buildpacks/hello-world", - "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); + .containsExactly("https://github.com/example/tree/main/buildpacks/hello-world", + "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); assertThat(metadata.getBuildpack("example/hello-world", "version-does-not-exist")).isNull(); assertThat(metadata.getBuildpack("id-does-not-exist", "9.9.9")).isNull(); } @@ -54,14 +54,14 @@ class BuildpackLayersMetadataTests extends AbstractJsonTests { @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test void fromImageWhenImageConfigIsNullThrowsException() { Image image = mock(Image.class); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(image)) - .withMessage("ImageConfig must not be null"); + .withMessage("ImageConfig must not be null"); } @Test @@ -71,25 +71,25 @@ class BuildpackLayersMetadataTests extends AbstractJsonTests { given(image.getConfig()).willReturn(imageConfig); given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a")); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackLayersMetadata.fromImage(image)) - .withMessage("No 'io.buildpacks.buildpack.layers' label found in image config labels 'alpha'"); + .withMessage("No 'io.buildpacks.buildpack.layers' label found in image config labels 'alpha'"); } @Test void fromJsonLoadsMetadata() throws IOException { BuildpackLayersMetadata metadata = BuildpackLayersMetadata - .fromJson(getContentAsString("buildpack-layers-metadata.json")); + .fromJson(getContentAsString("buildpack-layers-metadata.json")); assertThat(metadata.getBuildpack("example/hello-moon", "0.0.3")).extracting("name", "homepage", "layerDiffId") - .containsExactly("Example hello-moon buildpack", - "https://github.com/example/tree/main/buildpacks/hello-moon", - "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); + .containsExactly("Example hello-moon buildpack", + "https://github.com/example/tree/main/buildpacks/hello-moon", + "sha256:4bfdc8714aee68da6662c43bc28d3b41202c88e915641c356523dabe729814c2"); assertThat(metadata.getBuildpack("example/hello-world", "0.0.1")).extracting("name", "homepage", "layerDiffId") - .containsExactly("Example hello-world buildpack", - "https://github.com/example/tree/main/buildpacks/hello-world", - "sha256:1c90e0b80d92555a0523c9ee6500845328fc39ba9dca9d30a877ff759ffbff28"); + .containsExactly("Example hello-world buildpack", + "https://github.com/example/tree/main/buildpacks/hello-world", + "sha256:1c90e0b80d92555a0523c9ee6500845328fc39ba9dca9d30a877ff759ffbff28"); assertThat(metadata.getBuildpack("example/hello-world", "0.0.2")).extracting("name", "homepage", "layerDiffId") - .containsExactly("Example hello-world buildpack", - "https://github.com/example/tree/main/buildpacks/hello-world", - "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); + .containsExactly("Example hello-world buildpack", + "https://github.com/example/tree/main/buildpacks/hello-world", + "sha256:f752fe099c846e501bdc991d1a22f98c055ddc62f01cfc0495fff2c69f8eb940"); assertThat(metadata.getBuildpack("example/hello-world", "version-does-not-exist")).isNull(); assertThat(metadata.getBuildpack("id-does-not-exist", "9.9.9")).isNull(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java index 413fd2100e..dd9fac9d1a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -48,14 +48,14 @@ class BuildpackMetadataTests extends AbstractJsonTests { @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackMetadata.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test void fromImageWhenImageConfigIsNullThrowsException() { Image image = mock(Image.class); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackMetadata.fromImage(image)) - .withMessage("ImageConfig must not be null"); + .withMessage("ImageConfig must not be null"); } @Test @@ -65,7 +65,7 @@ class BuildpackMetadataTests extends AbstractJsonTests { given(image.getConfig()).willReturn(imageConfig); given(imageConfig.getLabels()).willReturn(Collections.singletonMap("alpha", "a")); assertThatIllegalArgumentException().isThrownBy(() -> BuildpackMetadata.fromImage(image)) - .withMessage("No 'io.buildpacks.buildpackage.metadata' label found in image config labels 'alpha'"); + .withMessage("No 'io.buildpacks.buildpackage.metadata' label found in image config labels 'alpha'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java index 23565c31ef..9fc08f4a13 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackReferenceTests.java @@ -33,7 +33,7 @@ class BuildpackReferenceTests { @Test void ofWhenValueIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> BuildpackReference.of("")) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java index 12c2038a7d..47daf7ee2b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuildpackResolversTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -96,9 +96,9 @@ class BuildpackResolversTests extends AbstractJsonTests { void resolveAllWithInvalidLocatorThrowsException() { BuildpackReference reference = BuildpackReference.of("unknown-buildpack@0.0.1"); assertThatIllegalArgumentException() - .isThrownBy(() -> BuildpackResolvers.resolveAll(this.resolverContext, Collections.singleton(reference))) - .withMessageContaining("Invalid buildpack reference") - .withMessageContaining("'unknown-buildpack@0.0.1'"); + .isThrownBy(() -> BuildpackResolvers.resolveAll(this.resolverContext, Collections.singleton(reference))) + .withMessageContaining("Invalid buildpack reference") + .withMessageContaining("'unknown-buildpack@0.0.1'"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java index 65a0fed9ff..bb9c95b61b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/DirectoryBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -90,9 +90,9 @@ class DirectoryBuildpackTests { Files.createDirectories(this.buildpackDir.toPath()); BuildpackReference reference = BuildpackReference.of(this.buildpackDir.toString()); assertThatIllegalArgumentException() - .isThrownBy(() -> DirectoryBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") - .withMessageContaining(this.buildpackDir.getAbsolutePath()); + .isThrownBy(() -> DirectoryBuildpack.resolve(this.resolverContext, reference)) + .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") + .withMessageContaining(this.buildpackDir.getAbsolutePath()); } @Test @@ -133,13 +133,14 @@ class DirectoryBuildpackTests { entries.add(entry); entry = tar.getNextTarEntry(); } - assertThat(entries).extracting("name", "mode").containsExactlyInAnyOrder(tuple("/cnb/", 0755), - tuple("/cnb/buildpacks/", 0755), tuple("/cnb/buildpacks/example_buildpack1/", 0755), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/", 0755), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml", 0644), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/", 0755), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/detect", 0744), - tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/build", 0744)); + assertThat(entries).extracting("name", "mode") + .containsExactlyInAnyOrder(tuple("/cnb/", 0755), tuple("/cnb/buildpacks/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml", 0644), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/", 0755), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/detect", 0744), + tuple("/cnb/buildpacks/example_buildpack1/0.0.1/bin/build", 0744)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java index fe4492d735..dac256363d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/EphemeralBuilderTests.java @@ -144,7 +144,7 @@ class EphemeralBuilderTests extends AbstractJsonTests { this.creator, this.env, this.buildpacks); ImageConfig config = builder.getArchive().getImageConfig(); assertThat(config.getLabels()) - .contains(entry(EphemeralBuilder.BUILDER_FOR_LABEL_NAME, this.targetImage.toString())); + .contains(entry(EphemeralBuilder.BUILDER_FOR_LABEL_NAME, this.targetImage.toString())); } @Test @@ -164,7 +164,7 @@ class EphemeralBuilderTests extends AbstractJsonTests { "/cnb/buildpacks/example_buildpack3/0.0.3/buildpack.toml"); File orderDirectory = unpack(getLayer(builder.getArchive(), EXISTING_IMAGE_LAYER_COUNT + 3), "order"); assertThat(new File(orderDirectory, "cnb/order.toml")).usingCharset(StandardCharsets.UTF_8) - .hasContent(content("order.toml")); + .hasContent(content("order.toml")); } private void assertBuildpackLayerContent(EphemeralBuilder builder, int index, String s) throws Exception { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java index 7a349006cf..20a483a514 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -126,7 +126,7 @@ class ImageBuildpackTests extends AbstractJsonTests { ImageReference imageReference = ImageReference.of("example/buildpack1:1.0.0"); BuildpackResolverContext resolverContext = mock(BuildpackResolverContext.class); given(resolverContext.getBuildpackLayersMetadata()) - .willReturn(BuildpackLayersMetadata.fromJson(getContentAsString("buildpack-layers-metadata.json"))); + .willReturn(BuildpackLayersMetadata.fromJson(getContentAsString("buildpack-layers-metadata.json"))); given(resolverContext.fetchImage(eq(imageReference), eq(ImageType.BUILDPACK))).willReturn(image); willAnswer(this::withMockLayers).given(resolverContext).exportImageLayers(eq(imageReference), any()); BuildpackReference reference = BuildpackReference.of("docker://example/buildpack1:1.0.0"); @@ -141,8 +141,8 @@ class ImageBuildpackTests extends AbstractJsonTests { given(resolverContext.fetchImage(any(), any())).willThrow(IOException.class); BuildpackReference reference = BuildpackReference.of("docker://example/buildpack1"); assertThatIllegalArgumentException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) - .withMessageContaining("Error pulling buildpack image") - .withMessageContaining("example/buildpack1:latest"); + .withMessageContaining("Error pulling buildpack image") + .withMessageContaining("example/buildpack1:latest"); } @Test @@ -152,7 +152,7 @@ class ImageBuildpackTests extends AbstractJsonTests { given(resolverContext.fetchImage(any(), any())).willReturn(image); BuildpackReference reference = BuildpackReference.of("docker://example/buildpack1:latest"); assertThatIllegalArgumentException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) - .withMessageContaining("No 'io.buildpacks.buildpackage.metadata' label found"); + .withMessageContaining("No 'io.buildpacks.buildpackage.metadata' label found"); } @Test @@ -160,7 +160,7 @@ class ImageBuildpackTests extends AbstractJsonTests { BuildpackReference reference = BuildpackReference.of("docker://buildpack@0.0.1"); BuildpackResolverContext resolverContext = mock(BuildpackResolverContext.class); assertThatIllegalArgumentException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) - .withMessageContaining("Unable to parse image reference \"buildpack@0.0.1\""); + .withMessageContaining("Unable to parse image reference \"buildpack@0.0.1\""); } @Test @@ -217,14 +217,14 @@ class ImageBuildpackTests extends AbstractJsonTests { entry = tar.getNextTarEntry(); } } - assertThat(entries).extracting("name", "mode").containsExactlyInAnyOrder( - tuple("cnb/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/example_buildpack/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/example_buildpack/0.0.1/", TarArchiveEntry.DEFAULT_DIR_MODE), - tuple("cnb/buildpacks/example_buildpack/0.0.1/buildpack.toml", TarArchiveEntry.DEFAULT_FILE_MODE), - tuple("cnb/buildpacks/example_buildpack/0.0.1/" + this.longFilePath, - TarArchiveEntry.DEFAULT_FILE_MODE)); + assertThat(entries).extracting("name", "mode") + .containsExactlyInAnyOrder(tuple("cnb/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/example_buildpack/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/example_buildpack/0.0.1/", TarArchiveEntry.DEFAULT_DIR_MODE), + tuple("cnb/buildpacks/example_buildpack/0.0.1/buildpack.toml", TarArchiveEntry.DEFAULT_FILE_MODE), + tuple("cnb/buildpacks/example_buildpack/0.0.1/" + this.longFilePath, + TarArchiveEntry.DEFAULT_FILE_MODE)); } private void assertAppliesNoLayers(Buildpack buildpack) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java index ed188ba520..e333cf9b45 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -135,7 +135,7 @@ class LifecycleTests { Lifecycle lifecycle = createLifecycle(); lifecycle.execute(); assertThatIllegalStateException().isThrownBy(lifecycle::execute) - .withMessage("Lifecycle has already been executed"); + .withMessage("Lifecycle has already been executed"); } @Test @@ -144,7 +144,7 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(9, null)); assertThatExceptionOfType(BuilderException.class).isThrownBy(() -> createLifecycle().execute()) - .withMessage("Builder lifecycle 'creator' failed with status code 9"); + .withMessage("Builder lifecycle 'creator' failed with status code 9"); } @Test @@ -165,8 +165,8 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null)); assertThatIllegalStateException() - .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-api.json").execute()) - .withMessageContaining("Detected platform API versions '0.2' are not included in supported versions"); + .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-api.json").execute()) + .withMessageContaining("Detected platform API versions '0.2' are not included in supported versions"); } @Test @@ -175,9 +175,8 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null)); assertThatIllegalStateException() - .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-apis.json").execute()) - .withMessageContaining( - "Detected platform API versions '0.1,0.2' are not included in supported versions"); + .isThrownBy(() -> createLifecycle("builder-metadata-unsupported-apis.json").execute()) + .withMessageContaining("Detected platform API versions '0.1,0.2' are not included in supported versions"); } @Test @@ -213,7 +212,7 @@ class LifecycleTests { given(this.docker.container().create(any(), any())).willAnswer(answerWithGeneratedContainerId()); given(this.docker.container().wait(any())).willReturn(ContainerStatus.of(0, null)); BuildRequest request = getTestRequest().withBuildCache(Cache.volume("build-volume")) - .withLaunchCache(Cache.volume("launch-volume")); + .withLaunchCache(Cache.volume("launch-volume")); createLifecycle(request).execute(); assertPhaseWasRun("creator", withExpectedConfig("lifecycle-creator-cache-volumes.json")); assertThat(this.out.toString()).contains("Successfully built image 'docker.io/library/my-application:latest'"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java index cf7675b728..4bd256bb75 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/LifecycleVersionTests.java @@ -31,19 +31,19 @@ class LifecycleVersionTests { @Test void parseWhenValueIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LifecycleVersion.parse(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void parseWhenTooLongThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LifecycleVersion.parse("v1.2.3.4")) - .withMessage("Malformed version number '1.2.3.4'"); + .withMessage("Malformed version number '1.2.3.4'"); } @Test void parseWhenNonNumericThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LifecycleVersion.parse("v1.2.3a")) - .withMessage("Malformed version number '1.2.3a'"); + .withMessage("Malformed version number '1.2.3a'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java index 3cff5bc23c..53de18ca94 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/StackIdTests.java @@ -39,7 +39,7 @@ class StackIdTests { @Test void fromImageWhenImageIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> StackId.fromImage(null)) - .withMessage("Image must not be null"); + .withMessage("Image must not be null"); } @Test @@ -48,7 +48,7 @@ class StackIdTests { ImageConfig imageConfig = mock(ImageConfig.class); given(image.getConfig()).willReturn(imageConfig); assertThatIllegalStateException().isThrownBy(() -> StackId.fromImage(image)) - .withMessage("Missing 'io.buildpacks.stack.id' stack label"); + .withMessage("Missing 'io.buildpacks.stack.id' stack label"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java index 9bc68cb8bb..561d370719 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TarGzipBuildpackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -73,8 +73,8 @@ class TarGzipBuildpackTests { Path compressedArchive = this.testTarGzip.createEmptyArchive(); BuildpackReference reference = BuildpackReference.of(compressedArchive.toString()); assertThatIllegalArgumentException().isThrownBy(() -> TarGzipBuildpack.resolve(this.resolverContext, reference)) - .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") - .withMessageContaining(compressedArchive.toString()); + .withMessageContaining("Buildpack descriptor 'buildpack.toml' is required") + .withMessageContaining(compressedArchive.toString()); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java index be0de887f4..6a143fa2e0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/TestTarGzip.java @@ -129,7 +129,7 @@ class TestTarGzip { assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/"); assertThat(tar.getNextEntry().getName()) - .isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml"); + .isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/buildpack.toml"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/bin/"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/bin/detect"); assertThat(tar.getNextEntry().getName()).isEqualTo("cnb/buildpacks/example_buildpack1/0.0.1/bin/build"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java index b5242e2be6..cff7b111eb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -35,8 +35,9 @@ class DockerApiIntegrationTests { @Test void pullImage() throws IOException { - this.docker.image().pull(ImageReference.of("gcr.io/paketo-buildpacks/builder:base"), - new TotalProgressPullListener(new TotalProgressBar("Pulling: "))); + this.docker.image() + .pull(ImageReference.of("gcr.io/paketo-buildpacks/builder:base"), + new TotalProgressPullListener(new TotalProgressBar("Pulling: "))); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java index a7521f8c66..9fd75fda61 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/DockerApiTests.java @@ -151,13 +151,13 @@ class DockerApiTests { @Test void pullWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.pull(null, this.pullListener)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void pullWhenListenerIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.pull(ImageReference.of("ubuntu"), null)) - .withMessage("Listener must not be null"); + .withMessage("Listener must not be null"); } @Test @@ -193,14 +193,14 @@ class DockerApiTests { @Test void pushWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.push(null, this.pushListener, null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void pushWhenListenerIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.api.push(ImageReference.of("ubuntu"), null, null)) - .withMessage("Listener must not be null"); + .isThrownBy(() -> this.api.push(ImageReference.of("ubuntu"), null, null)) + .withMessage("Listener must not be null"); } @Test @@ -221,21 +221,21 @@ class DockerApiTests { URI pushUri = new URI(IMAGES_URL + "/localhost:5000/ubuntu/push"); given(http().post(pushUri, "auth token")).willReturn(responseOf("push-stream-with-error.json")); assertThatIllegalStateException() - .isThrownBy(() -> this.api.push(reference, this.pushListener, "auth token")) - .withMessageContaining("test message"); + .isThrownBy(() -> this.api.push(reference, this.pushListener, "auth token")) + .withMessageContaining("test message"); } @Test void loadWhenArchiveIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.load(null, UpdateListener.none())) - .withMessage("Archive must not be null"); + .withMessage("Archive must not be null"); } @Test void loadWhenListenerIsNullThrowsException() { ImageArchive archive = mock(ImageArchive.class); assertThatIllegalArgumentException().isThrownBy(() -> this.api.load(archive, null)) - .withMessage("Listener must not be null"); + .withMessage("Listener must not be null"); } @Test // gh-23130 @@ -245,7 +245,7 @@ class DockerApiTests { URI loadUri = new URI(IMAGES_URL + "/load"); given(http().post(eq(loadUri), eq("application/x-tar"), any())).willReturn(emptyResponse()); assertThatIllegalStateException().isThrownBy(() -> this.api.load(archive, this.loadListener)) - .withMessageContaining("Invalid response received"); + .withMessageContaining("Invalid response received"); } @Test @@ -268,13 +268,13 @@ class DockerApiTests { @Test void removeWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.remove(null, true)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void removeRemovesContainer() throws Exception { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); URI removeUri = new URI(IMAGES_URL + "/docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); given(http().delete(removeUri)).willReturn(emptyResponse()); @@ -285,7 +285,7 @@ class DockerApiTests { @Test void removeWhenForceIsTrueRemovesContainer() throws Exception { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); URI removeUri = new URI(IMAGES_URL + "/docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d?force=1"); given(http().delete(removeUri)).willReturn(emptyResponse()); @@ -296,7 +296,7 @@ class DockerApiTests { @Test void inspectWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.inspect(null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -318,7 +318,7 @@ class DockerApiTests { void exportLayersWhenExportsIsNullThrowsException() { ImageReference reference = ImageReference.of("gcr.io/paketo-buildpacks/builder:base"); assertThatIllegalArgumentException().isThrownBy(() -> this.api.exportLayers(reference, null)) - .withMessage("Exports must not be null"); + .withMessage("Exports must not be null"); } @Test @@ -339,26 +339,26 @@ class DockerApiTests { } } }); - assertThat(contents).hasSize(3).containsKeys( - "1bf6c63a1e9ed1dd7cb961273bf60b8e0f440361faf273baf866f408e4910601/layer.tar", - "8fdfb915302159a842cbfae6faec5311b00c071ebf14e12da7116ae7532e9319/layer.tar", - "93cd584bb189bfca4f51744bd19d836fd36da70710395af5a1523ee88f208c6a/layer.tar"); + assertThat(contents).hasSize(3) + .containsKeys("1bf6c63a1e9ed1dd7cb961273bf60b8e0f440361faf273baf866f408e4910601/layer.tar", + "8fdfb915302159a842cbfae6faec5311b00c071ebf14e12da7116ae7532e9319/layer.tar", + "93cd584bb189bfca4f51744bd19d836fd36da70710395af5a1523ee88f208c6a/layer.tar"); assertThat(contents.get("1bf6c63a1e9ed1dd7cb961273bf60b8e0f440361faf273baf866f408e4910601/layer.tar")) - .containsExactly("etc/", "etc/apt/", "etc/apt/sources.list"); + .containsExactly("etc/", "etc/apt/", "etc/apt/sources.list"); } @Test void tagWhenReferenceIsNullThrowsException() { ImageReference tag = ImageReference.of("localhost:5000/ubuntu"); assertThatIllegalArgumentException().isThrownBy(() -> this.api.tag(null, tag)) - .withMessage("SourceReference must not be null"); + .withMessage("SourceReference must not be null"); } @Test void tagWhenTargetIsNullThrowsException() { ImageReference reference = ImageReference.of("localhost:5000/ubuntu"); assertThatIllegalArgumentException().isThrownBy(() -> this.api.tag(reference, null)) - .withMessage("TargetReference must not be null"); + .withMessage("TargetReference must not be null"); } @Test @@ -392,7 +392,7 @@ class DockerApiTests { @Test void createWhenConfigIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.create(null)) - .withMessage("Config must not be null"); + .withMessage("Config must not be null"); } @Test @@ -401,7 +401,7 @@ class DockerApiTests { ContainerConfig config = ContainerConfig.of(imageReference, (update) -> update.withCommand("/bin/bash")); URI createUri = new URI(CONTAINERS_URL + "/create"); given(http().post(eq(createUri), eq("application/json"), any())) - .willReturn(responseOf("create-container-response.json")); + .willReturn(responseOf("create-container-response.json")); ContainerReference containerReference = this.api.create(config); assertThat(containerReference).hasToString("e90e34656806"); then(http()).should().post(any(), any(), this.writer.capture()); @@ -421,7 +421,7 @@ class DockerApiTests { ContainerContent content = ContainerContent.of(archive); URI createUri = new URI(CONTAINERS_URL + "/create"); given(http().post(eq(createUri), eq("application/json"), any())) - .willReturn(responseOf("create-container-response.json")); + .willReturn(responseOf("create-container-response.json")); URI uploadUri = new URI(CONTAINERS_URL + "/e90e34656806/archive?path=%2F"); given(http().put(eq(uploadUri), eq("application/x-tar"), any())).willReturn(emptyResponse()); ContainerReference containerReference = this.api.create(config, content); @@ -438,7 +438,7 @@ class DockerApiTests { @Test void startWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.start(null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -453,14 +453,14 @@ class DockerApiTests { @Test void logsWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.logs(null, UpdateListener.none())) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void logsWhenListenerIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.api.logs(ContainerReference.of("e90e34656806"), null)) - .withMessage("Listener must not be null"); + .isThrownBy(() -> this.api.logs(ContainerReference.of("e90e34656806"), null)) + .withMessage("Listener must not be null"); } @Test @@ -478,7 +478,7 @@ class DockerApiTests { @Test void waitWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.wait(null)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -493,7 +493,7 @@ class DockerApiTests { @Test void removeWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.remove(null, true)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test @@ -529,7 +529,7 @@ class DockerApiTests { @Test void deleteWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.api.delete(null, false)) - .withMessage("Name must not be null"); + .withMessage("Name must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java index 91164b19c3..ab351ac8eb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/LogUpdateEventTests.java @@ -37,11 +37,11 @@ class LogUpdateEventTests { List events = readAll("log-update-event.stream"); assertThat(events).hasSize(7); assertThat(events.get(0)) - .hasToString("Analyzing image '307c032c4ceaa6330b6c02af945a1fe56a8c3c27c28268574b217c1d38b093cf'"); + .hasToString("Analyzing image '307c032c4ceaa6330b6c02af945a1fe56a8c3c27c28268574b217c1d38b093cf'"); assertThat(events.get(1)) - .hasToString("Writing metadata for uncached layer 'org.cloudfoundry.openjdk:openjdk-jre'"); + .hasToString("Writing metadata for uncached layer 'org.cloudfoundry.openjdk:openjdk-jre'"); assertThat(events.get(2)) - .hasToString("Using cached launch layer 'org.cloudfoundry.jvmapplication:executable-jar'"); + .hasToString("Using cached launch layer 'org.cloudfoundry.jvmapplication:executable-jar'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java index 7afe0a1703..02f7366713 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/TotalProgressEventTests.java @@ -38,13 +38,13 @@ class TotalProgressEventTests { @Test void createWhenPercentLessThanZeroThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new TotalProgressEvent(-1)) - .withMessage("Percent must be in the range 0 to 100"); + .withMessage("Percent must be in the range 0 to 100"); } @Test void createWhenEventMoreThanOneHundredThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new TotalProgressEvent(101)) - .withMessage("Percent must be in the range 0 to 100"); + .withMessage("Percent must be in the range 0 to 100"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java index 76ec72005f..dbb9deebe6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParserTests.java @@ -74,7 +74,7 @@ class CertificateParserTests { void parseWithInvalidPathWillThrowException() throws URISyntaxException { Path path = Paths.get(new URI("file:///bad/path/cert.pem")); assertThatIllegalStateException().isThrownBy(() -> CertificateParser.parse(path)) - .withMessageContaining(path.toString()); + .withMessageContaining(path.toString()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java index f55f79aaf3..8ba45fa513 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,7 @@ class PrivateKeyParserTests { void parseWithNonKeyFileWillThrowException() throws IOException { Path path = this.fileWriter.writeFile("text.pem", "plain text"); assertThatIllegalStateException().isThrownBy(() -> PrivateKeyParser.parse(path)) - .withMessageContaining(path.toString()); + .withMessageContaining(path.toString()); Files.delete(path); } @@ -95,7 +95,7 @@ class PrivateKeyParserTests { void parseWithInvalidPathWillThrowException() throws URISyntaxException { Path path = Paths.get(new URI("file:///bad/path/key.pem")); assertThatIllegalStateException().isThrownBy(() -> PrivateKeyParser.parse(path)) - .withMessageContaining(path.toString()); + .withMessageContaining(path.toString()); } @Nested diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java index 0501c5364c..68c5546e1a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerConnectionExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -35,20 +35,20 @@ class DockerConnectionExceptionTests { @Test void createWhenHostIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new DockerConnectionException(null, null)) - .withMessage("Host must not be null"); + .withMessage("Host must not be null"); } @Test void createWhenCauseIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new DockerConnectionException(HOST, null)) - .withMessage("Cause must not be null"); + .withMessage("Cause must not be null"); } @Test void createWithIOException() { DockerConnectionException exception = new DockerConnectionException(HOST, new IOException("error")); assertThat(exception.getMessage()) - .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"error\""); + .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"error\""); } @Test @@ -56,7 +56,7 @@ class DockerConnectionExceptionTests { DockerConnectionException exception = new DockerConnectionException(HOST, new IOException(new com.sun.jna.LastErrorException("root cause"))); assertThat(exception.getMessage()) - .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"root cause\""); + .contains("Connection to the Docker daemon at 'docker://localhost/' failed with error \"root cause\""); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java index d3a76a38ce..72c3ff0321 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -56,15 +56,15 @@ class DockerEngineExceptionTests { @Test void createWhenHostIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DockerEngineException(null, null, 404, null, NO_ERRORS, NO_MESSAGE)) - .withMessage("Host must not be null"); + .isThrownBy(() -> new DockerEngineException(null, null, 404, null, NO_ERRORS, NO_MESSAGE)) + .withMessage("Host must not be null"); } @Test void createWhenUriIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new DockerEngineException(HOST, null, 404, null, NO_ERRORS, NO_MESSAGE)) - .withMessage("URI must not be null"); + .isThrownBy(() -> new DockerEngineException(HOST, null, 404, null, NO_ERRORS, NO_MESSAGE)) + .withMessage("URI must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java index b415e5ed4a..0ff7f50407 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -264,10 +264,10 @@ class HttpClientTransportTests { given(this.entity.getContent()).willReturn(getClass().getResourceAsStream("errors.json")); given(this.statusLine.getStatusCode()).willReturn(404); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).hasSize(2); - assertThat(ex.getResponseMessage()).isNull(); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).hasSize(2); + assertThat(ex.getResponseMessage()).isNull(); + }); } @Test @@ -275,10 +275,10 @@ class HttpClientTransportTests { givenClientWillReturnResponse(); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).isNull(); - assertThat(ex.getResponseMessage()).isNull(); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).isNull(); + assertThat(ex.getResponseMessage()).isNull(); + }); } @Test @@ -287,10 +287,10 @@ class HttpClientTransportTests { given(this.entity.getContent()).willReturn(getClass().getResourceAsStream("message.json")); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).isNull(); - assertThat(ex.getResponseMessage().getMessage()).contains("test message"); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).isNull(); + assertThat(ex.getResponseMessage().getMessage()).contains("test message"); + }); } @Test @@ -299,18 +299,18 @@ class HttpClientTransportTests { given(this.entity.getContent()).willReturn(this.content); given(this.statusLine.getStatusCode()).willReturn(500); assertThatExceptionOfType(DockerEngineException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> { - assertThat(ex.getErrors()).isNull(); - assertThat(ex.getResponseMessage()).isNull(); - }); + .satisfies((ex) -> { + assertThat(ex.getErrors()).isNull(); + assertThat(ex.getResponseMessage()).isNull(); + }); } @Test void executeWhenClientThrowsIOExceptionRethrowsAsDockerException() throws IOException { given(this.client.execute(any(HttpHost.class), any(HttpRequest.class))) - .willThrow(new IOException("test IO exception")); + .willThrow(new IOException("test IO exception")); assertThatExceptionOfType(DockerConnectionException.class).isThrownBy(() -> this.http.get(this.uri)) - .satisfies((ex) -> assertThat(ex.getMessage()).contains("test IO exception")); + .satisfies((ex) -> assertThat(ex.getMessage()).contains("test IO exception")); } private String writeToString(HttpEntity entity) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java index 0bf2fb3685..7eb2fb5d06 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/RemoteHttpClientTransportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -80,7 +80,7 @@ class RemoteHttpClientTransportTests { SslContextFactory sslContextFactory = mock(SslContextFactory.class); given(sslContextFactory.forDirectory("/test-cert-path")).willReturn(SSLContext.getDefault()); ResolvedDockerHost dockerHost = ResolvedDockerHost - .from(new DockerHost("tcp://192.168.1.2:2376", true, "/test-cert-path")); + .from(new DockerHost("tcp://192.168.1.2:2376", true, "/test-cert-path")); RemoteHttpClientTransport transport = RemoteHttpClientTransport.createIfPossible(dockerHost, sslContextFactory); assertThat(transport.getHost()).satisfies(hostOf("https", "192.168.1.2", 2376)); } @@ -89,7 +89,7 @@ class RemoteHttpClientTransportTests { void createIfPossibleWhenTlsVerifyWithMissingCertPathThrowsException() { ResolvedDockerHost dockerHost = ResolvedDockerHost.from(new DockerHost("tcp://192.168.1.2:2376", true, null)); assertThatIllegalArgumentException().isThrownBy(() -> RemoteHttpClientTransport.createIfPossible(dockerHost)) - .withMessageContaining("Docker host TLS verification requires trust material"); + .withMessageContaining("Docker host TLS verification requires trust material"); } private Consumer hostOf(String scheme, String hostName, int port) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java index c8eb1783d8..3f0ec68cbe 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/BindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class BindingTests { @Test void ofWithNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.of(null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test @@ -49,13 +49,13 @@ class BindingTests { @Test void fromWithNullSourceThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.from((String) null, "container-dest")) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test void fromWithNullDestinationThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.from("host-src", null)) - .withMessageContaining("Destination must not be null"); + .withMessageContaining("Destination must not be null"); } @Test @@ -67,7 +67,7 @@ class BindingTests { @Test void fromVolumeNameSourceWithNullSourceThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Binding.from((VolumeName) null, "container-dest")) - .withMessageContaining("SourceVolume must not be null"); + .withMessageContaining("SourceVolume must not be null"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java index 4f63459d82..ce174809f0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ class ContainerConfigTests extends AbstractJsonTests { void ofWhenUpdateIsNullThrowsException() { ImageReference imageReference = ImageReference.of("ubuntu:bionic"); assertThatIllegalArgumentException().isThrownBy(() -> ContainerConfig.of(imageReference, null)) - .withMessage("Update must not be null"); + .withMessage("Update must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java index c5390ac1de..e6027da592 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -34,21 +34,21 @@ class ContainerContentTests { @Test void ofWhenArchiveIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ContainerContent.of(null)) - .withMessage("Archive must not be null"); + .withMessage("Archive must not be null"); } @Test void ofWhenDestinationPathIsNullThrowsException() { TarArchive archive = mock(TarArchive.class); assertThatIllegalArgumentException().isThrownBy(() -> ContainerContent.of(archive, null)) - .withMessage("DestinationPath must not be empty"); + .withMessage("DestinationPath must not be empty"); } @Test void ofWhenDestinationPathIsEmptyThrowsException() { TarArchive archive = mock(TarArchive.class); assertThatIllegalArgumentException().isThrownBy(() -> ContainerContent.of(archive, "")) - .withMessage("DestinationPath must not be empty"); + .withMessage("DestinationPath must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java index 6a66134b3e..41d4767234 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ContainerReferenceTests.java @@ -31,30 +31,30 @@ class ContainerReferenceTests { @Test void ofCreatesInstance() { ContainerReference reference = ContainerReference - .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); assertThat(reference).hasToString("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); } @Test void ofWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ContainerReference.of(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void ofWhenEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ContainerReference.of("")) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test void hashCodeAndEquals() { ContainerReference r1 = ContainerReference - .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); ContainerReference r2 = ContainerReference - .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("92691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); ContainerReference r3 = ContainerReference - .of("02691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); + .of("02691aec176333f7ae890de9aaeeafef11166efcaa3908edf83eb44a5c943781"); assertThat(r1).hasSameHashCodeAs(r2); assertThat(r1).isEqualTo(r1).isEqualTo(r2).isNotEqualTo(r3); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java index 38eb2e6787..592e1abd76 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -68,9 +68,9 @@ class ImageConfigTests extends AbstractJsonTests { void updateWithLabelUpdatesLabels() throws Exception { ImageConfig imageConfig = getImageConfig(); ImageConfig updatedImageConfig = imageConfig - .copy((update) -> update.withLabel("io.buildpacks.stack.id", "test")); + .copy((update) -> update.withLabel("io.buildpacks.stack.id", "test")); assertThat(imageConfig.getLabels()).hasSize(4) - .contains(entry("io.buildpacks.stack.id", "org.cloudfoundry.stacks.cflinuxfs3")); + .contains(entry("io.buildpacks.stack.id", "org.cloudfoundry.stacks.cflinuxfs3")); assertThat(updatedImageConfig.getLabels()).hasSize(4).contains(entry("io.buildpacks.stack.id", "test")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java index cfcde5725a..717d165d40 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageNameTests.java @@ -118,7 +118,7 @@ class ImageNameTests { @Test void ofWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageName.of(null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -129,20 +129,23 @@ class ImageNameTests { @Test void ofWhenContainsUppercaseThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageName.of("Test")) - .withMessageContaining("Unable to parse name").withMessageContaining("Test"); + .withMessageContaining("Unable to parse name") + .withMessageContaining("Test"); } @Test void ofWhenNameIncludesTagThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageName.of("ubuntu:latest")) - .withMessageContaining("Unable to parse name").withMessageContaining(":latest"); + .withMessageContaining("Unable to parse name") + .withMessageContaining(":latest"); } @Test void ofWhenNameIncludeDigestThrowsException() { assertThatIllegalArgumentException().isThrownBy( () -> ImageName.of("ubuntu@sha256:47bfdb88c3ae13e488167607973b7688f69d9e8c142c2045af343ec199649c09")) - .withMessageContaining("Unable to parse name").withMessageContaining("@sha256:47b"); + .withMessageContaining("Unable to parse name") + .withMessageContaining("@sha256:47b"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java index 158c6a9d0c..97fa86d1d1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageReferenceTests.java @@ -115,12 +115,12 @@ class ImageReferenceTests { @Test void ofNameAndDigest() { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.getDomain()).isEqualTo("docker.io"); assertThat(reference.getName()).isEqualTo("library/ubuntu"); assertThat(reference.getTag()).isNull(); assertThat(reference.getDigest()) - .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference).hasToString( "docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } @@ -128,25 +128,25 @@ class ImageReferenceTests { @Test void ofNameAndTagAndDigest() { ImageReference reference = ImageReference - .of("ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.getDomain()).isEqualTo("docker.io"); assertThat(reference.getName()).isEqualTo("library/ubuntu"); assertThat(reference.getTag()).isEqualTo("bionic"); assertThat(reference.getDigest()) - .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference).hasToString( "docker.io/library/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } @Test void ofCustomDomainAndPortWithTag() { - ImageReference reference = ImageReference.of( - "example.com:8080/canonical/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + ImageReference reference = ImageReference + .of("example.com:8080/canonical/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.getDomain()).isEqualTo("example.com:8080"); assertThat(reference.getName()).isEqualTo("canonical/ubuntu"); assertThat(reference.getTag()).isEqualTo("bionic"); assertThat(reference.getDigest()) - .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .isEqualTo("sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference).hasToString( "example.com:8080/canonical/ubuntu:bionic@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } @@ -174,9 +174,9 @@ class ImageReferenceTests { @Test void ofWhenHasIllegalCharacter() { assertThatIllegalArgumentException() - .isThrownBy(() -> ImageReference - .of("registry.example.com/example/example-app:1.6.0-dev.2.uncommitted+wip.foo.c75795d")) - .withMessageContaining("Unable to parse image reference"); + .isThrownBy(() -> ImageReference + .of("registry.example.com/example/example-app:1.6.0-dev.2.uncommitted+wip.foo.c75795d")) + .withMessageContaining("Unable to parse image reference"); } @Test @@ -219,15 +219,16 @@ class ImageReferenceTests { @Test void randomWherePrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> ImageReference.random(null)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test void inTaggedFormWhenHasDigestThrowsException() { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); - assertThatIllegalStateException().isThrownBy(() -> reference.inTaggedForm()).withMessage( - "Image reference 'docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d' cannot contain a digest"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + assertThatIllegalStateException().isThrownBy(() -> reference.inTaggedForm()) + .withMessage( + "Image reference 'docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d' cannot contain a digest"); } @Test @@ -245,7 +246,7 @@ class ImageReferenceTests { @Test void inTaggedOrDigestFormWhenHasDigestUsesDigest() { ImageReference reference = ImageReference - .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); + .of("ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); assertThat(reference.inTaggedOrDigestForm()).hasToString( "docker.io/library/ubuntu@sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java index d1551f7de3..2826fc1f13 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/ImageTests.java @@ -56,9 +56,9 @@ class ImageTests extends AbstractJsonTests { List layers = image.getLayers(); assertThat(layers).hasSize(46); assertThat(layers.get(0)) - .hasToString("sha256:733a8e5ce32984099ef675fce04730f6e2a6dcfdf5bd292fea01a8f936265342"); + .hasToString("sha256:733a8e5ce32984099ef675fce04730f6e2a6dcfdf5bd292fea01a8f936265342"); assertThat(layers.get(45)) - .hasToString("sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef"); + .hasToString("sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java index 337134a4c2..d910d0f8f9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerIdTests.java @@ -52,7 +52,7 @@ class LayerIdTests { @Test void ofWhenValueIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LayerId.of((String) null)) - .withMessage("Value must not be empty"); + .withMessage("Value must not be empty"); } @Test @@ -80,13 +80,13 @@ class LayerIdTests { @Test void ofSha256DigestWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LayerId.ofSha256Digest((byte[]) null)) - .withMessage("Digest must not be null"); + .withMessage("Digest must not be null"); } @Test void ofSha256DigestWhenWrongLengthThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> LayerId.ofSha256Digest(new byte[31])) - .withMessage("Digest must be exactly 32 bytes"); + .withMessage("Digest must be exactly 32 bytes"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java index 569056479c..db72d542c7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/LayerTests.java @@ -40,13 +40,13 @@ class LayerTests { @Test void ofWhenLayoutIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Layer.of((IOConsumer) null)) - .withMessage("Layout must not be null"); + .withMessage("Layout must not be null"); } @Test void fromTarArchiveWhenTarArchiveIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Layer.fromTarArchive(null)) - .withMessage("TarArchive must not be null"); + .withMessage("TarArchive must not be null"); } @Test @@ -56,7 +56,7 @@ class LayerTests { layout.file("/directory/file", Owner.ROOT, Content.of("test")); }); assertThat(layer.getId()) - .hasToString("sha256:d03a34f73804698c875eb56ff694fc2fceccc69b645e4adceb004ed13588613b"); + .hasToString("sha256:d03a34f73804698c875eb56ff694fc2fceccc69b645e4adceb004ed13588613b"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); layer.writeTo(outputStream); try (TarArchiveInputStream tarStream = new TarArchiveInputStream( diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java index 8305239a9f..aa9284485d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/RandomStringTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -31,7 +31,7 @@ class RandomStringTests { @Test void generateWhenPrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> RandomString.generate(null, 10)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java index 7545ed8487..90bafa796e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/type/VolumeNameTests.java @@ -31,7 +31,7 @@ class VolumeNameTests { @Test void randomWhenPrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.random(null)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test @@ -57,25 +57,25 @@ class VolumeNameTests { @Test void basedOnWhenSourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn(null, "prefix", "suffix", 6)) - .withMessage("Source must not be null"); + .withMessage("Source must not be null"); } @Test void basedOnWhenNameExtractorIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("test", null, "prefix", "suffix", 6)) - .withMessage("NameExtractor must not be null"); + .withMessage("NameExtractor must not be null"); } @Test void basedOnWhenPrefixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("test", null, "suffix", 6)) - .withMessage("Prefix must not be null"); + .withMessage("Prefix must not be null"); } @Test void basedOnWhenSuffixIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("test", "prefix", null, 6)) - .withMessage("Suffix must not be null"); + .withMessage("Suffix must not be null"); } @Test @@ -87,13 +87,13 @@ class VolumeNameTests { @Test void basedOnWhenSizeIsTooBigThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.basedOn("name", "prefix", "suffix", 33)) - .withMessage("DigestLength must be less than or equal to 32"); + .withMessage("DigestLength must be less than or equal to 32"); } @Test void ofWhenValueIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> VolumeName.of(null)) - .withMessage("Value must not be null"); + .withMessage("Value must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java index 5dd9e14873..cb9a8eb1f2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class ContentTests { @Test void ofWhenStreamIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Content.of(1, (IOSupplier) null)) - .withMessage("Supplier must not be null"); + .withMessage("Supplier must not be null"); } @Test @@ -51,7 +51,7 @@ class ContentTests { @Test void ofWhenStringIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Content.of((String) null)) - .withMessage("String must not be null"); + .withMessage("String must not be null"); } @Test @@ -63,7 +63,7 @@ class ContentTests { @Test void ofWhenBytesIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Content.of((byte[]) null)) - .withMessage("Bytes must not be null"); + .withMessage("Bytes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java index 2e14fcd36a..dd22a25b7c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java @@ -51,7 +51,7 @@ class FilePermissionsTests { @DisabledOnOs(OS.WINDOWS) void umaskForPath() throws IOException { FileAttribute> fileAttribute = PosixFilePermissions - .asFileAttribute(PosixFilePermissions.fromString("rw-r-----")); + .asFileAttribute(PosixFilePermissions.fromString("rw-r-----")); Path tempFile = Files.createTempFile(this.tempDir, "umask", null, fileAttribute); assertThat(FilePermissions.umaskForPath(tempFile)).isEqualTo(0640); } @@ -60,7 +60,7 @@ class FilePermissionsTests { @DisabledOnOs(OS.WINDOWS) void umaskForPathWithNonExistentFile() { assertThatIOException() - .isThrownBy(() -> FilePermissions.umaskForPath(Paths.get(this.tempDir.toString(), "does-not-exist"))); + .isThrownBy(() -> FilePermissions.umaskForPath(Paths.get(this.tempDir.toString(), "does-not-exist"))); } @Test @@ -68,7 +68,7 @@ class FilePermissionsTests { void umaskForPathOnWindowsFails() throws IOException { Path tempFile = Files.createTempFile("umask", null); assertThatIllegalStateException().isThrownBy(() -> FilePermissions.umaskForPath(tempFile)) - .withMessageContaining("Unsupported file type for retrieving Posix attributes"); + .withMessageContaining("Unsupported file type for retrieving Posix attributes"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java index 9997291847..dfbf2483ba 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/InspectedContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -39,19 +39,19 @@ class InspectedContentTests { @Test void ofWhenInputStreamThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> InspectedContent.of((InputStream) null)) - .withMessage("InputStream must not be null"); + .withMessage("InputStream must not be null"); } @Test void ofWhenContentIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> InspectedContent.of((Content) null)) - .withMessage("Content must not be null"); + .withMessage("Content must not be null"); } @Test void ofWhenConsumerIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> InspectedContent.of((IOConsumer) null)) - .withMessage("Writer must not be null"); + .withMessage("Writer must not be null"); } @Test @@ -85,9 +85,9 @@ class InspectedContentTests { InputStream inputStream = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)); MessageDigest digest = MessageDigest.getInstance("SHA-256"); InspectedContent.of(inputStream, digest::update); - assertThat(digest.digest()).inHexadecimal().contains(0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65, 0x9a, 0x2f, - 0xea, 0xa0, 0xc5, 0x5a, 0xd0, 0x15, 0xa3, 0xbf, 0x4f, 0x1b, 0x2b, 0x0b, 0x82, 0x2c, 0xd1, 0x5d, 0x6c, - 0x15, 0xb0, 0xf0, 0x0a, 0x08); + assertThat(digest.digest()).inHexadecimal() + .contains(0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65, 0x9a, 0x2f, 0xea, 0xa0, 0xc5, 0x5a, 0xd0, 0x15, + 0xa3, 0xbf, 0x4f, 0x1b, 0x2b, 0x0b, 0x82, 0x2c, 0xd1, 0x5d, 0x6c, 0x15, 0xb0, 0xf0, 0x0a, 0x08); } private byte[] readBytes(InspectedContent content) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java index 23ae04ae54..cd11ef3929 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/ZipFileTarArchiveTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ class ZipFileTarArchiveTests { @Test void createWhenZipIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ZipFileTarArchive(null, Owner.ROOT)) - .withMessage("Zip must not be null"); + .withMessage("Zip must not be null"); } @Test @@ -54,7 +54,7 @@ class ZipFileTarArchiveTests { File file = new File(this.tempDir, "test.zip"); writeTestZip(file); assertThatIllegalArgumentException().isThrownBy(() -> new ZipFileTarArchive(file, null)) - .withMessage("Owner must not be null"); + .withMessage("Owner must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java index 7065adeba8..edc27b5554 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/AbstractJsonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ public abstract class AbstractJsonTests { protected final String getContentAsString(String name) { return new BufferedReader(new InputStreamReader(getContent(name), StandardCharsets.UTF_8)).lines() - .collect(Collectors.joining("\n")); + .collect(Collectors.joining("\n")); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java index b445f9174a..23ae5f3b9f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/JsonStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class JsonStreamTests extends AbstractJsonTests { this.jsonStream.get(getContent("stream.json"), result::add); assertThat(result).hasSize(595); assertThat(result.get(594).toString()) - .contains("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); + .contains("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); } @Test @@ -55,7 +55,7 @@ class JsonStreamTests extends AbstractJsonTests { assertThat(result).hasSize(595); assertThat(result.get(1).getId()).isEqualTo("5667fdb72017"); assertThat(result.get(594).getStatus()) - .isEqualTo("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); + .isEqualTo("Status: Downloaded newer image for paketo-buildpacks/cnb:base"); } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java index 16a7b2844d..32f9a9d13d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/SharedObjectMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -38,13 +38,13 @@ class SharedObjectMapperTests { assertThat(mapper).isNotNull(); assertThat(mapper.getRegisteredModuleIds()).contains(new ParameterNamesModule().getTypeId()); assertThat(SerializationFeature.INDENT_OUTPUT - .enabledIn(mapper.getSerializationConfig().getSerializationFeatures())).isTrue(); + .enabledIn(mapper.getSerializationConfig().getSerializationFeatures())).isTrue(); assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES - .enabledIn(mapper.getDeserializationConfig().getDeserializationFeatures())).isFalse(); + .enabledIn(mapper.getDeserializationConfig().getDeserializationFeatures())).isFalse(); assertThat(mapper.getSerializationConfig().getPropertyNamingStrategy()) - .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); + .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); assertThat(mapper.getDeserializationConfig().getPropertyNamingStrategy()) - .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); + .isEqualTo(PropertyNamingStrategies.LOWER_CAMEL_CASE); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java index ba9689db8e..fa950ddc86 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/intTest/java/org/springframework/boot/cli/infrastructure/CommandLineInvoker.java @@ -132,9 +132,9 @@ public final class CommandLineInvoker { public Invocation(Process process) { this.process = process; this.streamReaders - .add(new Thread(new StreamReadingRunnable(this.process.getErrorStream(), this.err, this.combined))); + .add(new Thread(new StreamReadingRunnable(this.process.getErrorStream(), this.err, this.combined))); this.streamReaders - .add(new Thread(new StreamReadingRunnable(this.process.getInputStream(), this.out, this.combined))); + .add(new Thread(new StreamReadingRunnable(this.process.getInputStream(), this.out, this.combined))); for (Thread streamReader : this.streamReaders) { streamReader.start(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java index 5a4723b1c7..3360b402d9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,7 +40,7 @@ import org.springframework.util.StringUtils; public class CommandRunner implements Iterable { private static final Set NO_EXCEPTION_OPTIONS = EnumSet - .noneOf(CommandException.Option.class); + .noneOf(CommandException.Option.class); private final String name; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java index 9145721941..6475e6f52e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,8 +70,8 @@ public class EncodePasswordCommand extends OptionParsingCommand { @Override public Collection getExamples() { List examples = new ArrayList<>(); - examples.add( - new HelpExample("To encode a password with the default encoder", "spring encodepassword mypassword")); + examples + .add(new HelpExample("To encode a password with the default encoder", "spring encodepassword mypassword")); examples.add(new HelpExample("To encode a password with pbkdf2", "spring encodepassword -a pbkdf2 mypassword")); return examples; } @@ -83,7 +83,7 @@ public class EncodePasswordCommand extends OptionParsingCommand { @Override protected void options() { this.algorithm = option(Arrays.asList("algorithm", "a"), "The algorithm to use").withRequiredArg() - .defaultsTo("default"); + .defaultsTo("default"); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java index ba32bb0311..87796f9342 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -139,7 +139,7 @@ public class InitCommand extends OptionParsingCommand { @Override protected void options() { this.target = option(Arrays.asList("target"), "URL of the service to use").withRequiredArg() - .defaultsTo(ProjectGenerationRequest.DEFAULT_SERVICE_URL); + .defaultsTo(ProjectGenerationRequest.DEFAULT_SERVICE_URL); this.listCapabilities = option(Arrays.asList("list"), "List the capabilities of the service. Use it to discover the " + "dependencies and the types that are available"); @@ -149,33 +149,37 @@ public class InitCommand extends OptionParsingCommand { private void projectGenerationOptions() { this.groupId = option(Arrays.asList("group-id", "g"), "Project coordinates (for example 'org.test')") - .withRequiredArg(); + .withRequiredArg(); this.artifactId = option(Arrays.asList("artifact-id", "a"), - "Project coordinates; infer archive name (for example 'test')").withRequiredArg(); + "Project coordinates; infer archive name (for example 'test')") + .withRequiredArg(); this.version = option(Arrays.asList("version", "v"), "Project version (for example '0.0.1-SNAPSHOT')") - .withRequiredArg(); + .withRequiredArg(); this.name = option(Arrays.asList("name", "n"), "Project name; infer application name").withRequiredArg(); this.description = option("description", "Project description").withRequiredArg(); this.packageName = option(Arrays.asList("package-name"), "Package name").withRequiredArg(); this.type = option(Arrays.asList("type", "t"), "Project type. Not normally needed if you use --build " + "and/or --format. Check the capabilities of the service (--list) for more details") - .withRequiredArg(); + .withRequiredArg(); this.packaging = option(Arrays.asList("packaging", "p"), "Project packaging (for example 'jar')") - .withRequiredArg(); + .withRequiredArg(); this.build = option("build", "Build system to use (for example 'maven' or 'gradle')").withRequiredArg() - .defaultsTo("maven"); + .defaultsTo("maven"); this.format = option("format", "Format of the generated content (for example 'build' for a build file, " - + "'project' for a project archive)").withRequiredArg().defaultsTo("project"); + + "'project' for a project archive)") + .withRequiredArg() + .defaultsTo("project"); this.javaVersion = option(Arrays.asList("java-version", "j"), "Language level (for example '1.8')") - .withRequiredArg(); + .withRequiredArg(); this.language = option(Arrays.asList("language", "l"), "Programming language (for example 'java')") - .withRequiredArg(); + .withRequiredArg(); this.bootVersion = option(Arrays.asList("boot-version", "b"), - "Spring Boot version (for example '1.2.0.RELEASE')").withRequiredArg(); + "Spring Boot version (for example '1.2.0.RELEASE')") + .withRequiredArg(); this.dependencies = option(Arrays.asList("dependencies", "d"), "Comma-separated list of dependency identifiers to include in the generated project") - .withRequiredArg(); + .withRequiredArg(); } private void otherOptions() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java index 1409ab16bb..4f018fa789 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -152,7 +152,7 @@ public class OptionHandler { @Override public String format(Map options) { Comparator comparator = Comparator - .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); + .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); Set sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java index 1354839756..73dd58ef66 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -114,7 +114,7 @@ public class Shell { this.consoleReader.setBellEnabled(false); this.consoleReader.setExpandEvents(false); this.consoleReader - .addCompleter(new CommandCompleter(this.consoleReader, this.argumentDelimiter, this.commandRunner)); + .addCompleter(new CommandCompleter(this.consoleReader, this.argumentDelimiter, this.commandRunner)); this.consoleReader.setCompletionHandler(new CandidateListCompletionHandler()); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java index 292a17832c..8de77a0b26 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java @@ -160,7 +160,7 @@ class CommandRunnerTests { @Test void exceptionMessages() { assertThat(new NoSuchCommandException("name").getMessage()) - .isEqualTo("'name' is not a valid command. See 'help'."); + .isEqualTo("'name' is not a valid command. See 'help'."); } @Test @@ -172,13 +172,13 @@ class CommandRunnerTests { @Test void helpNoCommand() { assertThatExceptionOfType(NoHelpCommandArgumentsException.class) - .isThrownBy(() -> this.commandRunner.run("help")); + .isThrownBy(() -> this.commandRunner.run("help")); } @Test void helpUnknownCommand() { assertThatExceptionOfType(NoSuchCommandException.class) - .isThrownBy(() -> this.commandRunner.run("help", "missing")); + .isThrownBy(() -> this.commandRunner.run("help", "missing")); } private enum Call { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java index 37f12c4243..8820f76255 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/encodepassword/EncodePasswordCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ class EncodePasswordCommandTests { then(this.log).should().info(this.message.capture()); assertThat(this.message.getValue()).startsWith("{bcrypt}"); assertThat(PasswordEncoderFactories.createDelegatingPasswordEncoder().matches("boot", this.message.getValue())) - .isTrue(); + .isTrue(); assertThat(status).isEqualTo(ExitStatus.OK); } @@ -84,7 +84,7 @@ class EncodePasswordCommandTests { then(this.log).should().info(this.message.capture()); assertThat(this.message.getValue()).doesNotStartWith("{"); assertThat(Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8().matches("boot", this.message.getValue())) - .isTrue(); + .isTrue(); assertThat(status).isEqualTo(ExitStatus.OK); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java index a0d1d819a0..496e710e14 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -77,7 +77,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { ProjectGenerationRequest request = new ProjectGenerationRequest(); request.getDependencies().add("foo:bar"); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining(jsonMessage); + .withMessageContaining(jsonMessage); } @Test @@ -85,7 +85,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { mockProjectGenerationError(400, null); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("unexpected 400 error"); + .withMessageContaining("unexpected 400 error"); } @Test @@ -96,7 +96,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("No content received from server"); + .withMessageContaining("No content received from server"); } @Test @@ -105,7 +105,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { mockMetadataGetError(500, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining(jsonMessage); + .withMessageContaining(jsonMessage); } @Test @@ -116,7 +116,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("Invalid content received from server"); + .withMessageContaining("Invalid content received from server"); } @Test @@ -126,7 +126,7 @@ class InitializrServiceTests extends AbstractHttpClientMockTests { given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.invoker.generate(request)) - .withMessageContaining("No content received from server"); + .withMessageContaining("No content received from server"); } private ProjectGenerationResponse generateProject(ProjectGenerationRequest request, diff --git a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java index 7b05b9a914..151b40c248 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,21 +57,21 @@ class ProjectGenerationRequestTests { this.request.setServiceUrl(customServerUrl); this.request.getDependencies().add("security"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type")); + .isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type")); } @Test void customBootVersion() { this.request.setBootVersion("1.2.0.RELEASE"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&bootVersion=1.2.0.RELEASE")); + .isEqualTo(createDefaultUrl("?type=test-type&bootVersion=1.2.0.RELEASE")); } @Test void singleDependency() { this.request.getDependencies().add("web"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?dependencies=web&type=test-type")); + .isEqualTo(createDefaultUrl("?dependencies=web&type=test-type")); } @Test @@ -79,21 +79,21 @@ class ProjectGenerationRequestTests { this.request.getDependencies().add("web"); this.request.getDependencies().add("data-jpa"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); + .isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type")); } @Test void customJavaVersion() { this.request.setJavaVersion("1.8"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&javaVersion=1.8")); + .isEqualTo(createDefaultUrl("?type=test-type&javaVersion=1.8")); } @Test void customPackageName() { this.request.setPackageName("demo.foo"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?packageName=demo.foo&type=test-type")); + .isEqualTo(createDefaultUrl("?packageName=demo.foo&type=test-type")); } @Test @@ -110,14 +110,14 @@ class ProjectGenerationRequestTests { void customPackaging() { this.request.setPackaging("war"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&packaging=war")); + .isEqualTo(createDefaultUrl("?type=test-type&packaging=war")); } @Test void customLanguage() { this.request.setLanguage("groovy"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?type=test-type&language=groovy")); + .isEqualTo(createDefaultUrl("?type=test-type&language=groovy")); } @Test @@ -127,29 +127,29 @@ class ProjectGenerationRequestTests { this.request.setVersion("1.0.1-SNAPSHOT"); this.request.setDescription("Spring Boot Test"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" - + "&description=Spring+Boot+Test&type=test-type")); + .isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT" + + "&description=Spring+Boot+Test&type=test-type")); } @Test void outputCustomizeArtifactId() { this.request.setOutput("my-project"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test void outputArchiveCustomizeArtifactId() { this.request.setOutput("my-project.zip"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my-project&type=test-type")); } @Test void outputArchiveWithDotsCustomizeArtifactId() { this.request.setOutput("my.nice.project.zip"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type")); } @Test @@ -157,7 +157,7 @@ class ProjectGenerationRequestTests { this.request.setOutput("my-project"); this.request.setArtifactId("my-id"); assertThat(this.request.generateUrl(createDefaultMetadata())) - .isEqualTo(createDefaultUrl("?artifactId=my-id&type=test-type")); + .isEqualTo(createDefaultUrl("?artifactId=my-id&type=test-type")); } @Test @@ -165,7 +165,7 @@ class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("does-not-exist", null); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) - .withMessageContaining("does-not-exist"); + .withMessageContaining("does-not-exist"); } @Test @@ -173,7 +173,8 @@ class ProjectGenerationRequestTests { InitializrServiceMetadata metadata = readMetadata("types-conflict"); setBuildAndFormat("gradle", null); assertThatExceptionOfType(ReportableException.class).isThrownBy(() -> this.request.generateUrl(metadata)) - .withMessageContaining("gradle-project").withMessageContaining("gradle-project-2"); + .withMessageContaining("gradle-project") + .withMessageContaining("gradle-project-2"); } @Test @@ -195,14 +196,14 @@ class ProjectGenerationRequestTests { void invalidType() { this.request.setType("does-not-exist"); assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.request.generateUrl(createDefaultMetadata())); + .isThrownBy(() -> this.request.generateUrl(createDefaultMetadata())); } @Test void noTypeAndNoDefault() { assertThatExceptionOfType(ReportableException.class) - .isThrownBy(() -> this.request.generateUrl(readMetadata("types-conflict"))) - .withMessageContaining("no default is defined"); + .isThrownBy(() -> this.request.generateUrl(readMetadata("types-conflict"))) + .withMessageContaining("no default is defined"); } private static URI createUrl(String actionAndParam) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java index 954f46fc49..3a9147dea8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/RawConfigurationMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -52,9 +52,10 @@ class RawConfigurationMetadata { return null; } return this.sources.stream() - .filter((candidate) -> item.getSourceType().equals(candidate.getType()) - && item.getId().startsWith(candidate.getGroupId())) - .max(Comparator.comparingInt((candidate) -> candidate.getGroupId().length())).orElse(null); + .filter((candidate) -> item.getSourceType().equals(candidate.getType()) + && item.getId().startsWith(candidate.getGroupId())) + .max(Comparator.comparingInt((candidate) -> candidate.getGroupId().length())) + .orElse(null); } List getItems() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index 5b4d03a0de..1670a8b424 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -36,7 +36,7 @@ class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurat @Test void nullResource() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null)); + .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null)); } @Test @@ -105,7 +105,7 @@ class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurat assertThat(group.getSources().get("org.acme.Foo2").getProperties()).containsOnlyKeys("spring.foo.enabled", "spring.foo.type"); assertThat(group.getSources().get("org.springframework.boot.FooProperties").getProperties()) - .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); + .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); } } @@ -123,7 +123,7 @@ class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurat assertThat(group.getSources().get("org.acme.Foo").getProperties()).containsOnlyKeys("spring.foo.name", "spring.foo.description", "spring.foo.enabled", "spring.foo.type"); assertThat(group.getSources().get("org.springframework.boot.FooProperties").getProperties()) - .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); + .containsOnlyKeys("spring.foo.name", "spring.foo.counter"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java index b5dcc4b6b6..09760d3fad 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java @@ -94,7 +94,7 @@ class JsonReaderTests extends AbstractConfigurationMetadataTests { ValueHint valueHint = hint.getValueHints().get(0); assertThat(valueHint.getValue()).isEqualTo(42); assertThat(valueHint.getDescription()) - .isEqualTo("Because that's the answer to any question, choose it. \nReally."); + .isEqualTo("Because that's the answer to any question, choose it. \nReally."); assertThat(valueHint.getShortDescription()).isEqualTo("Because that's the answer to any question, choose it."); assertThat(hint.getValueProviders()).hasSize(1); ValueProvider valueProvider = hint.getValueProviders().get(0); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java index f6ce063c5a..50f41cf6af 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/SentenceExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,14 +40,14 @@ class SentenceExtractorTests { @Test void extractFirstSentenceNewLineBeforeDot() { String sentence = this.extractor - .getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); + .getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } @Test void extractFirstSentenceNewLineBeforeDotWithSpaces() { String sentence = this.extractor - .getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); + .getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); assertThat(sentence).isEqualTo("My short description."); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java index e0180ba8ce..6c805144a8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -103,7 +103,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor static final String AUTO_CONFIGURATION_ANNOTATION = "org.springframework.boot.autoconfigure.AutoConfiguration"; private static final Set SUPPORTED_OPTIONS = Collections - .unmodifiableSet(Collections.singleton(ADDITIONAL_METADATA_LOCATIONS_OPTION)); + .unmodifiableSet(Collections.singleton(ADDITIONAL_METADATA_LOCATIONS_OPTION)); private MetadataStore metadataStore; @@ -241,8 +241,9 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor this.metadataEnv.getTypeUtils().getQualifiedName(element.getEnclosingElement()), element.toString()); if (this.metadataCollector.hasSimilarGroup(group)) { - this.processingEnv.getMessager().printMessage(Kind.ERROR, - "Duplicate @ConfigurationProperties definition for prefix '" + prefix + "'", element); + this.processingEnv.getMessager() + .printMessage(Kind.ERROR, + "Duplicate @ConfigurationProperties definition for prefix '" + prefix + "'", element); } else { this.metadataCollector.add(group); @@ -260,7 +261,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor this.metadataCollector.add(descriptor.resolveItemMetadata(prefix, this.metadataEnv)); if (descriptor.isNested(this.metadataEnv)) { TypeElement nestedTypeElement = (TypeElement) this.metadataEnv.getTypeUtils() - .asElement(descriptor.getType()); + .asElement(descriptor.getType()); String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, descriptor.getName()); processTypeElement(nestedPrefix, nestedTypeElement, source, seen); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java index b83d784e1c..5109ffed45 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -275,7 +275,7 @@ class MetadataGenerationEnvironment { Map getAnnotationElementValues(AnnotationMirror annotation) { Map values = new LinkedHashMap<>(); annotation.getElementValues() - .forEach((name, value) -> values.put(name.getSimpleName().toString(), getAnnotationValue(value))); + .forEach((name, value) -> values.put(name.getSimpleName().toString(), getAnnotationValue(value))); return values; } @@ -306,8 +306,10 @@ class MetadataGenerationEnvironment { } Set getEndpointAnnotationElements() { - return this.endpointAnnotations.stream().map(this.elements::getTypeElement).filter(Objects::nonNull) - .collect(Collectors.toSet()); + return this.endpointAnnotations.stream() + .map(this.elements::getTypeElement) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); } AnnotationMirror getReadOperationAnnotation(Element element) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java index 826c504b02..31ba670d7c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -100,8 +100,8 @@ public class MetadataStore { private InputStream getAdditionalMetadataStream() throws IOException { // Most build systems will have copied the file to the class output location - FileObject fileObject = this.environment.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", - ADDITIONAL_METADATA_PATH); + FileObject fileObject = this.environment.getFiler() + .getResource(StandardLocation.CLASS_OUTPUT, "", ADDITIONAL_METADATA_PATH); InputStream inputStream = getMetadataStream(fileObject); if (inputStream != null) { return inputStream; @@ -129,7 +129,7 @@ public class MetadataStore { return standardLocation; } String locations = this.environment.getOptions() - .get(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION); + .get(ConfigurationMetadataAnnotationProcessor.ADDITIONAL_METADATA_LOCATIONS_OPTION); if (locations != null) { for (String location : locations.split(",")) { File candidate = new File(location, ADDITIONAL_METADATA_PATH); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java index e625be9453..7f94f1667b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -234,7 +234,8 @@ class TypeUtils { if (type.getKind() == TypeKind.DECLARED) { DeclaredType declaredType = (DeclaredType) type; DeclaredType freshType = (DeclaredType) this.env.getElementUtils() - .getTypeElement(this.types.asElement(type).toString()).asType(); + .getTypeElement(this.types.asElement(type).toString()) + .asType(); List arguments = declaredType.getTypeArguments(); for (int i = 0; i < arguments.size(); i++) { TypeMirror specificType = arguments.get(i); @@ -267,9 +268,12 @@ class TypeUtils { } StringBuilder name = new StringBuilder(); name.append(qualifiedName); - name.append("<").append( - type.getTypeArguments().stream().map((t) -> visit(t, descriptor)).collect(Collectors.joining(","))) - .append(">"); + name.append("<") + .append(type.getTypeArguments() + .stream() + .map((t) -> visit(t, descriptor)) + .collect(Collectors.joining(","))) + .append(">"); return name.toString(); } @@ -365,14 +369,19 @@ class TypeUtils { } TypeMirror resolveGeneric(String parameterName) { - return this.generics.entrySet().stream().filter((e) -> getParameterName(e.getKey()).equals(parameterName)) - .findFirst().map(Entry::getValue).orElse(null); + return this.generics.entrySet() + .stream() + .filter((e) -> getParameterName(e.getKey()).equals(parameterName)) + .findFirst() + .map(Entry::getValue) + .orElse(null); } private void registerIfNecessary(TypeMirror variable, TypeMirror resolution) { if (variable instanceof TypeVariable typeVariable) { - if (this.generics.keySet().stream() - .noneMatch((candidate) -> getParameterName(candidate).equals(getParameterName(typeVariable)))) { + if (this.generics.keySet() + .stream() + .noneMatch((candidate) -> getParameterName(candidate).equals(getParameterName(typeVariable)))) { this.generics.put(typeVariable, resolution); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java index 4eb816385b..4c4cfda98a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,8 +38,11 @@ class JsonConverter { JSONArray toJsonArray(ConfigurationMetadata metadata, ItemType itemType) throws Exception { JSONArray jsonArray = new JSONArray(); - List items = metadata.getItems().stream().filter((item) -> item.isOfItemType(itemType)) - .sorted(ITEM_COMPARATOR).toList(); + List items = metadata.getItems() + .stream() + .filter((item) -> item.isOfItemType(itemType)) + .sorted(ITEM_COMPARATOR) + .toList(); for (ItemMetadata item : items) { if (item.isOfItemType(itemType)) { jsonArray.put(toJsonObject(item)); @@ -160,11 +163,11 @@ class JsonConverter { private static class ItemMetadataComparator implements Comparator { private static final Comparator GROUP = Comparator.comparing(ItemMetadata::getName) - .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); + .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); private static final Comparator ITEM = Comparator.comparing(ItemMetadataComparator::isDeprecated) - .thenComparing(ItemMetadata::getName) - .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); + .thenComparing(ItemMetadata::getName) + .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); @Override public int compare(ItemMetadata o1, ItemMetadata o2) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java index bfdb5bf382..90198557e4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/AbstractMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,9 +43,10 @@ public abstract class AbstractMetadataGenerationTests { } protected ConfigurationMetadata compile(String additionalMetadata, Class type, Class... types) { - TestCompiler compiler = TestCompiler.forSystem().withSources(sourceFilesOf(type)) - .withSources(sourceFilesOf(types)) - .withResources(ResourceFile.of(ADDITIONAL_METADATA_FILE, additionalMetadata)); + TestCompiler compiler = TestCompiler.forSystem() + .withSources(sourceFilesOf(type)) + .withSources(sourceFilesOf(types)) + .withResources(ResourceFile.of(ADDITIONAL_METADATA_FILE, additionalMetadata)); return compile(compiler); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index ccd5d8676f..93227ecf61 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -79,15 +79,15 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene @Test void supportedAnnotations() { assertThat(new ConfigurationMetadataAnnotationProcessor().getSupportedAnnotationTypes()) - .containsExactlyInAnyOrder("org.springframework.boot.autoconfigure.AutoConfiguration", - "org.springframework.boot.context.properties.ConfigurationProperties", - "org.springframework.context.annotation.Configuration", - "org.springframework.boot.actuate.endpoint.annotation.Endpoint", - "org.springframework.boot.actuate.endpoint.jmx.annotation.JmxEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint", - "org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint"); + .containsExactlyInAnyOrder("org.springframework.boot.autoconfigure.AutoConfiguration", + "org.springframework.boot.context.properties.ConfigurationProperties", + "org.springframework.context.annotation.Configuration", + "org.springframework.boot.actuate.endpoint.annotation.Endpoint", + "org.springframework.boot.actuate.endpoint.jmx.annotation.JmxEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint", + "org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint"); } @Test @@ -101,10 +101,15 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(SimpleProperties.class); assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).withDefaultValue(false) - .fromSource(SimpleProperties.class).withDescription("A simple flag.").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(SimpleProperties.class) + .withDescription("A simple flag.") + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("simple.comparator")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.counter")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.size")); @@ -115,7 +120,7 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class); assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimplePrefixValueProperties.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.name", String.class).fromSource(SimplePrefixValueProperties.class)); + .has(Metadata.withProperty("simple.name", String.class).fromSource(SimplePrefixValueProperties.class)); } @Test @@ -125,21 +130,21 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene assertThat(metadata).has(Metadata.withProperty("simple.type.my-string", String.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-byte", Byte.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-char", Character.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-char", Character.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-boolean", Boolean.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class).withDefaultValue(false)); + .has(Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class).withDefaultValue(false)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-short", Short.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-short", Short.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-short", Short.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-integer", Integer.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-integer", Integer.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-long", Long.class)); assertThat(metadata) - .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class).withDefaultValue(0)); + .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class).withDefaultValue(0)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-double", Double.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-primitive-double", Double.class)); assertThat(metadata).has(Metadata.withProperty("simple.type.my-float", Float.class)); @@ -152,12 +157,15 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(HierarchicalProperties.class, HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class); assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class).withDefaultValue("one") - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.second", String.class).withDefaultValue("two") - .fromSource(HierarchicalProperties.class)); - assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class).withDefaultValue("three") - .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class) + .withDefaultValue("one") + .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.second", String.class) + .withDefaultValue("two") + .fromSource(HierarchicalProperties.class)); + assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class) + .withDefaultValue("three") + .fromSource(HierarchicalProperties.class)); } @Test @@ -165,10 +173,12 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(DescriptionProperties.class); assertThat(metadata).has(Metadata.withGroup("description").fromSource(DescriptionProperties.class)); assertThat(metadata).has(Metadata.withProperty("description.simple", String.class) - .fromSource(DescriptionProperties.class).withDescription("A simple description.")); + .fromSource(DescriptionProperties.class) + .withDescription("A simple description.")); assertThat(metadata).has(Metadata.withProperty("description.multi-line", String.class) - .fromSource(DescriptionProperties.class).withDescription( - "This is a lengthy description that spans across multiple lines to showcase that the line separators are cleaned automatically.")); + .fromSource(DescriptionProperties.class) + .withDescription( + "This is a lengthy description that spans across multiple lines to showcase that the line separators are cleaned automatically.")); } @Test @@ -177,10 +187,11 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type)); - assertThat(metadata).has( - Metadata.withProperty("deprecated.name", String.class).fromSource(type).withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("deprecated.description", String.class).fromSource(type) - .withDeprecation(null, null)); + assertThat(metadata) + .has(Metadata.withProperty("deprecated.name", String.class).fromSource(type).withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("deprecated.description", String.class) + .fromSource(type) + .withDeprecation(null, null)); } @Test @@ -189,8 +200,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("singledeprecated.new-name", String.class).fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class).fromSource(type) - .withDeprecation("renamed", "singledeprecated.new-name")); + assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class) + .fromSource(type) + .withDeprecation("renamed", "singledeprecated.new-name")); } @Test @@ -198,8 +210,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = DeprecatedFieldSingleProperty.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("singlefielddeprecated").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("singlefielddeprecated.name", String.class).fromSource(type) - .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("singlefielddeprecated.name", String.class) + .fromSource(type) + .withDeprecation(null, null)); } @Test @@ -207,10 +220,12 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = DeprecatedUnrelatedMethodPojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); - assertThat(metadata).has( - Metadata.withProperty("not.deprecated.counter", Integer.class).withNoDeprecation().fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class).withDefaultValue(false) - .withNoDeprecation().fromSource(type)); + assertThat(metadata) + .has(Metadata.withProperty("not.deprecated.counter", Integer.class).withNoDeprecation().fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class) + .withDefaultValue(false) + .withNoDeprecation() + .fromSource(type)); } @Test @@ -218,8 +233,10 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = DeprecatedLessPreciseTypePojo.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class).withDefaultValue(false) - .withNoDeprecation().fromSource(type)); + assertThat(metadata).has(Metadata.withProperty("not.deprecated.flag", Boolean.class) + .withDefaultValue(false) + .withNoDeprecation() + .fromSource(type)); } @Test @@ -227,8 +244,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene Class type = DeprecatedRecord.class; ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("deprecated-record").fromSource(type)); - assertThat(metadata).has(Metadata.withProperty("deprecated-record.alpha", String.class).fromSource(type) - .withDeprecation("some-reason", null)); + assertThat(metadata).has(Metadata.withProperty("deprecated-record.alpha", String.class) + .fromSource(type) + .withDeprecation("some-reason", null)); assertThat(metadata).has(Metadata.withProperty("deprecated-record.bravo", String.class).fromSource(type)); } @@ -238,7 +256,7 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type)); assertThat(metadata) - .has(Metadata.withProperty("boxing.flag", Boolean.class).withDefaultValue(false).fromSource(type)); + .has(Metadata.withProperty("boxing.flag", Boolean.class).withDefaultValue(false).fromSource(type)); assertThat(metadata).has(Metadata.withProperty("boxing.another-flag", Boolean.class).fromSource(type)); assertThat(metadata).has(Metadata.withProperty("boxing.counter", Integer.class).fromSource(type)); } @@ -268,8 +286,8 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene assertThat(metadata).has(Metadata.withProperty("array.simple", "java.lang.String[]")); assertThat(metadata).has(Metadata.withProperty("array.inner", "org.springframework.boot.configurationsample.simple.SimpleArrayProperties$Holder[]")); - assertThat(metadata).has( - Metadata.withProperty("array.name-to-integer", "java.util.Map[]")); + assertThat(metadata) + .has(Metadata.withProperty("array.name-to-integer", "java.util.Map[]")); assertThat(metadata.getItems()).hasSize(5); } @@ -278,7 +296,7 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(AnnotatedGetter.class); assertThat(metadata).has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class)); assertThat(metadata) - .has(Metadata.withProperty("specific.name", String.class).fromSource(AnnotatedGetter.class)); + .has(Metadata.withProperty("specific.name", String.class).fromSource(AnnotatedGetter.class)); } @Test @@ -286,9 +304,10 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(StaticAccessor.class); assertThat(metadata).has(Metadata.withGroup("specific").fromSource(StaticAccessor.class)); assertThat(metadata).has(Metadata.withProperty("specific.counter", Integer.class) - .fromSource(StaticAccessor.class).withDefaultValue(42)); + .fromSource(StaticAccessor.class) + .withDefaultValue(42)); assertThat(metadata) - .doesNotHave(Metadata.withProperty("specific.name", String.class).fromSource(StaticAccessor.class)); + .doesNotHave(Metadata.withProperty("specific.name", String.class).fromSource(StaticAccessor.class)); assertThat(metadata.getItems()).hasSize(2); } @@ -302,16 +321,17 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene void innerClassProperties() { ConfigurationMetadata metadata = compile(InnerClassProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(InnerClassProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first") + .ofType(InnerClassProperties.Foo.class) + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); assertThat(metadata).has(Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class) - .fromSource(InnerClassProperties.class)); + .fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.the-second.name")); assertThat(metadata).has(Metadata.withProperty("config.the-second.bar.name")); - assertThat(metadata).has( - Metadata.withGroup("config.third").ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); + assertThat(metadata) + .has(Metadata.withGroup("config.third").ofType(SimplePojo.class).fromSource(InnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.third.value")); assertThat(metadata).has(Metadata.withProperty("config.fourth")); assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth")); @@ -322,9 +342,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene ConfigurationMetadata metadata = compile(InnerClassHierarchicalProperties.class); assertThat(metadata).has(Metadata.withGroup("config.foo").ofType(InnerClassHierarchicalProperties.Foo.class)); assertThat(metadata) - .has(Metadata.withGroup("config.foo.bar").ofType(InnerClassHierarchicalProperties.Bar.class)); + .has(Metadata.withGroup("config.foo.bar").ofType(InnerClassHierarchicalProperties.Bar.class)); assertThat(metadata) - .has(Metadata.withGroup("config.foo.bar.baz").ofType(InnerClassHierarchicalProperties.Foo.Baz.class)); + .has(Metadata.withGroup("config.foo.bar.baz").ofType(InnerClassHierarchicalProperties.Foo.Baz.class)); assertThat(metadata).has(Metadata.withProperty("config.foo.bar.baz.blah")); assertThat(metadata).has(Metadata.withProperty("config.foo.bar.bling")); } @@ -340,12 +360,14 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene @Test void nestedClassChildProperties() { ConfigurationMetadata metadata = compile(ClassWithNestedProperties.class); - assertThat(metadata).has( - Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class)); + assertThat(metadata) + .has(Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class)); assertThat(metadata).has(Metadata.withProperty("nestedChildProps.child-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(20)); + .fromSource(ClassWithNestedProperties.NestedChildClass.class) + .withDefaultValue(20)); assertThat(metadata).has(Metadata.withProperty("nestedChildProps.parent-class-property", Integer.class) - .fromSource(ClassWithNestedProperties.NestedChildClass.class).withDefaultValue(10)); + .fromSource(ClassWithNestedProperties.NestedChildClass.class) + .withDefaultValue(10)); } @Test @@ -385,37 +407,40 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene @Test void invalidDoubleRegistration() { assertThatExceptionOfType(CompilationException.class) - .isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class)) - .withMessageContaining("Unable to compile source"); + .isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class)) + .withMessageContaining("Unable to compile source"); } @Test void constructorParameterPropertyWithInvalidDefaultValueOnNumber() { assertThatExceptionOfType(CompilationException.class) - .isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class)) - .withMessageContaining("Unable to compile source"); + .isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class)) + .withMessageContaining("Unable to compile source"); } @Test void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() { assertThatExceptionOfType(CompilationException.class) - .isThrownBy(() -> compile(InvalidDefaultValueFloatingPointProperties.class)) - .withMessageContaining("Unable to compile source"); + .isThrownBy(() -> compile(InvalidDefaultValueFloatingPointProperties.class)) + .withMessageContaining("Unable to compile source"); } @Test void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() { assertThatExceptionOfType(CompilationException.class) - .isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class)) - .withMessageContaining("Unable to compile source"); + .isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class)) + .withMessageContaining("Unable to compile source"); } @Test void constructorParameterPropertyWithEmptyDefaultValueOnProperty() { ConfigurationMetadata metadata = compile(EmptyDefaultValueProperties.class); assertThat(metadata).has(Metadata.withProperty("test.name")); - ItemMetadata nameMetadata = metadata.getItems().stream().filter((item) -> item.getName().equals("test.name")) - .findFirst().get(); + ItemMetadata nameMetadata = metadata.getItems() + .stream() + .filter((item) -> item.getName().equals("test.name")) + .findFirst() + .get(); assertThat(nameMetadata.getDefaultValue()).isNull(); } @@ -447,9 +472,9 @@ class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGene """; ConfigurationMetadata metadata = compile(source); assertThat(metadata) - .has(Metadata.withProperty("record.defaults.some-string", String.class).withDefaultValue("An1s9n")); + .has(Metadata.withProperty("record.defaults.some-string", String.class).withDefaultValue("An1s9n")); assertThat(metadata) - .has(Metadata.withProperty("record.defaults.some-integer", Integer.class).withDefaultValue(594)); + .has(Metadata.withProperty("record.defaults.some-integer", Integer.class).withDefaultValue(594)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java index 45cd1c0894..01284252ba 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -99,8 +99,12 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.counter").hasType(Long.class) - .hasSourceType(ImmutableSimpleProperties.class).hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.counter") + .hasType(Long.class) + .hasSourceType(ImmutableSimpleProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -109,10 +113,13 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType("org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo") - .hasSourceType(ImmutableInnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.first") + .hasType("org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties$Foo") + .hasSourceType(ImmutableInnerClassProperties.class) + .hasSourceMethod("getFirst()") + .hasNoDescription() + .isNotDeprecated(); }); } @@ -135,7 +142,7 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class); ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertItemMetadata(metadataEnv, property).isProperty() - .hasDescription("The name of this simple properties."); + .hasDescription("The name of this simple properties."); }); } @@ -156,7 +163,7 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")).hasDefaultValue((byte) 0); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue(null); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue((short) 0); + .hasDefaultValue((short) 0); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(0); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(0L); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0F); @@ -170,10 +177,10 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWithDefaultsProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")) - .hasDefaultValue((byte) 120); + .hasDefaultValue((byte) 120); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a"); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue((short) 1000); + .hasDefaultValue((short) 1000); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000L); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5F); @@ -187,10 +194,10 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWrapperWithDefaultsProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "octet")) - .hasDefaultValue((byte) 120); + .hasDefaultValue((byte) 120); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "letter")).hasDefaultValue("a"); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "number")) - .hasDefaultValue((short) 1000); + .hasDefaultValue((short) 1000); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "counter")).hasDefaultValue(42); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "value")).hasDefaultValue(2000L); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "percentage")).hasDefaultValue(0.5F); @@ -204,9 +211,9 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest TypeElement ownerElement = roundEnv.getRootElement(ImmutableCollectionProperties.class); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "names")).hasDefaultValue(null); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flags")) - .hasDefaultValue(Arrays.asList(true, false)); + .hasDefaultValue(Arrays.asList(true, false)); assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "durations")) - .hasDefaultValue(Arrays.asList("10s", "1m", "1h")); + .hasDefaultValue(Arrays.asList("10s", "1m", "1h")); }); } @@ -220,13 +227,19 @@ class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTest } private VariableElement getConstructorParameter(TypeElement ownerElement, String name) { - List constructors = ElementFilter.constructorsIn(ownerElement.getEnclosedElements()).stream() - .filter((constructor) -> !constructor.getParameters().isEmpty()).toList(); + List constructors = ElementFilter.constructorsIn(ownerElement.getEnclosedElements()) + .stream() + .filter((constructor) -> !constructor.getParameters().isEmpty()) + .toList(); if (constructors.size() != 1) { throw new IllegalStateException("No candidate constructor for " + ownerElement); } - return constructors.get(0).getParameters().stream() - .filter((parameter) -> parameter.getSimpleName().toString().equals(name)).findFirst().orElse(null); + return constructors.get(0) + .getParameters() + .stream() + .filter((parameter) -> parameter.getSimpleName().toString().equals(name)) + .findFirst() + .orElse(null); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java index bc74aca304..e85efc0e41 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/DeducedImmutablePropertiesMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -38,11 +38,14 @@ class DeducedImmutablePropertiesMetadataGenerationTests extends AbstractMetadata ConfigurationMetadata metadata = compile(DeducedImmutableClassProperties.class); assertThat(metadata).has(Metadata.withGroup("test").fromSource(DeducedImmutableClassProperties.class)); assertThat(metadata).has(Metadata.withGroup("test.nested", DeducedImmutableClassProperties.Nested.class) - .fromSource(DeducedImmutableClassProperties.class)); + .fromSource(DeducedImmutableClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("test.nested.name", String.class) - .fromSource(DeducedImmutableClassProperties.Nested.class)); - ItemMetadata nestedMetadata = metadata.getItems().stream() - .filter((item) -> item.getName().equals("test.nested")).findFirst().get(); + .fromSource(DeducedImmutableClassProperties.Nested.class)); + ItemMetadata nestedMetadata = metadata.getItems() + .stream() + .filter((item) -> item.getName().equals("test.nested")) + .findFirst() + .get(); assertThat(nestedMetadata.getDefaultValue()).isNull(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java index 83229fe49f..4c77c1794b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,9 +69,10 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { void customPropertiesEndpoint() { ConfigurationMetadata metadata = compile(CustomPropertiesEndpoint.class); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class)); - assertThat(metadata).has(Metadata.withProperty("management.endpoint.customprops.name").ofType(String.class) - .withDefaultValue("test")); + .has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class)); + assertThat(metadata).has(Metadata.withProperty("management.endpoint.customprops.name") + .ofType(String.class) + .withDefaultValue("test")); assertThat(metadata).has(enabledFlag("customprops", true)); assertThat(metadata).has(cacheTtl("customprops")); assertThat(metadata.getItems()).hasSize(4); @@ -90,7 +91,7 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { void camelCaseEndpoint() { ConfigurationMetadata metadata = compile(CamelCaseEndpoint.class); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class)); assertThat(metadata).has(enabledFlag("PascalCase", "pascal-case", true)); assertThat(metadata.getItems()).hasSize(2); } @@ -100,7 +101,7 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { TestProject project = new TestProject(IncrementalEndpoint.class); ConfigurationMetadata metadata = project.compile(); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); @@ -108,7 +109,7 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { "id = \"incremental\", enableByDefault = false"); metadata = project.compile(); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", false)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); @@ -119,14 +120,14 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { TestProject project = new TestProject(IncrementalEndpoint.class); ConfigurationMetadata metadata = project.compile(); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(cacheTtl("incremental")); assertThat(metadata.getItems()).hasSize(3); project.replaceText(IncrementalEndpoint.class, "@Nullable String param", "String param"); metadata = project.compile(); assertThat(metadata) - .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); + .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata.getItems()).hasSize(2); } @@ -149,8 +150,8 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { private Metadata.MetadataItemCondition enabledFlag(String endpointId, String endpointSuffix, Boolean defaultValue) { return Metadata.withEnabledFlag("management.endpoint." + endpointSuffix + ".enabled") - .withDefaultValue(defaultValue) - .withDescription(String.format("Whether to enable the %s endpoint.", endpointId)); + .withDefaultValue(defaultValue) + .withDescription(String.format("Whether to enable the %s endpoint.", endpointId)); } private Metadata.MetadataItemCondition enabledFlag(String endpointId, Boolean defaultValue) { @@ -158,8 +159,10 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { } private Metadata.MetadataItemCondition cacheTtl(String endpointId) { - return Metadata.withProperty("management.endpoint." + endpointId + ".cache.time-to-live").ofType(Duration.class) - .withDefaultValue("0ms").withDescription("Maximum time that a response can be cached."); + return Metadata.withProperty("management.endpoint." + endpointId + ".cache.time-to-live") + .ofType(Duration.class) + .withDefaultValue("0ms") + .withDescription("Maximum time that a response can be cached."); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java index 575ea90cc1..4f465990f5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/GenericsMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -43,10 +43,14 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, SimpleGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) - .fromSource(SimpleGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); - assertThat(metadata).has(Metadata - .withProperty("generic.mappings", "java.util.Map") - .fromSource(SimpleGenericProperties.class).withDescription("Generic mappings.").withDefaultValue(null)); + .fromSource(SimpleGenericProperties.class) + .withDescription("Generic name.") + .withDefaultValue(null)); + assertThat(metadata) + .has(Metadata.withProperty("generic.mappings", "java.util.Map") + .fromSource(SimpleGenericProperties.class) + .withDescription("Generic mappings.") + .withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @@ -54,11 +58,12 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { void complexGenericProperties() { ConfigurationMetadata metadata = compile(ComplexGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class)); - assertThat(metadata).has(Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class) - .fromSource(ComplexGenericProperties.class)); + assertThat(metadata).has(Metadata.withGroup("generic.test") + .ofType(UpperBoundGenericPojo.class) + .fromSource(ComplexGenericProperties.class)); assertThat(metadata) - .has(Metadata.withProperty("generic.test.mappings", "java.util.Map,java.lang.String>") - .fromSource(UpperBoundGenericPojo.class)); + .has(Metadata.withProperty("generic.test.mappings", "java.util.Map,java.lang.String>") + .fromSource(UpperBoundGenericPojo.class)); assertThat(metadata.getItems()).hasSize(3); } @@ -67,11 +72,14 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, UnresolvedGenericProperties.class); assertThat(metadata).has(Metadata.withGroup("generic").fromSource(UnresolvedGenericProperties.class)); assertThat(metadata).has(Metadata.withProperty("generic.name", String.class) - .fromSource(UnresolvedGenericProperties.class).withDescription("Generic name.").withDefaultValue(null)); + .fromSource(UnresolvedGenericProperties.class) + .withDescription("Generic name.") + .withDefaultValue(null)); assertThat(metadata) - .has(Metadata.withProperty("generic.mappings", "java.util.Map") - .fromSource(UnresolvedGenericProperties.class).withDescription("Generic mappings.") - .withDefaultValue(null)); + .has(Metadata.withProperty("generic.mappings", "java.util.Map") + .fromSource(UnresolvedGenericProperties.class) + .withDescription("Generic mappings.") + .withDefaultValue(null)); assertThat(metadata.getItems()).hasSize(3); } @@ -79,24 +87,27 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { void genericTypes() { ConfigurationMetadata metadata = compile(GenericConfig.class); assertThat(metadata).has(Metadata.withGroup("generic") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig")); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig")); assertThat(metadata).has(Metadata.withGroup("generic.foo") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Foo")); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Foo")); assertThat(metadata).has(Metadata.withGroup("generic.foo.bar") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar")); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar")); assertThat(metadata).has(Metadata.withGroup("generic.foo.bar.biz") - .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar$Biz")); - assertThat(metadata).has( - Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar").ofType( - "java.util.Map>") - .fromSource(GenericConfig.Foo.class)); + .ofType("org.springframework.boot.configurationsample.generic.GenericConfig$Bar$Biz")); + assertThat(metadata) + .has(Metadata.withProperty("generic.foo.name").ofType(String.class).fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-bar") + .ofType("java.util.Map>") + .fromSource(GenericConfig.Foo.class)); assertThat(metadata).has(Metadata.withProperty("generic.foo.string-to-integer") - .ofType("java.util.Map").fromSource(GenericConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name").ofType("java.lang.String") - .fromSource(GenericConfig.Bar.class)); - assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name").ofType("java.lang.String") - .fromSource(GenericConfig.Bar.Biz.class)); + .ofType("java.util.Map") + .fromSource(GenericConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.name") + .ofType("java.lang.String") + .fromSource(GenericConfig.Bar.class)); + assertThat(metadata).has(Metadata.withProperty("generic.foo.bar.biz.name") + .ofType("java.lang.String") + .fromSource(GenericConfig.Bar.Biz.class)); assertThat(metadata.getItems()).hasSize(9); } @@ -105,9 +116,11 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(WildcardConfig.class); assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number") - .ofType("java.util.Map").fromSource(WildcardConfig.class)); + .ofType("java.util.Map") + .fromSource(WildcardConfig.class)); assertThat(metadata).has(Metadata.withProperty("wildcard.integers") - .ofType("java.util.List").fromSource(WildcardConfig.class)); + .ofType("java.util.List") + .fromSource(WildcardConfig.class)); assertThat(metadata.getItems()).hasSize(3); } @@ -115,8 +128,8 @@ class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests { void builderPatternWithGenericReturnType() { ConfigurationMetadata metadata = compile(ConcreteBuilderProperties.class); assertThat(metadata).has(Metadata.withGroup("builder").fromSource(ConcreteBuilderProperties.class)); - assertThat(metadata).has( - Metadata.withProperty("builder.number", Integer.class).fromSource(ConcreteBuilderProperties.class)); + assertThat(metadata) + .has(Metadata.withProperty("builder.number", Integer.class).fromSource(ConcreteBuilderProperties.class)); assertThat(metadata).has( Metadata.withProperty("builder.description", String.class).fromSource(ConcreteBuilderProperties.class)); assertThat(metadata.getItems()).hasSize(3); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java index 8000658dd9..26a81530f4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutableNameAnnotationPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class ImmutableNameAnnotationPropertiesTests extends AbstractMetadataGenerationT void immutableNameAnnotationProperties() { ConfigurationMetadata metadata = compile(ImmutableNameAnnotationProperties.class); assertThat(metadata).has(Metadata.withProperty("named.import", String.class) - .fromSource(ImmutableNameAnnotationProperties.class)); + .fromSource(ImmutableNameAnnotationProperties.class)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java index c2de06ba0c..6e3571539f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ImmutablePropertiesMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,12 +35,15 @@ class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerat void immutableSimpleProperties() { ConfigurationMetadata metadata = compile(ImmutableSimpleProperties.class); assertThat(metadata).has(Metadata.withGroup("immutable").fromSource(ImmutableSimpleProperties.class)); - assertThat(metadata).has( - Metadata.withProperty("immutable.the-name", String.class).fromSource(ImmutableSimpleProperties.class) - .withDescription("The name of this simple properties.").withDefaultValue("boot")); - assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class).withDefaultValue(false) - .fromSource(ImmutableSimpleProperties.class).withDescription("A simple flag.") - .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("immutable.the-name", String.class) + .fromSource(ImmutableSimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot")); + assertThat(metadata).has(Metadata.withProperty("immutable.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(ImmutableSimpleProperties.class) + .withDescription("A simple flag.") + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("immutable.comparator")); assertThat(metadata).has(Metadata.withProperty("immutable.counter")); assertThat(metadata.getItems()).hasSize(5); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java index 8fd03b5357..d77cd2d820 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/IncrementalBuildMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,14 +41,14 @@ class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGeneration TestProject project = new TestProject(FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.compile(); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); metadata = project.compile(); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); project.addSourceCode(BarProperties.class, BarProperties.class.getResourceAsStream("BarProperties.snippet")); metadata = project.compile(); assertThat(metadata).has(Metadata.withProperty("bar.extra")); @@ -79,19 +79,19 @@ class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGeneration TestProject project = new TestProject(FooProperties.class, BarProperties.class); ConfigurationMetadata metadata = project.compile(); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter").fromSource(RenamedBarProperties.class)); project.delete(BarProperties.class); project.add(RenamedBarProperties.class); metadata = project.compile(); assertThat(metadata) - .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); + .has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0)); assertThat(metadata) - .doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); + .doesNotHave(Metadata.withProperty("bar.counter").fromSource(BarProperties.class).withDefaultValue(0)); assertThat(metadata) - .has(Metadata.withProperty("bar.counter").withDefaultValue(0).fromSource(RenamedBarProperties.class)); + .has(Metadata.withProperty("bar.counter").withDefaultValue(0).fromSource(RenamedBarProperties.class)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java index 567d8c3b4f..d763c13ca4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/JavaBeanPropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -128,8 +128,12 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.my-string").hasType(String.class) - .hasSourceType(SimpleTypeProperties.class).hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.my-string") + .hasType(String.class) + .hasSourceType(SimpleTypeProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -138,9 +142,12 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.doubles") - .hasType("java.util.List").hasSourceType(SimpleCollectionProperties.class) - .hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.doubles") + .hasType("java.util.List") + .hasSourceType(SimpleCollectionProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -149,10 +156,13 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(InnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType("org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo") - .hasSourceType(InnerClassProperties.class).hasSourceMethod("getFirst()").hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.first") + .hasType("org.springframework.boot.configurationsample.specific.InnerClassProperties$Foo") + .hasSourceType(InnerClassProperties.class) + .hasSourceMethod("getFirst()") + .hasNoDescription() + .isNotDeprecated(); }); } @@ -172,8 +182,8 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { void javaBeanDeprecatedPropertyOnClass() { process(org.springframework.boot.configurationsample.simple.DeprecatedProperties.class, (roundEnv, metadataEnv) -> { - TypeElement ownerElement = roundEnv.getRootElement( - org.springframework.boot.configurationsample.simple.DeprecatedProperties.class); + TypeElement ownerElement = roundEnv + .getRootElement(org.springframework.boot.configurationsample.simple.DeprecatedProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithNoInformation(); }); @@ -184,8 +194,9 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { process(DeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(DeprecatedSingleProperty.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name"); - assertItemMetadata(metadataEnv, property).isProperty().isDeprecatedWithReason("renamed") - .isDeprecatedWithReplacement("singledeprecated.new-name"); + assertItemMetadata(metadataEnv, property).isProperty() + .isDeprecatedWithReason("renamed") + .isDeprecatedWithReplacement("singledeprecated.new-name"); }); } @@ -213,7 +224,7 @@ class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests { TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class); JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName"); assertItemMetadata(metadataEnv, property).isProperty() - .hasDescription("The name of this simple properties."); + .hasDescription("The name of this simple properties."); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java index 524c200f77..69f0bb8718 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -97,16 +97,18 @@ class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { void lombokInnerClassProperties() { ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassProperties.class)); - assertThat(metadata).has(Metadata.withGroup("config.first").ofType(LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first") + .ofType(LombokInnerClassProperties.Foo.class) + .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name")); assertThat(metadata).has(Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class) - .fromSource(LombokInnerClassProperties.class)); + .fromSource(LombokInnerClassProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.second.name")); assertThat(metadata).has(Metadata.withProperty("config.second.bar.name")); - assertThat(metadata).has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class) - .fromSource(LombokInnerClassProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.third") + .ofType(SimpleLombokPojo.class) + .fromSource(LombokInnerClassProperties.class)); // For some reason the annotation processor resolves a type for SimpleLombokPojo // that is resolved (compiled) and the source annotations are gone. Because we // don't see the @Data annotation anymore, no field is harvested. What is crazy is @@ -121,9 +123,10 @@ class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { void lombokInnerClassWithGetterProperties() { ConfigurationMetadata metadata = compile(LombokInnerClassWithGetterProperties.class); assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassWithGetterProperties.class)); - assertThat(metadata) - .has(Metadata.withGroup("config.first").ofType(LombokInnerClassWithGetterProperties.Foo.class) - .fromSourceMethod("getFirst()").fromSource(LombokInnerClassWithGetterProperties.class)); + assertThat(metadata).has(Metadata.withGroup("config.first") + .ofType(LombokInnerClassWithGetterProperties.Foo.class) + .fromSourceMethod("getFirst()") + .fromSource(LombokInnerClassWithGetterProperties.class)); assertThat(metadata).has(Metadata.withProperty("config.first.name")); assertThat(metadata.getItems()).hasSize(3); } @@ -131,12 +134,15 @@ class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests { private void assertSimpleLombokProperties(ConfigurationMetadata metadata, Class source, String prefix) { assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source)); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".id")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class).fromSource(source) - .withDescription("Name description.")); + assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class) + .fromSource(source) + .withDescription("Name description.")); assertThat(metadata).has(Metadata.withProperty(prefix + ".description")); assertThat(metadata).has(Metadata.withProperty(prefix + ".counter")); - assertThat(metadata).has(Metadata.withProperty(prefix + ".number").fromSource(source).withDefaultValue(0) - .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty(prefix + ".number") + .fromSource(source) + .withDefaultValue(0) + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty(prefix + ".items")); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".ignored")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java index 1d8d0685a3..99f260cdf1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/LombokPropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -148,8 +148,12 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.description").hasType(String.class) - .hasSourceType(LombokSimpleProperties.class).hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.description") + .hasType(String.class) + .hasSourceType(LombokSimpleProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -158,9 +162,12 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items"); - assertItemMetadata(metadataEnv, property).isProperty().hasName("test.items") - .hasType("java.util.List").hasSourceType(LombokSimpleProperties.class) - .hasNoDescription().isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isProperty() + .hasName("test.items") + .hasType("java.util.List") + .hasSourceType(LombokSimpleProperties.class) + .hasNoDescription() + .isNotDeprecated(); }); } @@ -172,10 +179,13 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { ExecutableElement getter = getMethod(ownerElement, "getThird"); LombokPropertyDescriptor property = new LombokPropertyDescriptor(ownerElement, null, field, "third", field.asType(), getter, null); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.third") - .hasType("org.springframework.boot.configurationsample.lombok.SimpleLombokPojo") - .hasSourceType(LombokInnerClassProperties.class).hasSourceMethod("getThird()").hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.third") + .hasType("org.springframework.boot.configurationsample.lombok.SimpleLombokPojo") + .hasSourceType(LombokInnerClassProperties.class) + .hasSourceMethod("getThird()") + .hasNoDescription() + .isNotDeprecated(); }); } @@ -184,10 +194,13 @@ class LombokPropertyDescriptorTests extends PropertyDescriptorTests { process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> { TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class); LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first"); - assertItemMetadata(metadataEnv, property).isGroup().hasName("test.first") - .hasType("org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo") - .hasSourceType(LombokInnerClassProperties.class).hasSourceMethod(null).hasNoDescription() - .isNotDeprecated(); + assertItemMetadata(metadataEnv, property).isGroup() + .hasName("test.first") + .hasType("org.springframework.boot.configurationsample.lombok.LombokInnerClassProperties$Foo") + .hasSourceType(LombokInnerClassProperties.class) + .hasSourceMethod(null) + .hasNoDescription() + .isNotDeprecated(); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java index 72b3d7fd05..167feb22f9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MergeMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,8 +71,11 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, null, null, true, null); String additionalMetadata = buildAdditionalMetadata(property); ConfigurationMetadata metadata = compile(additionalMetadata, SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class).fromSource(SimpleProperties.class) - .withDescription("A simple flag.").withDeprecation(null, null).withDefaultValue(true)); + assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class) + .fromSource(SimpleProperties.class) + .withDescription("A simple flag.") + .withDeprecation(null, null) + .withDefaultValue(true)); assertThat(metadata.getItems()).hasSize(4); } @@ -84,17 +87,23 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(additionalMetadata, SimpleProperties.class, SimpleConflictingProperties.class); assertThat(metadata.getItems()).hasSize(6); - List items = metadata.getItems().stream().filter((item) -> item.getName().equals("simple.flag")) - .toList(); + List items = metadata.getItems() + .stream() + .filter((item) -> item.getName().equals("simple.flag")) + .toList(); assertThat(items).hasSize(2); - ItemMetadata matchingProperty = items.stream().filter((item) -> item.getType().equals(Boolean.class.getName())) - .findFirst().orElse(null); + ItemMetadata matchingProperty = items.stream() + .filter((item) -> item.getType().equals(Boolean.class.getName())) + .findFirst() + .orElse(null); assertThat(matchingProperty).isNotNull(); assertThat(matchingProperty.getDefaultValue()).isEqualTo(true); assertThat(matchingProperty.getSourceType()).isEqualTo(SimpleProperties.class.getName()); assertThat(matchingProperty.getDescription()).isEqualTo("A simple flag."); ItemMetadata nonMatchingProperty = items.stream() - .filter((item) -> item.getType().equals(String.class.getName())).findFirst().orElse(null); + .filter((item) -> item.getType().equals(String.class.getName())) + .findFirst() + .orElse(null); assertThat(nonMatchingProperty).isNotNull(); assertThat(nonMatchingProperty.getDefaultValue()).isEqualTo("hello"); assertThat(nonMatchingProperty.getSourceType()).isEqualTo(SimpleConflictingProperties.class.getName()); @@ -108,7 +117,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { String additionalMetadata = buildAdditionalMetadata(property); ConfigurationMetadata metadata = compile(additionalMetadata, SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.comparator", "java.util.Comparator") - .fromSource(SimpleProperties.class).withDescription("A nice comparator.")); + .fromSource(SimpleProperties.class) + .withDescription("A nice comparator.")); assertThat(metadata.getItems()).hasSize(4); } @@ -118,9 +128,9 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { new ItemDeprecation("Don't use this.", "simple.complex-comparator", "error")); String additionalMetadata = buildAdditionalMetadata(property); ConfigurationMetadata metadata = compile(additionalMetadata, SimpleProperties.class); - assertThat(metadata).has( - Metadata.withProperty("simple.comparator", "java.util.Comparator").fromSource(SimpleProperties.class) - .withDeprecation("Don't use this.", "simple.complex-comparator", "error")); + assertThat(metadata).has(Metadata.withProperty("simple.comparator", "java.util.Comparator") + .fromSource(SimpleProperties.class) + .withDeprecation("Don't use this.", "simple.complex-comparator", "error")); assertThat(metadata.getItems()).hasSize(4); } @@ -131,7 +141,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { String additionalMetadata = buildAdditionalMetadata(property); ConfigurationMetadata metadata = compile(additionalMetadata, DeprecatedSingleProperty.class); assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class).withDeprecation("Don't use this.", "single.name")); + .fromSource(DeprecatedSingleProperty.class) + .withDeprecation("Don't use this.", "single.name")); assertThat(metadata.getItems()).hasSize(3); } @@ -142,8 +153,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { String additionalMetadata = buildAdditionalMetadata(property); ConfigurationMetadata metadata = compile(additionalMetadata, DeprecatedSingleProperty.class); assertThat(metadata).has(Metadata.withProperty("singledeprecated.name", String.class.getName()) - .fromSource(DeprecatedSingleProperty.class) - .withDeprecation("renamed", "singledeprecated.new-name", "error")); + .fromSource(DeprecatedSingleProperty.class) + .withDeprecation("renamed", "singledeprecated.new-name", "error")); assertThat(metadata.getItems()).hasSize(3); } @@ -151,8 +162,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { void mergeOfInvalidAdditionalMetadata() { String metadata = "Hello World"; assertThatExceptionOfType(CompilationException.class) - .isThrownBy(() -> compile(metadata, SimpleProperties.class)) - .withMessageContaining("Invalid additional meta-data"); + .isThrownBy(() -> compile(metadata, SimpleProperties.class)) + .withMessageContaining("Invalid additional meta-data"); } @Test @@ -161,10 +172,12 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { new ItemHint.ValueHint("boot", "Bla bla"), new ItemHint.ValueHint("spring", null))); ConfigurationMetadata metadata = compile(hints, SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); assertThat(metadata) - .has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); + .has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); } @Test @@ -173,8 +186,10 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla"))); ConfigurationMetadata metadata = compile(hints, SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); assertThat(metadata).has(Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla")); } @@ -185,8 +200,10 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { new ItemHint.ValueProvider("second", null)))); ConfigurationMetadata metadata = compile(hints, SimpleProperties.class); assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class) - .fromSource(SimpleProperties.class).withDescription("The name of this simple properties.") - .withDefaultValue("boot").withDeprecation(null, null)); + .fromSource(SimpleProperties.class) + .withDescription("The name of this simple properties.") + .withDefaultValue("boot") + .withDeprecation(null, null)); assertThat(metadata).has( Metadata.withHint("simple.the-name").withProvider("first", "target", "org.foo").withProvider("second")); } @@ -196,8 +213,8 @@ class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests { String deprecations = buildPropertyDeprecations(ItemMetadata.newProperty("simple", "wrongName", "java.lang.String", null, null, null, null, new ItemDeprecation("Lame name.", "simple.the-name"))); ConfigurationMetadata metadata = compile(deprecations, SimpleProperties.class); - assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class).withDeprecation("Lame name.", - "simple.the-name")); + assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class) + .withDeprecation("Lame name.", "simple.the-name")); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java index ea284745c2..77ea482da2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MetadataStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class MetadataStoreTests { additionalMetadata.createNewFile(); assertThat(this.metadataStore.locateAdditionalMetadataFile( new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + .isEqualTo(additionalMetadata); } @Test @@ -67,7 +67,7 @@ class MetadataStoreTests { additionalMetadata.createNewFile(); assertThat(this.metadataStore.locateAdditionalMetadataFile( new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + .isEqualTo(additionalMetadata); } @Test @@ -81,7 +81,7 @@ class MetadataStoreTests { additionalMetadata.createNewFile(); assertThat(this.metadataStore.locateAdditionalMetadataFile( new File(classesLocation, "META-INF/additional-spring-configuration-metadata.json"))) - .isEqualTo(additionalMetadata); + .isEqualTo(additionalMetadata); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java index a1f25d3633..e7391bf980 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/MethodBasedMetadataGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,7 +60,7 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests assertThat(metadata).has(Metadata.withGroup("foo").fromSource(config)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class).fromSource(properties)); assertThat(metadata) - .has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false).fromSource(properties)); + .has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false).fromSource(properties)); } @Test @@ -73,7 +73,7 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests void invalidMethodConfig() { ConfigurationMetadata metadata = compile(InvalidMethodConfig.class); assertThat(metadata) - .has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class)); + .has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class)); assertThat(metadata).isNotEqualTo(Metadata.withProperty("invalid.name")); } @@ -81,22 +81,24 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests void methodAndClassConfig() { ConfigurationMetadata metadata = compile(MethodAndClassConfig.class); assertThat(metadata) - .has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class).withDefaultValue(false) - .fromSource(MethodAndClassConfig.Foo.class)); + .has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(MethodAndClassConfig.Foo.class)); assertThat(metadata) - .has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class)); + .has(Metadata.withProperty("conflict.value", String.class).fromSource(MethodAndClassConfig.class)); } @Test void singleConstructorMethodConfig() { ConfigurationMetadata metadata = compile(SingleConstructorMethodConfig.class); assertThat(metadata).doesNotHave(Metadata.withProperty("foo.my-service", Object.class) - .fromSource(SingleConstructorMethodConfig.Foo.class)); - assertThat(metadata).has( - Metadata.withProperty("foo.name", String.class).fromSource(SingleConstructorMethodConfig.Foo.class)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) - .fromSource(SingleConstructorMethodConfig.Foo.class)); + .fromSource(SingleConstructorMethodConfig.Foo.class)); + assertThat(metadata) + .has(Metadata.withProperty("foo.name", String.class).fromSource(SingleConstructorMethodConfig.Foo.class)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(SingleConstructorMethodConfig.Foo.class)); } @Test @@ -111,9 +113,12 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) - .fromSource(DeprecatedMethodConfig.Foo.class).withDeprecation(null, null)); + .fromSource(DeprecatedMethodConfig.Foo.class) + .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(DeprecatedMethodConfig.Foo.class) + .withDeprecation(null, null)); } @Test @@ -123,11 +128,12 @@ class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests ConfigurationMetadata metadata = compile(type); assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type)); assertThat(metadata).has(Metadata.withProperty("foo.name", String.class) - .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) - .withDeprecation(null, null)); - assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class).withDefaultValue(false) - .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) - .withDeprecation(null, null)); + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + .withDeprecation(null, null)); + assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class) + .withDefaultValue(false) + .fromSource(org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.Foo.class) + .withDeprecation(null, null)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java index 9ac221e0ed..9f85011de4 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,13 +73,13 @@ class PropertyDescriptorResolverTests { PropertyDescriptorResolver resolver = new PropertyDescriptorResolver(metadataEnv); assertThat(resolver.resolve(type, null).map(PropertyDescriptor::getName)).containsExactly("third", "second", "first"); - assertThat(resolver.resolve(type, null).map( - (descriptor) -> descriptor.getGetter().getEnclosingElement().getSimpleName().toString())) - .containsExactly("HierarchicalProperties", "HierarchicalPropertiesParent", - "HierarchicalPropertiesParent"); assertThat(resolver.resolve(type, null) - .map((descriptor) -> descriptor.resolveItemMetadata("test", metadataEnv)) - .map(ItemMetadata::getDefaultValue)).containsExactly("three", "two", "one"); + .map((descriptor) -> descriptor.getGetter().getEnclosingElement().getSimpleName().toString())) + .containsExactly("HierarchicalProperties", "HierarchicalPropertiesParent", + "HierarchicalPropertiesParent"); + assertThat(resolver.resolve(type, null) + .map((descriptor) -> descriptor.resolveItemMetadata("test", metadataEnv)) + .map(ItemMetadata::getDefaultValue)).containsExactly("three", "two", "one"); }); } @@ -112,7 +112,7 @@ class PropertyDescriptorResolverTests { process(ImmutableDeducedConstructorBindingProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("theName", "flag"))); process(ImmutableDeducedConstructorBindingProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test @@ -120,7 +120,7 @@ class PropertyDescriptorResolverTests { process(ImmutableSimpleProperties.class, propertyNames( (stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator", "counter"))); process(ImmutableSimpleProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test @@ -128,14 +128,14 @@ class PropertyDescriptorResolverTests { process(ImmutableClassConstructorBindingProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("name", "description"))); process(ImmutableClassConstructorBindingProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test void propertiesWithAutowiredConstructor() { process(AutowiredProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("theName"))); process(AutowiredProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof JavaBeanPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof JavaBeanPropertyDescriptor))); } @Test @@ -143,7 +143,7 @@ class PropertyDescriptorResolverTests { process(ImmutableMultiConstructorProperties.class, propertyNames((stream) -> assertThat(stream).containsExactly("name", "description"))); process(ImmutableMultiConstructorProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test @@ -154,7 +154,7 @@ class PropertyDescriptorResolverTests { propertyNames((stream) -> assertThat(stream).containsExactly("name", "description"))); process(org.springframework.boot.configurationsample.immutable.DeprecatedImmutableMultiConstructorProperties.class, properties((stream) -> assertThat(stream) - .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); + .allMatch((predicate) -> predicate instanceof ConstructorParameterPropertyDescriptor))); } @Test @@ -197,8 +197,10 @@ class PropertyDescriptorResolverTests { internalConsumer, new MetadataGenerationEnvironmentFactory()); SourceFile targetSource = SourceFile.forTestClass(target); List additionalSource = additionalClasses.stream().map(SourceFile::forTestClass).toList(); - TestCompiler compiler = TestCompiler.forSystem().withProcessors(processor).withSources(targetSource) - .withSources(additionalSource); + TestCompiler compiler = TestCompiler.forSystem() + .withProcessors(processor) + .withSources(targetSource) + .withSources(additionalSource); compiler.compile((compiled) -> { }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java index cb6e838499..c2d5b8fac6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/PropertyDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,15 +45,19 @@ public abstract class PropertyDescriptorTests { } protected ExecutableElement getMethod(TypeElement element, String name) { - return ElementFilter.methodsIn(element.getEnclosedElements()).stream() - .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst() - .orElse(null); + return ElementFilter.methodsIn(element.getEnclosedElements()) + .stream() + .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)) + .findFirst() + .orElse(null); } protected VariableElement getField(TypeElement element, String name) { - return ElementFilter.fieldsIn(element.getEnclosedElements()).stream() - .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)).findFirst() - .orElse(null); + return ElementFilter.fieldsIn(element.getEnclosedElements()) + .stream() + .filter((method) -> ((Element) method).getSimpleName().toString().equals(name)) + .findFirst() + .orElse(null); } protected ItemMetadataAssert assertItemMetadata(MetadataGenerationEnvironment metadataEnv, @@ -65,8 +69,9 @@ public abstract class PropertyDescriptorTests { BiConsumer consumer) { TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>( consumer, new MetadataGenerationEnvironmentFactory()); - TestCompiler compiler = TestCompiler.forSystem().withProcessors(processor) - .withSources(SourceFile.forTestClass(target)); + TestCompiler compiler = TestCompiler.forSystem() + .withProcessors(processor) + .withSources(SourceFile.forTestClass(target)); compiler.compile((compiled) -> { }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java index 312ef288fb..cacb142bd5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TestProject.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,8 +84,8 @@ public class TestProject { */ public void delete(Class type) { SourceFile[] newSources = this.sources.stream() - .filter((sourceFile) -> !sourceFile.getPath().equals(SourceFile.forTestClass(type).getPath())) - .toArray(SourceFile[]::new); + .filter((sourceFile) -> !sourceFile.getPath().equals(SourceFile.forTestClass(type).getPath())) + .toArray(SourceFile[]::new); this.sources = SourceFiles.of(newSources); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java index 759c030b7d..92d2ae00ec 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/TypeUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class TypeUtilsTests { void resolveTypeDescriptorOnConcreteClass() { process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils - .resolveTypeDescriptor(roundEnv.getRootElement(SimpleGenericProperties.class)); + .resolveTypeDescriptor(roundEnv.getRootElement(SimpleGenericProperties.class)); assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", "C"); assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName()); @@ -58,7 +58,7 @@ class TypeUtilsTests { void resolveTypeDescriptorOnIntermediateClass() { process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils - .resolveTypeDescriptor(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class)); + .resolveTypeDescriptor(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class)); assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", "C"); assertThat(typeDescriptor.resolveGeneric("A")).hasToString(String.class.getName()); @@ -71,7 +71,7 @@ class TypeUtilsTests { void resolveTypeDescriptorWithOnlyGenerics() { process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> { TypeDescriptor typeDescriptor = typeUtils - .resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class)); + .resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class)); assertThat(typeDescriptor.getGenerics().keySet().stream().map(Object::toString)).containsOnly("A", "B", "C"); @@ -80,8 +80,9 @@ class TypeUtilsTests { private void process(Class target, BiConsumer consumer) { TestableAnnotationProcessor processor = new TestableAnnotationProcessor<>(consumer, TypeUtils::new); - TestCompiler compiler = TestCompiler.forSystem().withProcessors(processor) - .withSources(SourceFile.forTestClass(target)); + TestCompiler compiler = TestCompiler.forSystem() + .withProcessors(processor) + .withSources(SourceFile.forTestClass(target)); compiler.compile((compiled) -> { }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java index bf948da2a2..025c0025ad 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java @@ -50,8 +50,9 @@ public abstract class AbstractFieldValuesProcessorTests { @Test void getFieldValues() throws Exception { TestProcessor processor = new TestProcessor(); - TestCompiler compiler = TestCompiler.forSystem().withProcessors(processor) - .withSources(SourceFile.forTestClass(FieldValues.class)); + TestCompiler compiler = TestCompiler.forSystem() + .withProcessors(processor) + .withSources(SourceFile.forTestClass(FieldValues.class)); compiler.compile((compiled) -> { }); Map values = processor.getValues(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java index 1f9c8d241e..2cbda570e8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -55,8 +55,11 @@ class JsonMarshallerTests { JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); ConfigurationMetadata read = marshaller.read(new ByteArrayInputStream(outputStream.toByteArray())); - assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class).fromSource(InputStream.class) - .withDescription("desc").withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d")); + assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class) + .fromSource(InputStream.class) + .withDescription("desc") + .withDefaultValue("x") + .withDeprecation("Deprecation comment", "b.c.d")); assertThat(read).has(Metadata.withProperty("b.c.d")); assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123)); assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true)); @@ -126,10 +129,10 @@ class JsonMarshallerTests { null, null, null)); metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", "java.lang.Integer", "com.example.Bar", null, null, null, null)); - metadata.add( - ItemMetadata.newProperty("com.example.alpha", "ddd", null, "com.example.Bar", null, null, null, null)); - metadata.add( - ItemMetadata.newProperty("com.example.alpha", "ccc", null, "com.example.Foo", null, null, null, null)); + metadata + .add(ItemMetadata.newProperty("com.example.alpha", "ddd", null, "com.example.Bar", null, null, null, null)); + metadata + .add(ItemMetadata.newProperty("com.example.alpha", "ccc", null, "com.example.Foo", null, null, null, null)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonMarshaller marshaller = new JsonMarshaller(); marshaller.write(metadata, outputStream); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java index ec383d0954..39be910daf 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/metadata/Metadata.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -208,8 +208,10 @@ public final class Metadata { } private ItemMetadata findItem(ConfigurationMetadata metadata, String name) { - List candidates = metadata.getItems().stream() - .filter((item) -> item.isOfItemType(this.itemType) && name.equals(item.getName())).toList(); + List candidates = metadata.getItems() + .stream() + .filter((item) -> item.isOfItemType(this.itemType) && name.equals(item.getName())) + .toList(); if (candidates.size() > 1) { throw new IllegalStateException("More than one metadata item with name '" + name + "': " + candidates); } @@ -389,7 +391,7 @@ public final class Metadata { if (this.parameters != null) { for (Map.Entry entry : this.parameters.entrySet()) { if (!IsMapContaining.hasEntry(entry.getKey(), entry.getValue()) - .matches(valueProvider.getParameters())) { + .matches(valueProvider.getParameters())) { return false; } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java index c33496fb50..a6376066e5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/test/RoundEnvironmentTester.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -38,10 +38,12 @@ public class RoundEnvironmentTester { * @return the {@link TypeElement} */ public TypeElement getRootElement(Class type) { - return (TypeElement) this.roundEnvironment.getRootElements().stream() - .filter((element) -> element.toString().equals(type.getName())).findFirst() - .orElseThrow(() -> new IllegalStateException("No element found for " + type - + " make sure it is included in the list of classes to compile")); + return (TypeElement) this.roundEnvironment.getRootElements() + .stream() + .filter((element) -> element.toString().equals(type.getName())) + .findFirst() + .orElseThrow(() -> new IllegalStateException( + "No element found for " + type + " make sure it is included in the list of classes to compile")); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedRecord.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedRecord.java index c5563ce52b..70e9afc7a9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedRecord.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/simple/DeprecatedRecord.java @@ -21,9 +21,9 @@ import org.springframework.boot.configurationsample.DeprecatedConfigurationPrope /** * Configuration properties as record with deprecated property. + * * @param alpha alpha property, deprecated * @param bravo bravo property - * * @author Moritz Halbritter */ @ConfigurationProperties("deprecated-record") diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java index f341938491..259b7706b9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/dsl/SpringBootExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -91,8 +91,9 @@ public class SpringBootExtension { this::configureBuildInfoTask); this.project.getPlugins().withType(JavaPlugin.class, (plugin) -> { tasks.named(JavaPlugin.CLASSES_TASK_NAME).configure((task) -> task.dependsOn(bootBuildInfo)); - bootBuildInfo.configure((buildInfo) -> buildInfo.getProperties().getArtifact() - .convention(this.project.provider(() -> determineArtifactBaseName()))); + bootBuildInfo.configure((buildInfo) -> buildInfo.getProperties() + .getArtifact() + .convention(this.project.provider(() -> determineArtifactBaseName()))); }); if (configurer != null) { bootBuildInfo.configure(configurer); @@ -102,13 +103,18 @@ public class SpringBootExtension { private void configureBuildInfoTask(BuildInfo task) { task.setGroup(BasePlugin.BUILD_GROUP); task.setDescription("Generates a META-INF/build-info.properties file."); - task.getDestinationDir().convention(this.project.getLayout() + task.getDestinationDir() + .convention(this.project.getLayout() .dir(this.project.provider(() -> new File(determineMainSourceSetResourcesOutputDir(), "META-INF")))); } private File determineMainSourceSetResourcesOutputDir() { - return this.project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput().getResourcesDir(); + return this.project.getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets() + .getByName(SourceSet.MAIN_SOURCE_SET_NAME) + .getOutput() + .getResourcesDir(); } private String determineArtifactBaseName() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java index 84b2fe03d6..a8bd949c62 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ApplicationPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,10 +49,10 @@ final class ApplicationPluginAction implements PluginApplicationAction { DistributionContainer distributions = project.getExtensions().getByType(DistributionContainer.class); Distribution distribution = distributions.create("boot"); distribution.getDistributionBaseName() - .convention((project.provider(() -> javaApplication.getApplicationName() + "-boot"))); - TaskProvider bootStartScripts = project.getTasks().register("bootStartScripts", - CreateStartScripts.class, - (task) -> configureCreateStartScripts(project, javaApplication, distribution, task)); + .convention((project.provider(() -> javaApplication.getApplicationName() + "-boot"))); + TaskProvider bootStartScripts = project.getTasks() + .register("bootStartScripts", CreateStartScripts.class, + (task) -> configureCreateStartScripts(project, javaApplication, distribution, task)); CopySpec binCopySpec = project.copySpec().into("bin").from(bootStartScripts); binCopySpec.setFileMode(0755); distribution.getContents().with(binCopySpec); @@ -61,19 +61,19 @@ final class ApplicationPluginAction implements PluginApplicationAction { private void configureCreateStartScripts(Project project, JavaApplication javaApplication, Distribution distribution, CreateStartScripts createStartScripts) { createStartScripts - .setDescription("Generates OS-specific start scripts to run the project as a Spring Boot application."); + .setDescription("Generates OS-specific start scripts to run the project as a Spring Boot application."); ((TemplateBasedScriptGenerator) createStartScripts.getUnixStartScriptGenerator()) - .setTemplate(project.getResources().getText().fromString(loadResource("/unixStartScript.txt"))); + .setTemplate(project.getResources().getText().fromString(loadResource("/unixStartScript.txt"))); ((TemplateBasedScriptGenerator) createStartScripts.getWindowsStartScriptGenerator()) - .setTemplate(project.getResources().getText().fromString(loadResource("/windowsStartScript.txt"))); + .setTemplate(project.getResources().getText().fromString(loadResource("/windowsStartScript.txt"))); project.getConfigurations().all((configuration) -> { if ("bootArchives".equals(configuration.getName())) { distribution.getContents().with(artifactFilesToLibCopySpec(project, configuration)); createStartScripts.setClasspath(configuration.getArtifacts().getFiles()); } }); - createStartScripts.getConventionMapping().map("outputDir", - () -> new File(project.getBuildDir(), "bootScripts")); + createStartScripts.getConventionMapping() + .map("outputDir", () -> new File(project.getBuildDir(), "bootScripts")); createStartScripts.getConventionMapping().map("applicationName", javaApplication::getApplicationName); createStartScripts.getConventionMapping().map("defaultJvmOpts", javaApplication::getApplicationDefaultJvmArgs); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java index c8b6759f12..8e9e7dd2af 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -32,8 +32,9 @@ final class DependencyManagementPluginAction implements PluginApplicationAction @Override public void execute(Project project) { - project.getExtensions().findByType(DependencyManagementExtension.class) - .imports((importsHandler) -> importsHandler.mavenBom(SpringBootPlugin.BOM_COORDINATES)); + project.getExtensions() + .findByType(DependencyManagementExtension.class) + .imports((importsHandler) -> importsHandler.mavenBom(SpringBootPlugin.BOM_COORDINATES)); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java index d6f0e22317..3e831234e3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -91,36 +91,41 @@ final class JavaPluginAction implements PluginApplicationAction { } private void classifyJarTask(Project project) { - project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class) - .configure((task) -> task.getArchiveClassifier().convention("plain")); + project.getTasks() + .named(JavaPlugin.JAR_TASK_NAME, Jar.class) + .configure((task) -> task.getArchiveClassifier().convention("plain")); } private void configureBuildTask(Project project) { - project.getTasks().named(BasePlugin.ASSEMBLE_TASK_NAME) - .configure((task) -> task.dependsOn(this.singlePublishedArtifact)); + project.getTasks() + .named(BasePlugin.ASSEMBLE_TASK_NAME) + .configure((task) -> task.dependsOn(this.singlePublishedArtifact)); } private TaskProvider configureResolveMainClassNameTask(Project project) { - return project.getTasks().register(SpringBootPlugin.RESOLVE_MAIN_CLASS_NAME_TASK_NAME, - ResolveMainClassName.class, (resolveMainClassName) -> { - ExtensionContainer extensions = project.getExtensions(); - resolveMainClassName.setDescription("Resolves the name of the application's main class."); - resolveMainClassName.setGroup(BasePlugin.BUILD_GROUP); - Callable classpath = () -> project.getExtensions() - .getByType(SourceSetContainer.class).getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput(); - resolveMainClassName.setClasspath(classpath); - resolveMainClassName.getConfiguredMainClassName().convention(project.provider(() -> { - String javaApplicationMainClass = getJavaApplicationMainClass(extensions); - if (javaApplicationMainClass != null) { - return javaApplicationMainClass; - } - SpringBootExtension springBootExtension = project.getExtensions() + return project.getTasks() + .register(SpringBootPlugin.RESOLVE_MAIN_CLASS_NAME_TASK_NAME, ResolveMainClassName.class, + (resolveMainClassName) -> { + ExtensionContainer extensions = project.getExtensions(); + resolveMainClassName.setDescription("Resolves the name of the application's main class."); + resolveMainClassName.setGroup(BasePlugin.BUILD_GROUP); + Callable classpath = () -> project.getExtensions() + .getByType(SourceSetContainer.class) + .getByName(SourceSet.MAIN_SOURCE_SET_NAME) + .getOutput(); + resolveMainClassName.setClasspath(classpath); + resolveMainClassName.getConfiguredMainClassName().convention(project.provider(() -> { + String javaApplicationMainClass = getJavaApplicationMainClass(extensions); + if (javaApplicationMainClass != null) { + return javaApplicationMainClass; + } + SpringBootExtension springBootExtension = project.getExtensions() .findByType(SpringBootExtension.class); - return springBootExtension.getMainClass().getOrNull(); - })); - resolveMainClassName.getOutputFile() + return springBootExtension.getMainClass().getOrNull(); + })); + resolveMainClassName.getOutputFile() .set(project.getLayout().getBuildDirectory().file("resolvedMainClassName")); - }); + }); } private static String getJavaApplicationMainClass(ExtensionContainer extensions) { @@ -134,24 +139,26 @@ final class JavaPluginAction implements PluginApplicationAction { private TaskProvider configureBootJarTask(Project project, TaskProvider resolveMainClassName) { SourceSet mainSourceSet = javaPluginExtension(project).getSourceSets() - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + .getByName(SourceSet.MAIN_SOURCE_SET_NAME); Configuration developmentOnly = project.getConfigurations() - .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); Configuration productionRuntimeClasspath = project.getConfigurations() - .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); Callable classpath = () -> mainSourceSet.getRuntimeClasspath() - .minus((developmentOnly.minus(productionRuntimeClasspath))).filter(new JarTypeFileSpec()); + .minus((developmentOnly.minus(productionRuntimeClasspath))) + .filter(new JarTypeFileSpec()); return project.getTasks().register(SpringBootPlugin.BOOT_JAR_TASK_NAME, BootJar.class, (bootJar) -> { bootJar.setDescription( "Assembles an executable jar archive containing the main classes and their dependencies."); bootJar.setGroup(BasePlugin.BUILD_GROUP); bootJar.classpath(classpath); Provider manifestStartClass = project - .provider(() -> (String) bootJar.getManifest().getAttributes().get("Start-Class")); - bootJar.getMainClass().convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() - ? manifestStartClass : resolveMainClassName.get().readMainClassName())); + .provider(() -> (String) bootJar.getManifest().getAttributes().get("Start-Class")); + bootJar.getMainClass() + .convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() + ? manifestStartClass : resolveMainClassName.get().readMainClassName())); bootJar.getTargetJavaVersion() - .set(project.provider(() -> javaPluginExtension(project).getTargetCompatibility())); + .set(project.provider(() -> javaPluginExtension(project).getTargetCompatibility())); }); } @@ -169,7 +176,9 @@ final class JavaPluginAction implements PluginApplicationAction { private void configureBootRunTask(Project project, TaskProvider resolveMainClassName) { Callable classpath = () -> javaPluginExtension(project).getSourceSets() - .findByName(SourceSet.MAIN_SOURCE_SET_NAME).getRuntimeClasspath().filter(new JarTypeFileSpec()); + .findByName(SourceSet.MAIN_SOURCE_SET_NAME) + .getRuntimeClasspath() + .filter(new JarTypeFileSpec()); project.getTasks().register("bootRun", BootRun.class, (run) -> { run.setDescription("Runs this project as a Spring Boot application."); run.setGroup(ApplicationPlugin.APPLICATION_GROUP); @@ -215,27 +224,32 @@ final class JavaPluginAction implements PluginApplicationAction { } private void configureAdditionalMetadataLocations(Project project) { - project.afterEvaluate((evaluated) -> evaluated.getTasks().withType(JavaCompile.class) - .configureEach(this::configureAdditionalMetadataLocations)); + project.afterEvaluate((evaluated) -> evaluated.getTasks() + .withType(JavaCompile.class) + .configureEach(this::configureAdditionalMetadataLocations)); } private void configureAdditionalMetadataLocations(JavaCompile compile) { - SourceSetContainer sourceSets = compile.getProject().getExtensions().getByType(JavaPluginExtension.class) - .getSourceSets(); - sourceSets.stream().filter((candidate) -> candidate.getCompileJavaTaskName().equals(compile.getName())) - .map((match) -> match.getResources().getSrcDirs()).findFirst() - .ifPresent((locations) -> compile.doFirst(new AdditionalMetadataLocationsConfigurer(locations))); + SourceSetContainer sourceSets = compile.getProject() + .getExtensions() + .getByType(JavaPluginExtension.class) + .getSourceSets(); + sourceSets.stream() + .filter((candidate) -> candidate.getCompileJavaTaskName().equals(compile.getName())) + .map((match) -> match.getResources().getSrcDirs()) + .findFirst() + .ifPresent((locations) -> compile.doFirst(new AdditionalMetadataLocationsConfigurer(locations))); } private void configureDevelopmentOnlyConfiguration(Project project) { Configuration developmentOnly = project.getConfigurations() - .create(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); + .create(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); developmentOnly - .setDescription("Configuration for development-only dependencies such as Spring Boot's DevTools."); + .setDescription("Configuration for development-only dependencies such as Spring Boot's DevTools."); Configuration runtimeClasspath = project.getConfigurations() - .getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME); + .getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME); Configuration productionRuntimeClasspath = project.getConfigurations() - .create(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); + .create(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); AttributeContainer attributes = productionRuntimeClasspath.getAttributes(); ObjectFactory objectFactory = project.getObjects(); attributes.attribute(Usage.USAGE_ATTRIBUTE, objectFactory.named(Usage.class, Usage.JAVA_RUNTIME)); @@ -275,14 +289,16 @@ final class JavaPluginAction implements PluginApplicationAction { private boolean hasConfigurationProcessorOnClasspath(JavaCompile compile) { Set files = (compile.getOptions().getAnnotationProcessorPath() != null) ? compile.getOptions().getAnnotationProcessorPath().getFiles() : compile.getClasspath().getFiles(); - return files.stream().map(File::getName) - .anyMatch((name) -> name.startsWith("spring-boot-configuration-processor")); + return files.stream() + .map(File::getName) + .anyMatch((name) -> name.startsWith("spring-boot-configuration-processor")); } private void configureAdditionalMetadataLocations(JavaCompile compile) { - compile.getOptions().getCompilerArgs() - .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" - + StringUtils.collectionToCommaDelimitedString(this.locations)); + compile.getOptions() + .getCompilerArgs() + .add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + + StringUtils.collectionToCommaDelimitedString(this.locations)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java index a4bce532bd..afb5eefac1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,8 +47,9 @@ class KotlinPluginAction implements PluginApplicationAction { } private void enableJavaParametersOption(Project project) { - project.getTasks().withType(KotlinCompile.class) - .configureEach((compile) -> compile.getKotlinOptions().setJavaParameters(true)); + project.getTasks() + .withType(KotlinCompile.class) + .configureEach((compile) -> compile.getKotlinOptions().setJavaParameters(true)); } @Override diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/NativeImagePluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/NativeImagePluginAction.java index 6ce4220cef..1ae66ec959 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/NativeImagePluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/NativeImagePluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,15 +70,16 @@ class NativeImagePluginAction implements PluginApplicationAction { private void configureMainNativeBinaryClasspath(Project project, SourceSetContainer sourceSets, GraalVMExtension graalVmExtension) { FileCollection runtimeClasspath = sourceSets.getByName(SpringBootAotPlugin.AOT_SOURCE_SET_NAME) - .getRuntimeClasspath(); + .getRuntimeClasspath(); graalVmExtension.getBinaries().getByName(NativeImagePlugin.NATIVE_MAIN_EXTENSION).classpath(runtimeClasspath); Configuration nativeImageClasspath = project.getConfigurations().getByName("nativeImageClasspath"); nativeImageClasspath.setExtendsFrom(removeDevelopmentOnly(nativeImageClasspath.getExtendsFrom())); } private Iterable removeDevelopmentOnly(Set configurations) { - return configurations.stream().filter(this::isNotDevelopmentOnly) - .collect(Collectors.toCollection(LinkedHashSet::new)); + return configurations.stream() + .filter(this::isNotDevelopmentOnly) + .collect(Collectors.toCollection(LinkedHashSet::new)); } private boolean isNotDevelopmentOnly(Configuration configuration) { @@ -88,7 +89,7 @@ class NativeImagePluginAction implements PluginApplicationAction { private void configureTestNativeBinaryClasspath(Project project, SourceSetContainer sourceSets, GraalVMExtension graalVmExtension) { FileCollection runtimeClasspath = sourceSets.getByName(SpringBootAotPlugin.AOT_TEST_SOURCE_SET_NAME) - .getRuntimeClasspath(); + .getRuntimeClasspath(); graalVmExtension.getBinaries().getByName(NativeImagePlugin.NATIVE_TEST_EXTENSION).classpath(runtimeClasspath); } @@ -109,21 +110,23 @@ class NativeImagePluginAction implements PluginApplicationAction { private void configureGraalVmReachabilityExtension(GraalVMExtension graalVmExtension) { GraalVMReachabilityMetadataRepositoryExtension extension = ((ExtensionAware) graalVmExtension).getExtensions() - .getByType(GraalVMReachabilityMetadataRepositoryExtension.class); + .getByType(GraalVMReachabilityMetadataRepositoryExtension.class); extension.getEnabled().set(true); } private void copyReachabilityMetadataToBootJar(Project project) { - project.getTasks().named(SpringBootPlugin.BOOT_JAR_TASK_NAME, BootJar.class) - .configure((bootJar) -> bootJar.from(project.getTasks().named("collectReachabilityMetadata"))); + project.getTasks() + .named(SpringBootPlugin.BOOT_JAR_TASK_NAME, BootJar.class) + .configure((bootJar) -> bootJar.from(project.getTasks().named("collectReachabilityMetadata"))); } private void configureBootBuildImageToProduceANativeImage(Project project) { - project.getTasks().named(SpringBootPlugin.BOOT_BUILD_IMAGE_TASK_NAME, BootBuildImage.class) - .configure((bootBuildImage) -> { - bootBuildImage.getBuilder().convention("paketobuildpacks/builder:tiny"); - bootBuildImage.getEnvironment().put("BP_NATIVE_IMAGE", "true"); - }); + project.getTasks() + .named(SpringBootPlugin.BOOT_BUILD_IMAGE_TASK_NAME, BootBuildImage.class) + .configure((bootBuildImage) -> { + bootBuildImage.getBuilder().convention("paketobuildpacks/builder:tiny"); + bootBuildImage.getEnvironment().put("BP_NATIVE_IMAGE", "true"); + }); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java index 6d5b9c5026..6d27100791 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -130,8 +130,13 @@ public class ResolveMainClassName extends DefaultTask { if (configuredMainClass != null) { return configuredMainClass; } - return getClasspath().filter(File::isDirectory).getFiles().stream().map(this::findMainClass) - .filter(Objects::nonNull).findFirst().orElse(""); + return getClasspath().filter(File::isDirectory) + .getFiles() + .stream() + .map(this::findMainClass) + .filter(Objects::nonNull) + .findFirst() + .orElse(""); } private String findMainClass(File file) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootAotPlugin.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootAotPlugin.java index f6461912fb..71199a2951 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootAotPlugin.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/SpringBootAotPlugin.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -90,17 +90,18 @@ public class SpringBootAotPlugin implements Plugin { SourceSetContainer sourceSets = javaPluginExtension.getSourceSets(); return sourceSets.create(newSourceSetName, (sourceSet) -> { existingSourceSet.setRuntimeClasspath(existingSourceSet.getRuntimeClasspath().plus(sourceSet.getOutput())); - project.getConfigurations().getByName(sourceSet.getCompileClasspathConfigurationName()) - .attributes((attributes) -> { - configureClassesAndResourcesLibraryElementsAttribute(project, attributes); - configureJavaRuntimeUsageAttribute(project, attributes); - }); + project.getConfigurations() + .getByName(sourceSet.getCompileClasspathConfigurationName()) + .attributes((attributes) -> { + configureClassesAndResourcesLibraryElementsAttribute(project, attributes); + configureJavaRuntimeUsageAttribute(project, attributes); + }); }); } private void configureClassesAndResourcesLibraryElementsAttribute(Project project, AttributeContainer attributes) { - LibraryElements classesAndResources = project.getObjects().named(LibraryElements.class, - LibraryElements.CLASSES_AND_RESOURCES); + LibraryElements classesAndResources = project.getObjects() + .named(LibraryElements.class, LibraryElements.CLASSES_AND_RESOURCES); attributes.attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, classesAndResources); } @@ -111,21 +112,22 @@ public class SpringBootAotPlugin implements Plugin { private void registerProcessAotTask(Project project, SourceSet aotSourceSet, SourceSet mainSourceSet) { TaskProvider resolveMainClassName = project.getTasks() - .named(SpringBootPlugin.RESOLVE_MAIN_CLASS_NAME_TASK_NAME, ResolveMainClassName.class); + .named(SpringBootPlugin.RESOLVE_MAIN_CLASS_NAME_TASK_NAME, ResolveMainClassName.class); Configuration aotClasspath = createAotProcessingClasspath(project, PROCESS_AOT_TASK_NAME, mainSourceSet); project.getDependencies().add(aotClasspath.getName(), project.files(mainSourceSet.getOutput())); Configuration compileClasspath = project.getConfigurations() - .getByName(aotSourceSet.getCompileClasspathConfigurationName()); + .getByName(aotSourceSet.getCompileClasspathConfigurationName()); compileClasspath.extendsFrom(aotClasspath); - Provider resourcesOutput = project.getLayout().getBuildDirectory() - .dir("generated/" + aotSourceSet.getName() + "Resources"); - TaskProvider processAot = project.getTasks().register(PROCESS_AOT_TASK_NAME, ProcessAot.class, - (task) -> { - configureAotTask(project, aotSourceSet, task, mainSourceSet, resourcesOutput); - task.getApplicationMainClass() - .set(resolveMainClassName.flatMap(ResolveMainClassName::readMainClassName)); - task.setClasspath(aotClasspath); - }); + Provider resourcesOutput = project.getLayout() + .getBuildDirectory() + .dir("generated/" + aotSourceSet.getName() + "Resources"); + TaskProvider processAot = project.getTasks() + .register(PROCESS_AOT_TASK_NAME, ProcessAot.class, (task) -> { + configureAotTask(project, aotSourceSet, task, mainSourceSet, resourcesOutput); + task.getApplicationMainClass() + .set(resolveMainClassName.flatMap(ResolveMainClassName::readMainClassName)); + task.setClasspath(aotClasspath); + }); aotSourceSet.getJava().srcDir(processAot.map(ProcessAot::getSourcesOutput)); aotSourceSet.getResources().srcDir(resourcesOutput); ConfigurableFileCollection classesOutputFiles = project.files(processAot.map(ProcessAot::getClassesOutput)); @@ -137,10 +139,10 @@ public class SpringBootAotPlugin implements Plugin { private void configureAotTask(Project project, SourceSet sourceSet, AbstractAot task, SourceSet inputSourceSet, Provider resourcesOutput) { task.getSourcesOutput() - .set(project.getLayout().getBuildDirectory().dir("generated/" + sourceSet.getName() + "Sources")); + .set(project.getLayout().getBuildDirectory().dir("generated/" + sourceSet.getName() + "Sources")); task.getResourcesOutput().set(resourcesOutput); task.getClassesOutput() - .set(project.getLayout().getBuildDirectory().dir("generated/" + sourceSet.getName() + "Classes")); + .set(project.getLayout().getBuildDirectory().dir("generated/" + sourceSet.getName() + "Classes")); task.getGroupId().set(project.provider(() -> String.valueOf(project.getGroup()))); task.getArtifactId().set(project.provider(() -> project.getName())); } @@ -148,7 +150,7 @@ public class SpringBootAotPlugin implements Plugin { @SuppressWarnings("unchecked") private Configuration createAotProcessingClasspath(Project project, String taskName, SourceSet inputSourceSet) { Configuration base = project.getConfigurations() - .getByName(inputSourceSet.getRuntimeClasspathConfigurationName()); + .getByName(inputSourceSet.getRuntimeClasspathConfigurationName()); Configuration aotClasspath = project.getConfigurations().create(taskName + "Classpath", (classpath) -> { classpath.setCanBeConsumed(false); classpath.setCanBeResolved(true); @@ -166,8 +168,9 @@ public class SpringBootAotPlugin implements Plugin { private void configureDependsOn(Project project, SourceSet aotSourceSet, TaskProvider processAot) { - project.getTasks().named(aotSourceSet.getProcessResourcesTaskName()) - .configure((processResources) -> processResources.dependsOn(processAot)); + project.getTasks() + .named(aotSourceSet.getProcessResourcesTaskName()) + .configure((processResources) -> processResources.dependsOn(processAot)); } private void registerProcessTestAotTask(Project project, SourceSet mainSourceSet, SourceSet aotTestSourceSet, @@ -175,22 +178,23 @@ public class SpringBootAotPlugin implements Plugin { Configuration aotClasspath = createAotProcessingClasspath(project, PROCESS_TEST_AOT_TASK_NAME, testSourceSet); addJUnitPlatformLauncherDependency(project, aotClasspath); Configuration compileClasspath = project.getConfigurations() - .getByName(aotTestSourceSet.getCompileClasspathConfigurationName()); + .getByName(aotTestSourceSet.getCompileClasspathConfigurationName()); compileClasspath.extendsFrom(aotClasspath); - Provider resourcesOutput = project.getLayout().getBuildDirectory() - .dir("generated/" + aotTestSourceSet.getName() + "Resources"); - TaskProvider processTestAot = project.getTasks().register(PROCESS_TEST_AOT_TASK_NAME, - ProcessTestAot.class, (task) -> { - configureAotTask(project, aotTestSourceSet, task, testSourceSet, resourcesOutput); - task.setClasspath(aotClasspath); - task.setClasspathRoots(testSourceSet.getOutput()); - }); + Provider resourcesOutput = project.getLayout() + .getBuildDirectory() + .dir("generated/" + aotTestSourceSet.getName() + "Resources"); + TaskProvider processTestAot = project.getTasks() + .register(PROCESS_TEST_AOT_TASK_NAME, ProcessTestAot.class, (task) -> { + configureAotTask(project, aotTestSourceSet, task, testSourceSet, resourcesOutput); + task.setClasspath(aotClasspath); + task.setClasspathRoots(testSourceSet.getOutput()); + }); aotTestSourceSet.getJava().srcDir(processTestAot.map(ProcessTestAot::getSourcesOutput)); aotTestSourceSet.getResources().srcDir(resourcesOutput); project.getDependencies().add(aotClasspath.getName(), project.files(mainSourceSet.getOutput())); project.getDependencies().add(aotClasspath.getName(), project.files(testSourceSet.getOutput())); ConfigurableFileCollection classesOutputFiles = project - .files(processTestAot.map(ProcessTestAot::getClassesOutput)); + .files(processTestAot.map(ProcessTestAot::getClassesOutput)); testSourceSet.setRuntimeClasspath(testSourceSet.getRuntimeClasspath().plus(classesOutputFiles)); project.getDependencies().add(aotTestSourceSet.getImplementationConfigurationName(), classesOutputFiles); configureDependsOn(project, aotTestSourceSet, processTestAot); @@ -199,7 +203,7 @@ public class SpringBootAotPlugin implements Plugin { private void addJUnitPlatformLauncherDependency(Project project, Configuration configuration) { DependencyHandler dependencyHandler = project.getDependencies(); Dependency springBootDependencies = dependencyHandler - .create(dependencyHandler.platform(SpringBootPlugin.BOM_COORDINATES)); + .create(dependencyHandler.platform(SpringBootPlugin.BOM_COORDINATES)); DependencySet dependencies = configuration.getDependencies(); dependencies.add(springBootDependencies); dependencies.add(dependencyHandler.create("org.junit.platform:junit-platform-launcher")); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java index b80d0b377d..feb988ed74 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/WarPluginAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,36 +64,40 @@ class WarPluginAction implements PluginApplicationAction { } private void classifyWarTask(Project project) { - project.getTasks().named(WarPlugin.WAR_TASK_NAME, War.class) - .configure((war) -> war.getArchiveClassifier().convention("plain")); + project.getTasks() + .named(WarPlugin.WAR_TASK_NAME, War.class) + .configure((war) -> war.getArchiveClassifier().convention("plain")); } private TaskProvider configureBootWarTask(Project project) { Configuration developmentOnly = project.getConfigurations() - .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.DEVELOPMENT_ONLY_CONFIGURATION_NAME); Configuration productionRuntimeClasspath = project.getConfigurations() - .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); - Callable classpath = () -> project.getExtensions().getByType(SourceSetContainer.class) - .getByName(SourceSet.MAIN_SOURCE_SET_NAME).getRuntimeClasspath() - .minus(providedRuntimeConfiguration(project)).minus((developmentOnly.minus(productionRuntimeClasspath))) - .filter(new JarTypeFileSpec()); + .getByName(SpringBootPlugin.PRODUCTION_RUNTIME_CLASSPATH_CONFIGURATION_NAME); + Callable classpath = () -> project.getExtensions() + .getByType(SourceSetContainer.class) + .getByName(SourceSet.MAIN_SOURCE_SET_NAME) + .getRuntimeClasspath() + .minus(providedRuntimeConfiguration(project)) + .minus((developmentOnly.minus(productionRuntimeClasspath))) + .filter(new JarTypeFileSpec()); TaskProvider resolveMainClassName = project.getTasks() - .named(SpringBootPlugin.RESOLVE_MAIN_CLASS_NAME_TASK_NAME, ResolveMainClassName.class); - TaskProvider bootWarProvider = project.getTasks().register(SpringBootPlugin.BOOT_WAR_TASK_NAME, - BootWar.class, (bootWar) -> { - bootWar.setGroup(BasePlugin.BUILD_GROUP); - bootWar.setDescription("Assembles an executable war archive containing webapp" - + " content, and the main classes and their dependencies."); - bootWar.providedClasspath(providedRuntimeConfiguration(project)); - bootWar.setClasspath(classpath); - Provider manifestStartClass = project - .provider(() -> (String) bootWar.getManifest().getAttributes().get("Start-Class")); - bootWar.getMainClass() - .convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() - ? manifestStartClass : resolveMainClassName.get().readMainClassName())); - bootWar.getTargetJavaVersion() - .set(project.provider(() -> javaPluginExtension(project).getTargetCompatibility())); - }); + .named(SpringBootPlugin.RESOLVE_MAIN_CLASS_NAME_TASK_NAME, ResolveMainClassName.class); + TaskProvider bootWarProvider = project.getTasks() + .register(SpringBootPlugin.BOOT_WAR_TASK_NAME, BootWar.class, (bootWar) -> { + bootWar.setGroup(BasePlugin.BUILD_GROUP); + bootWar.setDescription("Assembles an executable war archive containing webapp" + + " content, and the main classes and their dependencies."); + bootWar.providedClasspath(providedRuntimeConfiguration(project)); + bootWar.setClasspath(classpath); + Provider manifestStartClass = project + .provider(() -> (String) bootWar.getManifest().getAttributes().get("Start-Class")); + bootWar.getMainClass() + .convention(resolveMainClassName.flatMap((resolver) -> manifestStartClass.isPresent() + ? manifestStartClass : resolveMainClassName.get().readMainClassName())); + bootWar.getTargetJavaVersion() + .set(project.provider(() -> javaPluginExtension(project).getTargetCompatibility())); + }); bootWarProvider.map(War::getClasspath); return bootWarProvider; } @@ -104,8 +108,9 @@ class WarPluginAction implements PluginApplicationAction { } private void configureBootBuildImageTask(Project project, TaskProvider bootWar) { - project.getTasks().named(SpringBootPlugin.BOOT_BUILD_IMAGE_TASK_NAME, BootBuildImage.class) - .configure((buildImage) -> buildImage.getArchiveFile().set(bootWar.get().getArchiveFile())); + project.getTasks() + .named(SpringBootPlugin.BOOT_BUILD_IMAGE_TASK_NAME, BootBuildImage.class) + .configure((buildImage) -> buildImage.getArchiveFile().set(bootWar.get().getArchiveFile())); } private void configureArtifactPublication(TaskProvider bootWar) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/aot/ProcessTestAot.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/aot/ProcessTestAot.java index 11de712577..15e2a2d3eb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/aot/ProcessTestAot.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/aot/ProcessTestAot.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,8 +78,11 @@ public class ProcessTestAot extends AbstractAot { @TaskAction public void exec() { List args = new ArrayList<>(); - args.add(getClasspathRoots().getFiles().stream().filter(File::exists).map(File::getAbsolutePath) - .collect(Collectors.joining(File.pathSeparator))); + args.add(getClasspathRoots().getFiles() + .stream() + .filter(File::exists) + .map(File::getAbsolutePath) + .collect(Collectors.joining(File.pathSeparator))); args.addAll(processorArgs()); setArgs(args); super.exec(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java index 3372194089..ec13bc150d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ public abstract class BuildInfo extends DefaultTask { this.properties.getNameIfNotExcluded(), this.properties.getTimeIfNotExcluded(), this.properties.getAdditionalIfNotExcluded()); new BuildPropertiesWriter(new File(getDestinationDir().get().getAsFile(), "build-info.properties")) - .writeBuildProperties(details); + .writeBuildProperties(details); } catch (IOException ex) { throw new TaskExecutionException(this, ex); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java index a78afe2fae..5ace201ad7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ public abstract class BuildInfoProperties implements Serializable { getGroup().convention(project.provider(() -> project.getGroup().toString())); getVersion().convention(project.provider(() -> project.getVersion().toString())); getArtifact() - .convention(project.provider(() -> project.findProperty("archivesBaseName")).map(Object::toString)); + .convention(project.provider(() -> project.findProperty("archivesBaseName")).map(Object::toString)); getName().convention(project.provider(project::getName)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImage.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImage.java index b102926269..0817bd731e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImage.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImage.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,8 +78,9 @@ public abstract class BootBuildImage extends DefaultTask { public BootBuildImage() { this.projectName = getProject().getName(); Project project = getProject(); - Property projectVersion = project.getObjects().property(String.class) - .convention(project.provider(() -> project.getVersion().toString())); + Property projectVersion = project.getObjects() + .property(String.class) + .convention(project.provider(() -> project.getVersion().toString())); getImageName().convention(project.provider(() -> { ImageName imageName = ImageName.of(this.projectName); if ("unspecified".equals(projectVersion.get())) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java index 76b1f75601..fac4f6969f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootWar.java @@ -165,7 +165,7 @@ public abstract class BootWar extends War implements BootArchive { public void providedClasspath(Object... classpath) { FileCollection existingClasspath = this.providedClasspath; this.providedClasspath = getProject() - .files((existingClasspath != null) ? existingClasspath : Collections.emptyList(), classpath); + .files((existingClasspath != null) ? existingClasspath : Collections.emptyList(), classpath); } /** diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java index 7f9ece9275..508ef2af32 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootZipCopyAction.java @@ -74,11 +74,11 @@ import org.springframework.util.StringUtils; class BootZipCopyAction implements CopyAction { static final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, Calendar.FEBRUARY, 1, 0, 0, 0) - .getTimeInMillis(); + .getTimeInMillis(); private static final Pattern REACHABILITY_METADATA_PROPERTIES_LOCATION_PATTERN = Pattern - .compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", - ".*", ".*")); + .compile(ReachabilityMetadataProperties.REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(".*", ".*", + ".*")); private final File output; @@ -352,14 +352,14 @@ class BootZipCopyAction implements CopyAction { Set excludes = new LinkedHashSet<>(); for (Map.Entry entry : this.writtenLibraries.entrySet()) { DependencyDescriptor descriptor = BootZipCopyAction.this.resolvedDependencies - .find(entry.getValue().getFile()); + .find(entry.getValue().getFile()); LibraryCoordinates coordinates = (descriptor != null) ? descriptor.getCoordinates() : null; FileCopyDetails propertiesFile = (coordinates != null) ? this.reachabilityMetadataProperties - .get(ReachabilityMetadataProperties.getLocation(coordinates)) : null; + .get(ReachabilityMetadataProperties.getLocation(coordinates)) : null; if (propertiesFile != null) { try (InputStream inputStream = propertiesFile.open()) { ReachabilityMetadataProperties properties = ReachabilityMetadataProperties - .fromInputStream(inputStream); + .fromInputStream(inputStream); if (properties.isOverridden()) { excludes.add(entry.getKey()); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java index b9794f8b91..6199890449 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -309,13 +309,15 @@ public abstract class LayeredSpec { ContentSelector asLibrarySelector(Function> filterFactory) { Layer layer = new Layer(getIntoLayer()); - List> includeFilters = getIncludes().stream().map(filterFactory) - .collect(Collectors.toCollection(ArrayList::new)); + List> includeFilters = getIncludes().stream() + .map(filterFactory) + .collect(Collectors.toCollection(ArrayList::new)); if (this.includeProjectDependencies) { includeFilters.add(Library::isLocal); } - List> excludeFilters = getExcludes().stream().map(filterFactory) - .collect(Collectors.toCollection(ArrayList::new)); + List> excludeFilters = getExcludes().stream() + .map(filterFactory) + .collect(Collectors.toCollection(ArrayList::new)); if (this.excludeProjectDependencies) { excludeFilters.add(Library::isLocal); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java index b4644094b0..630f15794b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/ResolvedDependencies.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,8 +50,11 @@ class ResolvedDependencies { } void processConfiguration(Project project, Configuration configuration) { - Set localProjectIds = project.getRootProject().getAllprojects().stream().map(this::projectId) - .collect(Collectors.toSet()); + Set localProjectIds = project.getRootProject() + .getAllprojects() + .stream() + .map(this::projectId) + .collect(Collectors.toSet()); this.configurationDependencies.put(configuration, new ResolvedConfigurationDependencies(localProjectIds, configuration.getResolvedConfiguration())); } @@ -83,7 +86,7 @@ class ResolvedDependencies { for (ResolvedArtifact resolvedArtifact : lenientConfiguration.getArtifacts()) { ModuleVersionIdentifier id = resolvedArtifact.getModuleVersion().getId(); boolean projectDependency = projectDependencyIds - .contains(id.getGroup() + ":" + id.getName() + ":" + id.getVersion()); + .contains(id.getGroup() + ":" + id.getName() + ":" + id.getVersion()); this.dependencies.put(resolvedArtifact.getFile(), new DependencyDescriptor( new ModuleVersionIdentifierLibraryCoordinates(id), projectDependency)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java index e8c779803b..7b3e241388 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/TaskConfigurationAvoidanceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,12 +47,14 @@ class TaskConfigurationAvoidanceTests { @ArchTest void noApisThatCauseEagerTaskConfigurationShouldBeCalled(JavaClasses classes) { ProhibitedMethods prohibited = new ProhibitedMethods(); - prohibited.on(TaskContainer.class).methodsNamed("create", "findByPath, getByPath").method("withType", - Class.class, Action.class); + prohibited.on(TaskContainer.class) + .methodsNamed("create", "findByPath, getByPath") + .method("withType", Class.class, Action.class); prohibited.on(TaskCollection.class).methodsNamed("findByName", "getByName"); - ArchRuleDefinition.noClasses().should() - .callMethodWhere(DescribedPredicate.describe("it would cause eager task configuration", prohibited)) - .check(classes); + ArchRuleDefinition.noClasses() + .should() + .callMethodWhere(DescribedPredicate.describe("it would cause eager task configuration", prohibited)) + .check(classes); } static class DoNotIncludeTests implements ImportOption { @@ -99,7 +101,7 @@ class TaskConfigurationAvoidanceTests { private ProhibitedConfigurer method(String name, Class... parameterTypes) { ProhibitedMethods.this.prohibited - .add(new ProhibitMethod(this.type, name, Arrays.asList(parameterTypes))); + .add(new ProhibitMethod(this.type, name, Arrays.asList(parameterTypes))); return this; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java index 4c952602f5..8483a52d79 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/IntegratingWithActuatorDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,13 +44,13 @@ class IntegratingWithActuatorDocumentationTests { void basicBuildInfo() { this.gradleBuild.script("src/docs/gradle/integrating-with-actuator/build-info-basic").build("bootBuildInfo"); assertThat(new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties")) - .isFile(); + .isFile(); } @TestTemplate void buildInfoCustomValues() { this.gradleBuild.script("src/docs/gradle/integrating-with-actuator/build-info-custom-values") - .build("bootBuildInfo"); + .build("bootBuildInfo"); File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = buildInfoProperties(file); @@ -64,7 +64,7 @@ class IntegratingWithActuatorDocumentationTests { @TestTemplate void buildInfoAdditional() { this.gradleBuild.script("src/docs/gradle/integrating-with-actuator/build-info-additional") - .build("bootBuildInfo"); + .build("bootBuildInfo"); File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = buildInfoProperties(file); @@ -75,7 +75,7 @@ class IntegratingWithActuatorDocumentationTests { @TestTemplate void buildInfoExcludeTime() { this.gradleBuild.script("src/docs/gradle/integrating-with-actuator/build-info-exclude-time") - .build("bootBuildInfo"); + .build("bootBuildInfo"); File file = new File(this.gradleBuild.getProjectDir(), "build/resources/main/META-INF/build-info.properties"); assertThat(file).isFile(); Properties properties = buildInfoProperties(file); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java index be33e3567d..e33ee06b03 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/ManagingDependenciesDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,14 +44,16 @@ class ManagingDependenciesDocumentationTests { @TestTemplate void customManagedVersions() { - assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/custom-version").build("slf4jVersion") - .getOutput()).contains("1.7.20"); + assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/custom-version") + .build("slf4jVersion") + .getOutput()).contains("1.7.20"); } @TestTemplate void dependencyManagementInIsolation() { assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/configure-bom") - .build("dependencyManagement").getOutput()).contains("org.springframework.boot:spring-boot-starter "); + .build("dependencyManagement") + .getOutput()).contains("org.springframework.boot:spring-boot-starter "); } @TestTemplate @@ -59,21 +61,23 @@ class ManagingDependenciesDocumentationTests { assumingThat(this.gradleBuild.getDsl() == Dsl.KOTLIN, () -> assertThat( this.gradleBuild.script("src/docs/gradle/managing-dependencies/configure-bom-with-plugins") - .build("dependencyManagement").getOutput()) - .contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT")); + .build("dependencyManagement") + .getOutput()) + .contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT")); } @TestTemplate void configurePlatform() { assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/configure-platform") - .build("dependencies", "--configuration", "compileClasspath").getOutput()) - .contains("org.springframework.boot:spring-boot-starter "); + .build("dependencies", "--configuration", "compileClasspath") + .getOutput()).contains("org.springframework.boot:spring-boot-starter "); } @TestTemplate void customManagedVersionsWithPlatform() { assertThat(this.gradleBuild.script("src/docs/gradle/managing-dependencies/custom-version-with-platform") - .build("dependencies", "--configuration", "compileClasspath").getOutput()).contains("1.7.20"); + .build("dependencies", "--configuration", "compileClasspath") + .getOutput()).contains("1.7.20"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java index c13b63795a..562a3f5b13 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PackagingDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -75,7 +75,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -87,7 +87,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -99,7 +99,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.ExampleApplication"); + .isEqualTo("com.example.ExampleApplication"); } } @@ -166,7 +166,7 @@ class PackagingDocumentationTests { assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); + .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); } } @@ -222,8 +222,10 @@ class PackagingDocumentationTests { try (JarFile jar = new JarFile(file)) { JarEntry entry = jar.getJarEntry("BOOT-INF/layers.idx"); assertThat(entry).isNotNull(); - assertThat(Collections.list(jar.entries()).stream().map(JarEntry::getName) - .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isNotEmpty(); + assertThat(Collections.list(jar.entries()) + .stream() + .map(JarEntry::getName) + .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isNotEmpty(); } } @@ -236,100 +238,105 @@ class PackagingDocumentationTests { try (JarFile jar = new JarFile(file)) { JarEntry entry = jar.getJarEntry("BOOT-INF/layers.idx"); assertThat(entry).isNotNull(); - assertThat(Collections.list(jar.entries()).stream().map(JarEntry::getName) - .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isEmpty(); + assertThat(Collections.list(jar.entries()) + .stream() + .map(JarEntry::getName) + .filter((name) -> name.startsWith("BOOT-INF/lib/spring-boot"))).isEmpty(); } } @TestTemplate void bootBuildImageWithBuilder() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-builder") - .build("bootBuildImageBuilder"); + .build("bootBuildImageBuilder"); assertThat(result.getOutput()).contains("builder=mine/java-cnb-builder").contains("runImage=mine/java-cnb-run"); } @TestTemplate void bootBuildImageWithCustomBuildpackJvmVersion() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-env") - .build("bootBuildImageEnvironment"); + .build("bootBuildImageEnvironment"); assertThat(result.getOutput()).contains("BP_JVM_VERSION=17"); } @TestTemplate void bootBuildImageWithCustomProxySettings() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-env-proxy") - .build("bootBuildImageEnvironment"); + .build("bootBuildImageEnvironment"); assertThat(result.getOutput()).contains("HTTP_PROXY=http://proxy.example.com") - .contains("HTTPS_PROXY=https://proxy.example.com"); + .contains("HTTPS_PROXY=https://proxy.example.com"); } @TestTemplate void bootBuildImageWithCustomRuntimeConfiguration() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-env-runtime") - .build("bootBuildImageEnvironment"); + .build("bootBuildImageEnvironment"); assertThat(result.getOutput()).contains("BPE_DELIM_JAVA_TOOL_OPTIONS= ") - .contains("BPE_APPEND_JAVA_TOOL_OPTIONS=-XX:+HeapDumpOnOutOfMemoryError"); + .contains("BPE_APPEND_JAVA_TOOL_OPTIONS=-XX:+HeapDumpOnOutOfMemoryError"); } @TestTemplate void bootBuildImageWithCustomImageName() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-name") - .build("bootBuildImageName"); + .build("bootBuildImageName"); assertThat(result.getOutput()).contains("example.com/library/" + this.gradleBuild.getProjectDir().getName()); } @TestTemplate void bootBuildImageWithDockerHostMinikube() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-host") - .build("bootBuildImageDocker"); - assertThat(result.getOutput()).contains("host=tcp://192.168.99.100:2376").contains("tlsVerify=true") - .contains("certPath=/home/user/.minikube/certs"); + .build("bootBuildImageDocker"); + assertThat(result.getOutput()).contains("host=tcp://192.168.99.100:2376") + .contains("tlsVerify=true") + .contains("certPath=/home/user/.minikube/certs"); } @TestTemplate void bootBuildImageWithDockerHostPodman() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-host-podman") - .build("bootBuildImageDocker"); + .build("bootBuildImageDocker"); assertThat(result.getOutput()).contains("host=unix:///run/user/1000/podman/podman.sock") - .contains("bindHostToBuilder=true"); + .contains("bindHostToBuilder=true"); } @TestTemplate void bootBuildImageWithDockerUserAuth() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-auth-user") - .build("bootBuildImageDocker"); - assertThat(result.getOutput()).contains("username=user").contains("password=secret") - .contains("url=https://docker.example.com/v1/").contains("email=user@example.com"); + .build("bootBuildImageDocker"); + assertThat(result.getOutput()).contains("username=user") + .contains("password=secret") + .contains("url=https://docker.example.com/v1/") + .contains("email=user@example.com"); } @TestTemplate void bootBuildImageWithDockerTokenAuth() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-docker-auth-token") - .build("bootBuildImageDocker"); + .build("bootBuildImageDocker"); assertThat(result.getOutput()).contains("token=9cbaf023786cd7..."); } @TestTemplate void bootBuildImagePublish() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-publish") - .build("bootBuildImagePublish"); + .build("bootBuildImagePublish"); assertThat(result.getOutput()).contains("true"); } @TestTemplate void bootBuildImageWithBuildpacks() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-buildpacks") - .build("bootBuildImageBuildpacks"); + .build("bootBuildImageBuildpacks"); assertThat(result.getOutput()).contains("file:///path/to/example-buildpack.tgz") - .contains("urn:cnb:builder:paketo-buildpacks/java"); + .contains("urn:cnb:builder:paketo-buildpacks/java"); } @TestTemplate void bootBuildImageWithCaches() { BuildResult result = this.gradleBuild.script("src/docs/gradle/packaging/boot-build-image-caches") - .build("bootBuildImageCaches"); + .build("bootBuildImageCaches"); assertThat(result.getOutput()).containsPattern("buildCache=cache-gradle-[\\d]+.build") - .containsPattern("launchCache=cache-gradle-[\\d]+.launch"); + .containsPattern("launchCache=cache-gradle-[\\d]+.launch"); } protected void jarFile(File file) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java index 32bd9b443f..10ff323e83 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/PublishingDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -37,8 +37,9 @@ class PublishingDocumentationTests { @TestTemplate void mavenPublish() { - assertThat(this.gradleBuild.script("src/docs/gradle/publishing/maven-publish").build("publishingConfiguration") - .getOutput()).contains("MavenPublication").contains("https://repo.example.com"); + assertThat(this.gradleBuild.script("src/docs/gradle/publishing/maven-publish") + .build("publishingConfiguration") + .getOutput()).contains("MavenPublication").contains("https://repo.example.com"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java index 11db7f5659..71833a8e38 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/docs/RunningDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,46 +44,51 @@ class RunningDocumentationTests { void bootRunMain() throws IOException { writeMainClass(); assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-main").build("bootRun").getOutput()) - .contains("com.example.ExampleApplication"); + .contains("com.example.ExampleApplication"); } @TestTemplate void applicationPluginMainClassName() throws IOException { writeMainClass(); assertThat(this.gradleBuild.script("src/docs/gradle/running/application-plugin-main-class-name") - .build("bootRun").getOutput()).contains("com.example.ExampleApplication"); + .build("bootRun") + .getOutput()).contains("com.example.ExampleApplication"); } @TestTemplate void springBootDslMainClassName() throws IOException { writeMainClass(); - assertThat(this.gradleBuild.script("src/docs/gradle/running/spring-boot-dsl-main-class-name").build("bootRun") - .getOutput()).contains("com.example.ExampleApplication"); + assertThat(this.gradleBuild.script("src/docs/gradle/running/spring-boot-dsl-main-class-name") + .build("bootRun") + .getOutput()).contains("com.example.ExampleApplication"); } @TestTemplate void bootRunSourceResources() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-source-resources") - .build("configuredClasspath").getOutput()).contains(new File("src/main/resources").getPath()); + .build("configuredClasspath") + .getOutput()).contains(new File("src/main/resources").getPath()); } @TestTemplate void bootRunDisableOptimizedLaunch() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-disable-optimized-launch") - .build("optimizedLaunch").getOutput()).contains("false"); + .build("optimizedLaunch") + .getOutput()).contains("false"); } @TestTemplate void bootRunSystemPropertyDefaultValue() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-system-property") - .build("configuredSystemProperties").getOutput()).contains("com.example.property = default"); + .build("configuredSystemProperties") + .getOutput()).contains("com.example.property = default"); } @TestTemplate void bootRunSystemProperty() { assertThat(this.gradleBuild.script("src/docs/gradle/running/boot-run-system-property") - .build("-Pexample=custom", "configuredSystemProperties").getOutput()) - .contains("com.example.property = custom"); + .build("-Pexample=custom", "configuredSystemProperties") + .getOutput()).contains("com.example.property = custom"); } private void writeMainClass() throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java index c584b3deda..1d4e130e11 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/dsl/BuildInfoDslIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void basicJar() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); @@ -55,7 +55,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void jarWithCustomName() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", "foo"); @@ -66,7 +66,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void basicWar() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); @@ -77,7 +77,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void warWithCustomName() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", "foo"); @@ -88,7 +88,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void additionalProperties() { assertThat(this.gradleBuild.build("bootBuildInfo", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Properties properties = buildInfoProperties(); assertThat(properties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName()); assertThat(properties).containsEntry("build.artifact", this.gradleBuild.getProjectDir().getName()); @@ -101,7 +101,7 @@ class BuildInfoDslIntegrationTests { @TestTemplate void classesDependency() { assertThat(this.gradleBuild.build("classes", "--stacktrace").task(":bootBuildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } private Properties buildInfoProperties() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java index dad0414b88..3e18bfd59e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/junit/GradleCompatibilityExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,11 +49,12 @@ final class GradleCompatibilityExtension implements TestTemplateInvocationContex public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { Stream gradleVersions = GRADLE_VERSIONS.stream(); GradleCompatibility gradleCompatibility = AnnotationUtils - .findAnnotation(context.getRequiredTestClass(), GradleCompatibility.class).get(); + .findAnnotation(context.getRequiredTestClass(), GradleCompatibility.class) + .get(); if (StringUtils.hasText(gradleCompatibility.versionsLessThan())) { GradleVersion upperExclusive = GradleVersion.version(gradleCompatibility.versionsLessThan()); gradleVersions = gradleVersions - .filter((version) -> GradleVersion.version(version).compareTo(upperExclusive) < 0); + .filter((version) -> GradleVersion.version(version).compareTo(upperExclusive) < 0); } return gradleVersions.flatMap((version) -> { List invocationContexts = new ArrayList<>(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java index 1354085b9f..d30629bb32 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/ApplicationPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,37 +55,37 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void noBootDistributionWithoutApplicationPluginApplied() { assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot").getOutput()) - .contains("boot exists = false"); + .contains("boot exists = false"); } @TestTemplate void applyingApplicationPluginCreatesBootDistribution() { assertThat(this.gradleBuild.build("distributionExists", "-PdistributionName=boot", "-PapplyApplicationPlugin") - .getOutput()).contains("boot exists = true"); + .getOutput()).contains("boot exists = true"); } @TestTemplate void noBootStartScriptsTaskWithoutApplicationPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts").getOutput()) - .contains("bootStartScripts exists = false"); + .contains("bootStartScripts exists = false"); } @TestTemplate void applyingApplicationPluginCreatesBootStartScriptsTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootStartScripts", "-PapplyApplicationPlugin") - .getOutput()).contains("bootStartScripts exists = true"); + .getOutput()).contains("bootStartScripts exists = true"); } @TestTemplate void createsBootStartScriptsTaskUsesApplicationPluginsDefaultJvmOpts() { assertThat(this.gradleBuild.build("startScriptsDefaultJvmOpts", "-PapplyApplicationPlugin").getOutput()) - .contains("bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]"); + .contains("bootStartScripts defaultJvmOpts = [-Dcom.example.a=alpha, -Dcom.example.b=bravo]"); } @TestTemplate void zipDistributionForJarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip"); assertThat(distribution).isFile(); @@ -97,7 +97,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void tarDistributionForJarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); @@ -109,7 +109,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void zipDistributionForWarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistZip").task(":bootDistZip").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.zip"); assertThat(distribution).isFile(); @@ -121,7 +121,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void tarDistributionForWarCanBeBuilt() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); @@ -133,7 +133,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void applicationNameCanBeUsedToCustomizeDistributionName() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/custom-boot.tar"); assertThat(distribution).isFile(); String name = this.gradleBuild.getProjectDir().getName(); @@ -145,7 +145,7 @@ class ApplicationPluginActionIntegrationTests { @TestTemplate void scriptsHaveCorrectPermissions() throws IOException { assertThat(this.gradleBuild.build("bootDistTar").task(":bootDistTar").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String name = this.gradleBuild.getProjectDir().getName(); File distribution = new File(this.gradleBuild.getProjectDir(), "build/distributions/" + name + "-boot.tar"); assertThat(distribution).isFile(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java index 1041969f10..9ea28687c7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -37,14 +37,16 @@ class DependencyManagementPluginActionIntegrationTests { @TestTemplate void noDependencyManagementIsAppliedByDefault() { - assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement").task(":doesNotHaveDependencyManagement") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("doesNotHaveDependencyManagement") + .task(":doesNotHaveDependencyManagement") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void bomIsImportedWhenDependencyManagementPluginIsApplied() { assertThat(this.gradleBuild.build("hasDependencyManagement", "-PapplyDependencyManagementPlugin") - .task(":hasDependencyManagement").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + .task(":hasDependencyManagement") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java index cde3db181c..551d9cd51c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/JavaPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,52 +48,53 @@ class JavaPluginActionIntegrationTests { @TestTemplate void noBootJarTaskWithoutJavaPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootJar").getOutput()) - .contains("bootJar exists = false"); + .contains("bootJar exists = false"); } @TestTemplate void applyingJavaPluginCreatesBootJarTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootJar", "-PapplyJavaPlugin").getOutput()) - .contains("bootJar exists = true"); + .contains("bootJar exists = true"); } @TestTemplate void noBootRunTaskWithoutJavaPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootRun").getOutput()) - .contains("bootRun exists = false"); + .contains("bootRun exists = false"); } @TestTemplate void applyingJavaPluginCreatesBootRunTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootRun", "-PapplyJavaPlugin").getOutput()) - .contains("bootRun exists = true"); + .contains("bootRun exists = true"); } @TestTemplate void javaCompileTasksUseUtf8Encoding() { assertThat(this.gradleBuild.build("javaCompileEncoding", "-PapplyJavaPlugin").getOutput()) - .contains("compileJava = UTF-8").contains("compileTestJava = UTF-8"); + .contains("compileJava = UTF-8") + .contains("compileTestJava = UTF-8"); } @TestTemplate void javaCompileTasksUseParametersCompilerFlagByDefault() { assertThat(this.gradleBuild.build("javaCompileTasksCompilerArgs").getOutput()) - .contains("compileJava compiler args: [-parameters]") - .contains("compileTestJava compiler args: [-parameters]"); + .contains("compileJava compiler args: [-parameters]") + .contains("compileTestJava compiler args: [-parameters]"); } @TestTemplate void javaCompileTasksUseParametersAndAdditionalCompilerFlags() { assertThat(this.gradleBuild.build("javaCompileTasksCompilerArgs").getOutput()) - .contains("compileJava compiler args: [-parameters, -Xlint:all]") - .contains("compileTestJava compiler args: [-parameters, -Xlint:all]"); + .contains("compileJava compiler args: [-parameters, -Xlint:all]") + .contains("compileTestJava compiler args: [-parameters, -Xlint:all]"); } @TestTemplate void javaCompileTasksCanOverrideDefaultParametersCompilerFlag() { assertThat(this.gradleBuild.build("javaCompileTasksCompilerArgs").getOutput()) - .contains("compileJava compiler args: [-Xlint:all]") - .contains("compileTestJava compiler args: [-Xlint:all]"); + .contains("compileJava compiler args: [-Xlint:all]") + .contains("compileTestJava compiler args: [-Xlint:all]"); } @TestTemplate @@ -120,7 +121,7 @@ class JavaPluginActionIntegrationTests { File libs = new File(this.gradleBuild.getProjectDir(), "libs"); libs.mkdirs(); new JarOutputStream(new FileOutputStream(new File(libs, "spring-boot-configuration-processor-1.2.3.jar"))) - .close(); + .close(); BuildResult result = this.gradleBuild.build("compileJava"); assertThat(result.task(":compileJava").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()).contains("compileJava compiler args: [-parameters, -Aorg.springframework.boot." @@ -139,27 +140,32 @@ class JavaPluginActionIntegrationTests { @TestTemplate void applyingJavaPluginCreatesDevelopmentOnlyConfiguration() { assertThat(this.gradleBuild - .build("configurationExists", "-PconfigurationName=developmentOnly", "-PapplyJavaPlugin").getOutput()) - .contains("developmentOnly exists = true"); + .build("configurationExists", "-PconfigurationName=developmentOnly", "-PapplyJavaPlugin") + .getOutput()).contains("developmentOnly exists = true"); } @TestTemplate void productionRuntimeClasspathIsConfiguredWithAttributes() { assertThat(this.gradleBuild - .build("configurationAttributes", "-PconfigurationName=productionRuntimeClasspath", "-PapplyJavaPlugin") - .getOutput()).contains("3 productionRuntimeClasspath attributes:") - .contains("org.gradle.usage: java-runtime").contains("org.gradle.libraryelements: jar") - .contains("org.gradle.dependency.bundling: external"); + .build("configurationAttributes", "-PconfigurationName=productionRuntimeClasspath", "-PapplyJavaPlugin") + .getOutput()).contains("3 productionRuntimeClasspath attributes:") + .contains("org.gradle.usage: java-runtime") + .contains("org.gradle.libraryelements: jar") + .contains("org.gradle.dependency.bundling: external"); } @TestTemplate void productionRuntimeClasspathIsConfiguredWithResolvabilityAndConsumabilityThatMatchesRuntimeClasspath() { - String runtime = this.gradleBuild.build("configurationResolvabilityAndConsumability", - "-PconfigurationName=runtimeClasspath", "-PapplyJavaPlugin").getOutput(); + String runtime = this.gradleBuild + .build("configurationResolvabilityAndConsumability", "-PconfigurationName=runtimeClasspath", + "-PapplyJavaPlugin") + .getOutput(); assertThat(runtime).contains("canBeResolved: true"); assertThat(runtime).contains("canBeConsumed: false"); - String productionRuntime = this.gradleBuild.build("configurationResolvabilityAndConsumability", - "-PconfigurationName=productionRuntimeClasspath", "-PapplyJavaPlugin").getOutput(); + String productionRuntime = this.gradleBuild + .build("configurationResolvabilityAndConsumability", "-PconfigurationName=productionRuntimeClasspath", + "-PapplyJavaPlugin") + .getOutput(); assertThat(productionRuntime).contains("canBeResolved: true"); assertThat(productionRuntime).contains("canBeConsumed: false"); } @@ -177,7 +183,7 @@ class JavaPluginActionIntegrationTests { } } if (!this.gradleBuild.isConfigurationCache() && GradleVersion.version(this.gradleBuild.getGradleVersion()) - .compareTo(GradleVersion.version("7.3.3")) < 0) { + .compareTo(GradleVersion.version("7.3.3")) < 0) { assertThat(configured).containsExactly("help"); } else { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java index 9025861bb8..cdab2b2925 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/KotlinPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,20 +49,22 @@ class KotlinPluginActionIntegrationTests { @TestTemplate void kotlinVersionPropertyIsSet() { String output = this.gradleBuild.build("kotlinVersion", "dependencies", "--configuration", "compileClasspath") - .getOutput(); + .getOutput(); assertThat(output).containsPattern("Kotlin version: [0-9]\\.[0-9]\\.[0-9]+"); } @TestTemplate void kotlinCompileTasksUseJavaParametersFlagByDefault() { assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput()) - .contains("compileKotlin java parameters: true").contains("compileTestKotlin java parameters: true"); + .contains("compileKotlin java parameters: true") + .contains("compileTestKotlin java parameters: true"); } @TestTemplate void kotlinCompileTasksCanOverrideDefaultJavaParametersFlag() { assertThat(this.gradleBuild.build("kotlinCompileTasksJavaParameters").getOutput()) - .contains("compileKotlin java parameters: false").contains("compileTestKotlin java parameters: false"); + .contains("compileKotlin java parameters: false") + .contains("compileTestKotlin java parameters: false"); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/NativeImagePluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/NativeImagePluginActionIntegrationTests.java index 759f91db73..e25e6c0455 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/NativeImagePluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/NativeImagePluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ class NativeImagePluginActionIntegrationTests { @TestTemplate void applyingNativeImagePluginAppliesAotPlugin() { assertThat(this.gradleBuild.build("aotPluginApplied").getOutput()) - .contains("org.springframework.boot.aot applied = true"); + .contains("org.springframework.boot.aot applied = true"); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java index e9424d9032..cf9410917d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/OnlyDependencyManagementIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class OnlyDependencyManagementIntegrationTests { @TestTemplate void dependencyManagementCanBeConfiguredUsingCoordinatesConstant() { assertThat(this.gradleBuild.build("dependencyManagement").getOutput()) - .contains("org.springframework.boot:spring-boot-starter "); + .contains("org.springframework.boot:spring-boot-starter "); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootAotPluginIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootAotPluginIntegrationTests.java index 9603e77b24..61044f636e 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootAotPluginIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootAotPluginIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,25 +42,25 @@ class SpringBootAotPluginIntegrationTests { @TestTemplate void noProcessAotTaskWithoutAotPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=processAot").getOutput()) - .contains("processAot exists = false"); + .contains("processAot exists = false"); } @TestTemplate void noProcessTestAotTaskWithoutAotPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=processTestAot").getOutput()) - .contains("processTestAot exists = false"); + .contains("processTestAot exists = false"); } @TestTemplate void applyingAotPluginCreatesProcessAotTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=processAot").getOutput()) - .contains("processAot exists = true"); + .contains("processAot exists = true"); } @TestTemplate void applyingAotPluginCreatesProcessTestAotTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=processTestAot").getOutput()) - .contains("processTestAot exists = true"); + .contains("processTestAot exists = true"); } @TestTemplate @@ -100,13 +100,13 @@ class SpringBootAotPluginIntegrationTests { writeMainClass("org.springframework.boot", "SpringApplicationAotProcessor"); writeMainClass("com.example", "Main"); assertThat(this.gradleBuild.build("processAot").task(":processAot").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void processTestAotIsSkippedWhenProjectHasNoTestSource() { assertThat(this.gradleBuild.build("processTestAot").task(":processTestAot").getOutcome()) - .isEqualTo(TaskOutcome.NO_SOURCE); + .isEqualTo(TaskOutcome.NO_SOURCE); } private void writeMainClass(String packageName, String className) throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java index 33a676b5ee..adec7e6cd3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class SpringBootPluginIntegrationTests { void failFastWithVersionOfGradle7LowerThanRequired() { BuildResult result = this.gradleBuild.gradleVersion("7.3.3").buildAndFail(); assertThat(result.getOutput()) - .contains("Spring Boot plugin requires Gradle 7.x (7.4 or later). The current version is Gradle 7.3.3"); + .contains("Spring Boot plugin requires Gradle 7.x (7.4 or later). The current version is Gradle 7.3.3"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java index 072baa977d..06cb321a24 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/SpringBootPluginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class SpringBootPluginTests { Project project = GradleProjectBuilder.builder().withProjectDir(this.temp).build(); project.getPlugins().apply(SpringBootPlugin.class); Configuration bootArchives = project.getConfigurations() - .getByName(SpringBootPlugin.BOOT_ARCHIVES_CONFIGURATION_NAME); + .getByName(SpringBootPlugin.BOOT_ARCHIVES_CONFIGURATION_NAME); assertThat(bootArchives.isCanBeResolved()).isFalse(); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java index 524a914cc0..09e23e284a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/plugin/WarPluginActionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,13 +46,13 @@ class WarPluginActionIntegrationTests { @TestTemplate void noBootWarTaskWithoutWarPluginApplied() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar").getOutput()) - .contains("bootWar exists = false"); + .contains("bootWar exists = false"); } @TestTemplate void applyingWarPluginCreatesBootWarTask() { assertThat(this.gradleBuild.build("taskExists", "-PtaskName=bootWar", "-PapplyWarPlugin").getOutput()) - .contains("bootWar exists = true"); + .contains("bootWar exists = true"); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java index b445155504..1d216b7445 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,17 +84,21 @@ class BuildInfoIntegrationTests { @TestTemplate void upToDateWhenExecutedTwiceWithFixedTime() { assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void notUpToDateWhenExecutedTwiceWithFixedTimeAndChangedProjectVersion() { - assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.1.0").build("buildInfo").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.2.0").build("buildInfo").task(":buildInfo") - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.1.0") + .build("buildInfo") + .task(":buildInfo") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("projectVersion", "0.2.0") + .build("buildInfo") + .task(":buildInfo") + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate @@ -111,13 +115,13 @@ class BuildInfoIntegrationTests { @TestTemplate void reproducibleOutputWithFixedTime() throws IOException, InterruptedException { assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); File buildInfoProperties = new File(this.gradleBuild.getProjectDir(), "build/buildInfo/build-info.properties"); String firstHash = FileUtils.sha1Hash(buildInfoProperties); assertThat(buildInfoProperties.delete()).isTrue(); Thread.sleep(1500); assertThat(this.gradleBuild.build("buildInfo", "-PnullTime").task(":buildInfo").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String secondHash = FileUtils.sha1Hash(buildInfoProperties); assertThat(firstHash).isEqualTo(secondHash); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java index 3ba5442adc..6798c5015d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -168,14 +168,15 @@ class BuildInfoTests { void nullAdditionalPropertyProducesInformativeFailure() { BuildInfo task = createTask(createProject("test")); assertThatThrownBy(() -> task.getProperties().getAdditional().put("a", null)) - .hasMessage("Cannot add an entry with a null value to a property of type Map."); + .hasMessage("Cannot add an entry with a null value to a property of type Map."); } private Project createProject(String projectName) { File projectDir = new File(this.temp, projectName); Project project = GradleProjectBuilder.builder().withProjectDir(projectDir).withName(projectName).build(); - ((ProjectInternal) project).getServices().get(GradlePropertiesController.class) - .loadGradlePropertiesFrom(projectDir); + ((ProjectInternal) project).getServices() + .get(GradlePropertiesController.class) + .loadGradlePropertiesFrom(projectDir); return project; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java index 8108bc329c..af744b2d81 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -85,18 +85,18 @@ abstract class AbstractBootArchiveIntegrationTests { @TestTemplate void basicBuild() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void reproducibleArchive() throws IOException, InterruptedException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); File jar = new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0]; String firstHash = FileUtils.sha1Hash(jar); Thread.sleep(1500); assertThat(this.gradleBuild.build("clean", this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); String secondHash = FileUtils.sha1Hash(jar); assertThat(firstHash).isEqualTo(secondHash); } @@ -104,67 +104,81 @@ abstract class AbstractBootArchiveIntegrationTests { @TestTemplate void upToDateWhenBuiltTwice() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void upToDateWhenBuiltTwiceWithLaunchScriptIncluded() { - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.build("-PincludeLaunchScript=true", this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void notUpToDateWhenLaunchScriptWasNotIncludedAndThenIsIncluded() { - assertThat(this.gradleBuild.scriptProperty("launchScript", "").build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void notUpToDateWhenLaunchScriptWasIncludedAndThenIsNotIncluded() { - assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("launchScript", "").build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "launchScript()") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScript", "") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void notUpToDateWhenLaunchScriptPropertyChanges() { - assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "alpha").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "bravo").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "alpha") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("launchScriptProperty", "bravo") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void applicationPluginMainClassNameIsUsed() throws IOException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.CustomMain"); + .isEqualTo("com.example.CustomMain"); } } @TestTemplate void springBootExtensionMainClassNameIsUsed() throws IOException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.CustomMain"); + .isEqualTo("com.example.CustomMain"); } } @TestTemplate void duplicatesAreHandledGracefully() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate @@ -173,13 +187,17 @@ abstract class AbstractBootArchiveIntegrationTests { srcMainResources.mkdirs(); new File(srcMainResources, "resource").createNewFile(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream libEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.libPath)); + Stream libEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.libPath)); assertThat(libEntryNames).containsExactly(this.libPath + "commons-io-2.6.jar"); - Stream classesEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.classesPath)); + Stream classesEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.classesPath)); assertThat(classesEntryNames).containsExactly(this.classesPath + "resource"); } } @@ -187,10 +205,12 @@ abstract class AbstractBootArchiveIntegrationTests { @TestTemplate void developmentOnlyDependenciesCanBeIncludedInTheArchive() throws IOException { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream libEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.libPath)); + Stream libEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.libPath)); assertThat(libEntryNames).containsExactly(this.libPath + "commons-io-2.6.jar", this.libPath + "commons-lang3-3.9.jar"); } @@ -202,10 +222,12 @@ abstract class AbstractBootArchiveIntegrationTests { createDependenciesStarterJar(new File(flatDirRepository, "starter.jar")); createStandardJar(new File(flatDirRepository, "standard.jar")); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream libEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.libPath)); + Stream libEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.libPath)); assertThat(libEntryNames).containsExactly(this.libPath + "standard.jar"); } } @@ -214,44 +236,56 @@ abstract class AbstractBootArchiveIntegrationTests { void startClassIsSetByResolvingTheMainClass() throws IOException { copyMainClassApplication(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { Attributes mainAttributes = jarFile.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Start-Class")) - .isEqualTo("com.example." + this.taskName.toLowerCase(Locale.ENGLISH) + ".main.CustomMainClass"); + .isEqualTo("com.example." + this.taskName.toLowerCase(Locale.ENGLISH) + ".main.CustomMainClass"); } assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.UP_TO_DATE); + .isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void upToDateWhenBuiltWithDefaultLayeredAndThenWithExplicitLayered() { - assertThat(this.gradleBuild.scriptProperty("layered", "").build("" + this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("layered", "layered {}").build("" + this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(this.gradleBuild.scriptProperty("layered", "") + .build("" + this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layered", "layered {}") + .build("" + this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); } @TestTemplate void notUpToDateWhenBuiltWithoutLayersAndThenWithLayers() { - assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = false").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = true").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = false") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerEnablement", "enabled = true") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void notUpToDateWhenBuiltWithLayerToolsAndThenWithoutLayerTools() { - assertThat(this.gradleBuild.scriptProperty("layerTools", "").build(this.taskName).task(":" + this.taskName) - .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(this.gradleBuild.scriptProperty("layerTools", "includeLayerTools = false").build(this.taskName) - .task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerTools", "") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(this.gradleBuild.scriptProperty("layerTools", "includeLayerTools = false") + .build(this.taskName) + .task(":" + this.taskName) + .getOutcome()).isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate void layersWithCustomSourceSet() { assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate @@ -259,7 +293,7 @@ abstract class AbstractBootArchiveIntegrationTests { writeMainClass(); writeResource(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Map> indexedLayers; String layerToolsJar = this.libPath + JarModeLibrary.LAYER_TOOLS.getName(); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { @@ -293,7 +327,7 @@ abstract class AbstractBootArchiveIntegrationTests { assertThat(indexedLayers.get("spring-boot-loader")).containsExactly("org/"); assertThat(indexedLayers.get("snapshot-dependencies")).containsExactlyElementsOf(expectedSnapshotDependencies); assertThat(indexedLayers.get("application")) - .containsExactly(getExpectedApplicationLayerContents(this.classesPath)); + .containsExactly(getExpectedApplicationLayerContents(this.classesPath)); BuildResult listLayers = this.gradleBuild.build("listLayers"); assertThat(listLayers.task(":listLayers").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); String listLayersOutput = listLayers.getOutput(); @@ -311,7 +345,7 @@ abstract class AbstractBootArchiveIntegrationTests { writeMainClass(); writeResource(); assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); Map> indexedLayers; String layerToolsJar = this.libPath + JarModeLibrary.LAYER_TOOLS.getName(); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { @@ -341,8 +375,8 @@ abstract class AbstractBootArchiveIntegrationTests { assertThat(indexedLayers.get("spring-boot-loader")).containsExactly("org/"); assertThat(indexedLayers.get("snapshot-dependencies")).containsExactlyElementsOf(expectedSnapshotDependencies); assertThat(indexedLayers.get("application")) - .containsExactly(getExpectedApplicationLayerContents(this.classesPath, this.libPath + "alpha-1.2.3.jar", - this.libPath + "bravo-1.2.3.jar", this.libPath + "charlie-1.2.3.jar")); + .containsExactly(getExpectedApplicationLayerContents(this.classesPath, this.libPath + "alpha-1.2.3.jar", + this.libPath + "bravo-1.2.3.jar", this.libPath + "charlie-1.2.3.jar")); BuildResult listLayers = this.gradleBuild.build("listLayers"); assertThat(listLayers.task(":listLayers").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); String listLayersOutput = listLayers.getOutput(); @@ -435,7 +469,7 @@ abstract class AbstractBootArchiveIntegrationTests { expectedSnapshotDependencies.add(this.libPath + "library-1.0-SNAPSHOT.jar"); (layerToolsJar.contains("SNAPSHOT") ? expectedSnapshotDependencies : expectedDependencies).add(layerToolsJar); assertThat(indexedLayers.get("subproject-dependencies")) - .containsExactlyElementsOf(expectedSubprojectDependencies); + .containsExactlyElementsOf(expectedSubprojectDependencies); assertThat(indexedLayers.get("dependencies")).containsExactlyElementsOf(expectedDependencies); assertThat(indexedLayers.get("commons-dependencies")).containsExactly(this.libPath + "commons-lang3-3.9.jar"); assertThat(indexedLayers.get("snapshot-dependencies")).containsExactlyElementsOf(expectedSnapshotDependencies); @@ -471,8 +505,10 @@ abstract class AbstractBootArchiveIntegrationTests { BuildResult build = this.gradleBuild.build(this.taskName); assertThat(build.task(":" + this.taskName).getOutcome()).isEqualTo(TaskOutcome.SUCCESS); try (JarFile jarFile = new JarFile(new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0])) { - Stream classesEntryNames = jarFile.stream().filter((entry) -> !entry.isDirectory()) - .map(JarEntry::getName).filter((name) -> name.startsWith(this.classesPath)); + Stream classesEntryNames = jarFile.stream() + .filter((entry) -> !entry.isDirectory()) + .map(JarEntry::getName) + .filter((name) -> name.startsWith(this.classesPath)); assertThat(classesEntryNames).containsExactly(this.classesPath + "example/Main.class", this.classesPath + "example/Secondary.class"); } @@ -551,8 +587,9 @@ abstract class AbstractBootArchiveIntegrationTests { private void writeResource() { try { - Path path = this.gradleBuild.getProjectDir().toPath() - .resolve(Paths.get("src", "main", "resources", "static", "file.txt")); + Path path = this.gradleBuild.getProjectDir() + .toPath() + .resolve(Paths.get("src", "main", "resources", "static", "file.txt")); Files.createDirectories(path.getParent()); Files.createFile(path); } @@ -587,8 +624,11 @@ abstract class AbstractBootArchiveIntegrationTests { assertThat(layer).isDirectory(); List files; try (Stream pathStream = Files.walk(layer.toPath())) { - files = pathStream.filter((path) -> path.toFile().isFile()).map(layer.toPath()::relativize) - .map(Path::toString).map(StringUtils::cleanPath).toList(); + files = pathStream.filter((path) -> path.toFile().isFile()) + .map(layer.toPath()::relativize) + .map(Path::toString) + .map(StringUtils::cleanPath) + .toList(); } extractedLayers.put(layerName, files); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java index b359c590df..d9a21ee3d5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java @@ -129,11 +129,11 @@ abstract class AbstractBootArchiveTests { assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass); assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main"); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes")) - .isEqualTo(this.classesPath); + .isEqualTo(this.classesPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Version")).isNotNull(); assertThat(jarFile.getManifest().getMainAttributes().getValue("Implementation-Title")) - .isEqualTo(this.project.getName()); + .isEqualTo(this.project.getName()); assertThat(jarFile.getManifest().getMainAttributes().getValue("Implementation-Version")).isNull(); } } @@ -145,7 +145,7 @@ abstract class AbstractBootArchiveTests { executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Implementation-Title")) - .isEqualTo("Customized"); + .isEqualTo("Customized"); } } @@ -167,7 +167,7 @@ abstract class AbstractBootArchiveTests { executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Implementation-Version")) - .isEqualTo("Customized"); + .isEqualTo("Customized"); } } @@ -177,10 +177,12 @@ abstract class AbstractBootArchiveTests { this.task.classpath(jarFile("one.jar"), jarFile("two.jar")); executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { - assertThat(jarFile.getEntry(this.libPath + "one.jar")).isNotNull().extracting(ZipEntry::getMethod) - .isEqualTo(ZipEntry.STORED); - assertThat(jarFile.getEntry(this.libPath + "two.jar")).isNotNull().extracting(ZipEntry::getMethod) - .isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry(this.libPath + "one.jar")).isNotNull() + .extracting(ZipEntry::getMethod) + .isEqualTo(ZipEntry.STORED); + assertThat(jarFile.getEntry(this.libPath + "two.jar")).isNotNull() + .extracting(ZipEntry::getMethod) + .isEqualTo(ZipEntry.STORED); } } @@ -314,7 +316,7 @@ abstract class AbstractBootArchiveTests { properties.put("initInfoDescription", this.project.getDescription()); File archiveFile = this.task.getArchiveFile().get().getAsFile(); assertThat(Files.readAllBytes(archiveFile.toPath())) - .startsWith(new DefaultLaunchScript(null, properties).toByteArray()); + .startsWith(new DefaultLaunchScript(null, properties).toByteArray()); try (ZipFile zipFile = new ZipFile(archiveFile)) { assertThat(zipFile.getEntries().hasMoreElements()).isTrue(); } @@ -362,7 +364,7 @@ abstract class AbstractBootArchiveTests { assertThat(this.task.getArchiveFile().get().getAsFile()).exists(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")) - .isEqualTo("com.example.CustomLauncher"); + .isEqualTo("com.example.CustomLauncher"); assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")).isEqualTo("com.example.Main"); assertThat(jarFile.getEntry("org/springframework/boot/loader/LaunchedURLClassLoader.class")).isNull(); } @@ -377,7 +379,7 @@ abstract class AbstractBootArchiveTests { try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Main-Class")).isEqualTo(this.launcherClass); assertThat(jarFile.getManifest().getMainAttributes().getValue("Start-Class")) - .isEqualTo("com.example.CustomMain"); + .isEqualTo("com.example.CustomMain"); } } @@ -399,7 +401,7 @@ abstract class AbstractBootArchiveTests { @Test void constantTimestampMatchesGradleInternalTimestamp() { assertThat(BootZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES) - .isEqualTo(ZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES); + .isEqualTo(ZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES); } @Test @@ -477,10 +479,10 @@ abstract class AbstractBootArchiveTests { executeTask(); try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes")) - .isEqualTo(this.classesPath); + .isEqualTo(this.classesPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Layers-Index")) - .isEqualTo(this.indexPath + "layers.idx"); + .isEqualTo(this.indexPath + "layers.idx"); assertThat(getEntryNames(jarFile)).contains(this.libPath + JarModeLibrary.LAYER_TOOLS.getName()); } } @@ -496,10 +498,10 @@ abstract class AbstractBootArchiveTests { void whenJarIsLayeredThenManifestContainsEntryForLayersIndexInPlaceOfClassesAndLib() throws IOException { try (JarFile jarFile = new JarFile(createLayeredJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classes")) - .isEqualTo(this.classesPath); + .isEqualTo(this.classesPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Lib")).isEqualTo(this.libPath); assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Layers-Index")) - .isEqualTo(this.indexPath + "layers.idx"); + .isEqualTo(this.indexPath + "layers.idx"); } } @@ -557,7 +559,7 @@ abstract class AbstractBootArchiveTests { dependencies.intoLayer("my-deps"); }); layered.getLayerOrder() - .set(List.of("my-deps", "my-internal-deps", "my-snapshot-deps", "resources", "application")); + .set(List.of("my-deps", "my-internal-deps", "my-snapshot-deps", "resources", "application")); }); try (JarFile jarFile = new JarFile(jar)) { List entryNames = getEntryNames(jar); @@ -607,7 +609,7 @@ abstract class AbstractBootArchiveTests { List entryNames = getEntryNames( createLayeredJar((configuration) -> configuration.getIncludeLayerTools().set(false))); assertThat(entryNames) - .doesNotContain(this.indexPath + "layers/dependencies/lib/spring-boot-jarmode-layertools.jar"); + .doesNotContain(this.indexPath + "layers/dependencies/lib/spring-boot-jarmode-layertools.jar"); } protected File jarFile(String name) throws IOException { @@ -718,11 +720,11 @@ abstract class AbstractBootArchiveTests { Set artifacts = new LinkedHashSet<>(); artifacts.add(mockLibraryArtifact("first-library.jar", "com.example", "first-library", "1.0.0")); artifacts.add(mockLibraryArtifact("second-library.jar", "com.example", "second-library", "1.0.0")); - artifacts.add( - mockLibraryArtifact("third-library-SNAPSHOT.jar", "com.example", "third-library", "1.0.0.SNAPSHOT")); + artifacts + .add(mockLibraryArtifact("third-library-SNAPSHOT.jar", "com.example", "third-library", "1.0.0.SNAPSHOT")); artifacts.add(mockLibraryArtifact("fourth-library.jar", "com.example", "fourth-library", "1.0.0")); artifacts - .add(mockProjectArtifact("first-project-library.jar", "com.example", "first-project-library", "1.0.0")); + .add(mockProjectArtifact("first-project-library.jar", "com.example", "first-project-library", "1.0.0")); artifacts.add(mockProjectArtifact("second-project-library-SNAPSHOT.jar", "com.example", "second-project-library", "1.0.0.SNAPSHOT")); ResolvedConfiguration resolvedConfiguration = mock(ResolvedConfiguration.class); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java index 4d691b7444..91ebfc4062 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -90,7 +90,7 @@ class BootBuildImageIntegrationTests { assertThat(result.getOutput()).contains("---> Test Info buildpack done"); File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs"); assertThat(buildLibs.listFiles()) - .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); + .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); removeImages(projectName); } @@ -106,7 +106,7 @@ class BootBuildImageIntegrationTests { assertThat(result.getOutput()).contains("---> Test Info buildpack done"); File buildLibs = new File(this.gradleBuild.getProjectDir(), "build/libs"); assertThat(buildLibs.listFiles()) - .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); + .containsExactly(new File(buildLibs, this.gradleBuild.getProjectDir().getName() + ".war")); removeImages(projectName); } @@ -172,7 +172,7 @@ class BootBuildImageIntegrationTests { assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()).contains("docker.io/library/" + projectName); assertThat(result.getOutput()).contains("---> Test Info buildpack building") - .contains("---> Test Info buildpack done"); + .contains("---> Test Info buildpack done"); removeImages(projectName); } @@ -214,7 +214,7 @@ class BootBuildImageIntegrationTests { assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()).contains("docker.io/library/" + projectName); assertThat(result.getOutput()).contains("---> Test Info buildpack building") - .contains("---> Test Info buildpack done"); + .contains("---> Test Info buildpack done"); removeImages(projectName); } @@ -307,7 +307,7 @@ class BootBuildImageIntegrationTests { BuildResult result = this.gradleBuild.buildAndFail("bootBuildImage", "--imageName=example/Invalid-Image-Name"); assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.FAILED); assertThat(result.getOutput()).containsPattern("Unable to parse image reference") - .containsPattern("example/Invalid-Image-Name"); + .containsPattern("example/Invalid-Image-Name"); } @TestTemplate @@ -326,7 +326,7 @@ class BootBuildImageIntegrationTests { BuildResult result = this.gradleBuild.buildAndFail("bootBuildImage"); assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.FAILED); assertThat(result.getOutput()).containsPattern("Unable to parse image reference") - .containsPattern("example/Invalid-Tag-Name"); + .containsPattern("example/Invalid-Tag-Name"); } @TestTemplate @@ -362,17 +362,18 @@ class BootBuildImageIntegrationTests { private void writeLongNameResource() throws IOException { StringBuilder name = new StringBuilder(); new Random().ints('a', 'z' + 1).limit(128).forEach((i) -> name.append((char) i)); - Path path = this.gradleBuild.getProjectDir().toPath() - .resolve(Paths.get("src", "main", "resources", name.toString())); + Path path = this.gradleBuild.getProjectDir() + .toPath() + .resolve(Paths.get("src", "main", "resources", name.toString())); Files.createDirectories(path.getParent()); Files.createFile(path); } private void writeBuildpackContent() throws IOException { FileAttribute> dirAttribute = PosixFilePermissions - .asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x")); + .asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x")); FileAttribute> execFileAttribute = PosixFilePermissions - .asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")); + .asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")); File buildpackDir = new File(this.gradleBuild.getProjectDir(), "buildpack/hello-world"); Files.createDirectories(buildpackDir.toPath(), dirAttribute); File binDir = new File(buildpackDir, "bin"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java index c37e9b00ca..f3d4c221a2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class BootBuildImageRegistryIntegrationTests { @Container static final RegistryContainer registry = new RegistryContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(3)); + .withStartupTimeout(Duration.ofMinutes(3)); String registryAddress; @@ -72,9 +72,10 @@ class BootBuildImageRegistryIntegrationTests { String imageName = this.registryAddress + "/" + repoName; BuildResult result = this.gradleBuild.build("bootBuildImage", "--imageName=" + imageName); assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).contains("Building image").contains("Successfully built image") - .contains("Pushing image '" + imageName + ":latest" + "'") - .contains("Pushed image '" + imageName + ":latest" + "'"); + assertThat(result.getOutput()).contains("Building image") + .contains("Successfully built image") + .contains("Pushing image '" + imageName + ":latest" + "'") + .contains("Pushed image '" + imageName + ":latest" + "'"); ImageReference imageReference = ImageReference.of(imageName); Image pulledImage = new DockerApi().image().pull(imageReference, UpdateListener.none()); assertThat(pulledImage).isNotNull(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java index 6b5aeaf61e..fdb69d2a53 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageTests.java @@ -103,8 +103,9 @@ class BootBuildImageTests { void whenIndividualEntriesAreAddedToTheEnvironmentThenTheyAreIncludedInTheRequest() { this.buildImage.getEnvironment().put("ALPHA", "a"); this.buildImage.getEnvironment().put("BRAVO", "b"); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -113,8 +114,9 @@ class BootBuildImageTests { environment.put("ALPHA", "a"); environment.put("BRAVO", "b"); this.buildImage.getEnvironment().putAll(environment); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -123,8 +125,9 @@ class BootBuildImageTests { environment.put("ALPHA", "a"); environment.put("BRAVO", "b"); this.buildImage.getEnvironment().set(environment); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -134,8 +137,9 @@ class BootBuildImageTests { environment.put("BRAVO", "b"); this.buildImage.getEnvironment().put("C", "Charlie"); this.buildImage.getEnvironment().set(environment); - assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b") - .hasSize(2); + assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a") + .containsEntry("BRAVO", "b") + .hasSize(2); } @Test @@ -206,23 +210,23 @@ class BootBuildImageTests { @Test void whenBuildpacksAreConfiguredThenRequestHasBuildpacks() { this.buildImage.getBuildpacks().set(Arrays.asList("example/buildpack1", "example/buildpack2")); - assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly( - BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); + assertThat(this.buildImage.createRequest().getBuildpacks()) + .containsExactly(BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); } @Test void whenEntriesAreAddedToBuildpacksThenRequestHasBuildpacks() { this.buildImage.getBuildpacks().addAll(Arrays.asList("example/buildpack1", "example/buildpack2")); - assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly( - BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); + assertThat(this.buildImage.createRequest().getBuildpacks()) + .containsExactly(BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); } @Test void whenIndividualEntriesAreAddedToBuildpacksThenRequestHasBuildpacks() { this.buildImage.getBuildpacks().add("example/buildpack1"); this.buildImage.getBuildpacks().add("example/buildpack2"); - assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly( - BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); + assertThat(this.buildImage.createRequest().getBuildpacks()) + .containsExactly(BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2")); } @Test @@ -234,15 +238,15 @@ class BootBuildImageTests { void whenBindingsAreConfiguredThenRequestHasBindings() { this.buildImage.getBindings().set(Arrays.asList("host-src:container-dest:ro", "volume-name:container-dest:rw")); assertThat(this.buildImage.createRequest().getBindings()) - .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); + .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); } @Test void whenEntriesAreAddedToBindingsThenRequestHasBindings() { this.buildImage.getBindings() - .addAll(Arrays.asList("host-src:container-dest:ro", "volume-name:container-dest:rw")); + .addAll(Arrays.asList("host-src:container-dest:ro", "volume-name:container-dest:rw")); assertThat(this.buildImage.createRequest().getBindings()) - .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); + .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); } @Test @@ -250,7 +254,7 @@ class BootBuildImageTests { this.buildImage.getBindings().add("host-src:container-dest:ro"); this.buildImage.getBindings().add("volume-name:container-dest:rw"); assertThat(this.buildImage.createRequest().getBindings()) - .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); + .containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw")); } @Test @@ -267,15 +271,15 @@ class BootBuildImageTests { @Test void whenTagsAreConfiguredThenRequestHasTags() { this.buildImage.getTags() - .set(Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); + .set(Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); assertThat(this.buildImage.createRequest().getTags()).containsExactly(ImageReference.of("my-app:latest"), ImageReference.of("example.com/my-app:0.0.1-SNAPSHOT"), ImageReference.of("example.com/my-app:latest")); } @Test void whenEntriesAreAddedToTagsThenRequestHasTags() { - this.buildImage.getTags().addAll( - Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); + this.buildImage.getTags() + .addAll(Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest")); assertThat(this.buildImage.createRequest().getTags()).containsExactly(ImageReference.of("my-app:latest"), ImageReference.of("example.com/my-app:0.0.1-SNAPSHOT"), ImageReference.of("example.com/my-app:latest")); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java index 3400dd974c..3657a86ad8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class BootJarIntegrationTests extends AbstractBootArchiveIntegrationTests { void whenAResolvableCopyOfAnUnresolvableConfigurationIsResolvedThenResolutionSucceeds() { BuildResult build = this.gradleBuild.build("resolveResolvableCopyOfUnresolvableConfiguration"); assertThat(build.task(":resolveResolvableCopyOfUnresolvableConfiguration").getOutcome()) - .isEqualTo(TaskOutcome.SUCCESS); + .isEqualTo(TaskOutcome.SUCCESS); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java index b205b69597..38d5f09781 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootJarTests.java @@ -99,7 +99,7 @@ class BootJarTests extends AbstractBootArchiveTests { void classpathIndexPointsToBootInfLibs() throws IOException { try (JarFile jarFile = new JarFile(createPopulatedJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classpath-Index")) - .isEqualTo("BOOT-INF/classpath.idx"); + .isEqualTo("BOOT-INF/classpath.idx"); assertThat(entryLines(jarFile, "BOOT-INF/classpath.idx")).containsExactly( "- \"BOOT-INF/lib/first-library.jar\"", "- \"BOOT-INF/lib/second-library.jar\"", "- \"BOOT-INF/lib/third-library-SNAPSHOT.jar\"", "- \"BOOT-INF/lib/fourth-library.jar\"", @@ -208,7 +208,7 @@ class BootJarTests extends AbstractBootArchiveTests { void javaVersionIsWrittenToManifest() throws IOException { try (JarFile jarFile = new JarFile(createPopulatedJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Build-Jdk-Spec")) - .isEqualTo(JavaVersion.VERSION_17.getMajorVersion()); + .isEqualTo(JavaVersion.VERSION_17.getMajorVersion()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java index 8d1500460c..e2c280b242 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/BootWarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -117,7 +117,7 @@ class BootWarTests extends AbstractBootArchiveTests { getTask().providedClasspath(jarFile("provided-library.jar")); executeTask(); assertThat(getEntryNames(getTask().getArchiveFile().get().getAsFile())) - .containsSubsequence("WEB-INF/lib/library.jar", "WEB-INF/lib-provided/provided-library.jar"); + .containsSubsequence("WEB-INF/lib/library.jar", "WEB-INF/lib-provided/provided-library.jar"); } @Test @@ -135,7 +135,7 @@ class BootWarTests extends AbstractBootArchiveTests { void classpathIndexPointsToWebInfLibs() throws IOException { try (JarFile jarFile = new JarFile(createPopulatedJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Spring-Boot-Classpath-Index")) - .isEqualTo("WEB-INF/classpath.idx"); + .isEqualTo("WEB-INF/classpath.idx"); assertThat(entryLines(jarFile, "WEB-INF/classpath.idx")).containsExactly( "- \"WEB-INF/lib/first-library.jar\"", "- \"WEB-INF/lib/second-library.jar\"", "- \"WEB-INF/lib/third-library-SNAPSHOT.jar\"", "- \"WEB-INF/lib/fourth-library.jar\"", @@ -148,7 +148,7 @@ class BootWarTests extends AbstractBootArchiveTests { void javaVersionIsWrittenToManifest() throws IOException { try (JarFile jarFile = new JarFile(createPopulatedJar())) { assertThat(jarFile.getManifest().getMainAttributes().getValue("Build-Jdk-Spec")) - .isEqualTo(JavaVersion.VERSION_17.getMajorVersion()); + .isEqualTo(JavaVersion.VERSION_17.getMajorVersion()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java index eef5747894..7cce2758b0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/DockerSpecTests.java @@ -43,8 +43,11 @@ class DockerSpecTests { @BeforeEach void prepareDockerSpec(@TempDir File temp) { - this.dockerSpec = GradleProjectBuilder.builder().withProjectDir(temp).build().getObjects() - .newInstance(DockerSpec.class); + this.dockerSpec = GradleProjectBuilder.builder() + .withProjectDir(temp) + .build() + .getObjects() + .newInstance(DockerSpec.class); } @Test @@ -53,8 +56,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.getHost()).isNull(); assertThat(dockerConfiguration.getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -70,8 +75,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isFalse(); assertThat(this.dockerSpec.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -85,8 +92,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isFalse(); assertThat(this.dockerSpec.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -101,8 +110,10 @@ class DockerSpecTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isTrue(); assertThat(this.dockerSpec.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -121,13 +132,15 @@ class DockerSpecTests { }); DockerConfiguration dockerConfiguration = this.dockerSpec.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user1\"").contains("\"password\" : \"secret1\"") - .contains("\"email\" : \"docker1@example.com\"") - .contains("\"serveraddress\" : \"https://docker1.example.com\""); + .contains("\"username\" : \"user1\"") + .contains("\"password\" : \"secret1\"") + .contains("\"email\" : \"docker1@example.com\"") + .contains("\"serveraddress\" : \"https://docker1.example.com\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user2\"").contains("\"password\" : \"secret2\"") - .contains("\"email\" : \"docker2@example.com\"") - .contains("\"serveraddress\" : \"https://docker2.example.com\""); + .contains("\"username\" : \"user2\"") + .contains("\"password\" : \"secret2\"") + .contains("\"email\" : \"docker2@example.com\"") + .contains("\"serveraddress\" : \"https://docker2.example.com\""); assertThat(this.dockerSpec.asDockerConfiguration().getHost()).isNull(); } @@ -139,7 +152,7 @@ class DockerSpecTests { registry.getEmail().set("docker1@example.com"); }); assertThatExceptionOfType(GradleException.class).isThrownBy(this.dockerSpec::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } @Test @@ -150,7 +163,7 @@ class DockerSpecTests { registry.getEmail().set("docker2@example.com"); }); assertThatExceptionOfType(GradleException.class).isThrownBy(this.dockerSpec::asDockerConfiguration) - .withMessageContaining("Invalid Docker publish registry configuration"); + .withMessageContaining("Invalid Docker publish registry configuration"); } @Test @@ -159,9 +172,9 @@ class DockerSpecTests { this.dockerSpec.publishRegistry((registry) -> registry.getToken().set("token2")); DockerConfiguration dockerConfiguration = this.dockerSpec.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token1\""); + .contains("\"identitytoken\" : \"token1\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token2\""); + .contains("\"identitytoken\" : \"token2\""); } @Test @@ -172,7 +185,7 @@ class DockerSpecTests { registry.getToken().set("token"); }); assertThatExceptionOfType(GradleException.class).isThrownBy(this.dockerSpec::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } String decoded(String value) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java index f39eafce40..8d03af72af 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/MavenPublishingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,10 @@ class MavenPublishingIntegrationTests { assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("jar")).isFile(); assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") - .artifactId(this.gradleBuild.getProjectDir().getName()).version("1.0").noPackaging().noDependencies()); + .artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0") + .noPackaging() + .noDependencies()); } @TestTemplate @@ -52,9 +55,11 @@ class MavenPublishingIntegrationTests { BuildResult result = this.gradleBuild.build("publish"); assertThat(result.task(":publish").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(artifactWithSuffix("war")).isFile(); - assertThat(artifactWithSuffix("pom")) - .is(pomWith().groupId("com.example").artifactId(this.gradleBuild.getProjectDir().getName()) - .version("1.0").packaging("war").noDependencies()); + assertThat(artifactWithSuffix("pom")).is(pomWith().groupId("com.example") + .artifactId(this.gradleBuild.getProjectDir().getName()) + .version("1.0") + .packaging("war") + .noDependencies()); } private File artifactWithSuffix(String suffix) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java index 05e78bbd44..a5f6c5c347 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/run/BootRunIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,7 @@ class BootRunIntegrationTests { BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(result.getOutput()) - .contains("Main class name = com.example.bootrun.classpath.BootRunClasspathApplication"); + .contains("Main class name = com.example.bootrun.classpath.BootRunClasspathApplication"); } @TestTemplate @@ -111,8 +111,9 @@ class BootRunIntegrationTests { copyJvmArgsApplication(); BuildResult result = this.gradleBuild.build("bootRun"); assertThat(result.task(":bootRun").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); - assertThat(result.getOutput()).contains("-Dcom.bar=baz").contains("-Dcom.foo=bar") - .contains("-XX:TieredStopAtLevel=1"); + assertThat(result.getOutput()).contains("-Dcom.bar=baz") + .contains("-Dcom.foo=bar") + .contains("-XX:TieredStopAtLevel=1"); } @TestTemplate diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java index b1fa01c228..f6c1a35d66 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-test-support/src/main/java/org/springframework/boot/testsupport/gradle/testkit/GradleBuild.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -224,8 +224,9 @@ public class GradleBuild { if (repository.exists()) { FileSystemUtils.copyRecursively(repository, new File(this.projectDir, "repository")); } - GradleRunner gradleRunner = GradleRunner.create().withProjectDir(this.projectDir) - .withPluginClasspath(pluginClasspath()); + GradleRunner gradleRunner = GradleRunner.create() + .withProjectDir(this.projectDir) + .withPluginClasspath(pluginClasspath()); if (this.dsl != Dsl.KOTLIN && !this.configurationCache) { // see https://github.com/gradle/gradle/issues/6862 gradleRunner.withDebug(true); @@ -301,14 +302,17 @@ public class GradleBuild { private String getProperty(File propertiesFile, String key) { try { - assertThat(propertiesFile).withFailMessage("Expecting properties file to exist at path '%s'", - propertiesFile.getCanonicalFile()).exists(); + assertThat(propertiesFile) + .withFailMessage("Expecting properties file to exist at path '%s'", propertiesFile.getCanonicalFile()) + .exists(); Properties properties = new Properties(); try (FileInputStream input = new FileInputStream(propertiesFile)) { properties.load(input); String value = properties.getProperty(key); - assertThat(value).withFailMessage("Expecting properties file '%s' to contain the key '%s'", - propertiesFile.getCanonicalFile(), key).isNotEmpty(); + assertThat(value) + .withFailMessage("Expecting properties file '%s' to contain the key '%s'", + propertiesFile.getCanonicalFile(), key) + .isNotEmpty(); return value; } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java index 2ef17ba199..c9f661facb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/ExtractCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -99,7 +99,7 @@ class ExtractCommand extends Command { } try { Files.getFileAttributeView(file.toPath(), BasicFileAttributeView.class) - .setTimes(entry.getLastModifiedTime(), entry.getLastAccessTime(), entry.getCreationTime()); + .setTimes(entry.getLastModifiedTime(), entry.getLastAccessTime(), entry.getCreationTime()); } catch (IOException ex) { // File system does not support setting time attributes. Continue. diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java index 61826969c1..33e2ae66e0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/IndexedLayers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,10 @@ class IndexedLayers implements Layers { private final Map> layers = new LinkedHashMap<>(); IndexedLayers(String indexFile) { - String[] lines = Arrays.stream(indexFile.split("\n")).map((line) -> line.replace("\r", "")) - .filter(StringUtils::hasText).toArray(String[]::new); + String[] lines = Arrays.stream(indexFile.split("\n")) + .map((line) -> line.replace("\r", "")) + .filter(StringUtils::hasText) + .toArray(String[]::new); List contents = null; for (String line : lines) { if (line.startsWith("- ")) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java index 14fdf76c34..4293af4fa2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/CommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -83,14 +83,15 @@ class CommandTests { void runWithUnknownOptionThrowsException() { TestCommand command = new TestCommand("test", VERBOSE_FLAG, LOG_LEVEL_OPTION); assertThatExceptionOfType(UnknownOptionException.class).isThrownBy(() -> run(command, "--invalid")) - .withMessage("--invalid"); + .withMessage("--invalid"); } @Test void runWithOptionMissingRequiredValueThrowsException() { TestCommand command = new TestCommand("test", VERBOSE_FLAG, LOG_LEVEL_OPTION); assertThatExceptionOfType(MissingValueException.class) - .isThrownBy(() -> run(command, "--verbose", "--log-level")).withMessage("--log-level"); + .isThrownBy(() -> run(command, "--verbose", "--log-level")) + .withMessage("--log-level"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java index fc8e320f1c..44c6c5b0a0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class ContextTests { @Test void createWhenSourceIsNullThrowsException() { assertThatIllegalStateException().isThrownBy(() -> new Context(null, this.temp)) - .withMessage("Unable to find source archive"); + .withMessage("Unable to find source archive"); } @Test @@ -47,7 +47,7 @@ class ContextTests { File directory = new File(this.temp, "test"); directory.mkdir(); assertThatIllegalStateException().isThrownBy(() -> new Context(directory, this.temp)) - .withMessage("Unable to find source archive"); + .withMessage("Unable to find source archive"); } @Test @@ -55,7 +55,7 @@ class ContextTests { File zip = new File(this.temp, "test.zip"); Files.createFile(zip.toPath()); assertThatIllegalStateException().isThrownBy(() -> new Context(zip, this.temp)) - .withMessageContaining("test.zip must end with .jar or .war"); + .withMessageContaining("test.zip must end with .jar or .war"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java index 99b73ce541..7407d91109 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/ExtractCommandTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -103,16 +103,16 @@ class ExtractCommandTests { private void timeAttributes(File file) { try { BasicFileAttributes basicAttributes = Files - .getFileAttributeView(file.toPath(), BasicFileAttributeView.class, new LinkOption[0]) - .readAttributes(); + .getFileAttributeView(file.toPath(), BasicFileAttributeView.class, new LinkOption[0]) + .readAttributes(); assertThat(basicAttributes.lastModifiedTime().to(TimeUnit.SECONDS)) - .isEqualTo(LAST_MODIFIED_TIME.to(TimeUnit.SECONDS)); + .isEqualTo(LAST_MODIFIED_TIME.to(TimeUnit.SECONDS)); assertThat(basicAttributes.creationTime().to(TimeUnit.SECONDS)).satisfiesAnyOf( (creationTime) -> assertThat(creationTime).isEqualTo(CREATION_TIME.to(TimeUnit.SECONDS)), // On macOS (at least) the creation time is the last modified time (creationTime) -> assertThat(creationTime).isEqualTo(LAST_MODIFIED_TIME.to(TimeUnit.SECONDS))); assertThat(basicAttributes.lastAccessTime().to(TimeUnit.SECONDS)) - .isEqualTo(LAST_ACCESS_TIME.to(TimeUnit.SECONDS)); + .isEqualTo(LAST_ACCESS_TIME.to(TimeUnit.SECONDS)); } catch (IOException ex) { throw new RuntimeException(ex); @@ -151,8 +151,8 @@ class ExtractCommandTests { given(this.context.getArchiveFile()).willReturn(file); given(this.context.getWorkingDir()).willReturn(this.extract); assertThatIllegalStateException() - .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) - .withMessageContaining("not compatible with layertools"); + .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) + .withMessageContaining("not compatible with layertools"); } @Test @@ -168,8 +168,8 @@ class ExtractCommandTests { }); given(this.context.getArchiveFile()).willReturn(this.jarFile); assertThatIllegalStateException() - .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) - .withMessageContaining("Entry 'e/../../e.jar' would be written"); + .isThrownBy(() -> this.command.run(Collections.emptyMap(), Collections.emptyList())) + .withMessageContaining("Entry 'e/../../e.jar' would be written"); } private File createJarFile(String name) throws Exception { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java index 2074dbe605..9b34b4cd30 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/test/java/org/springframework/boot/jarmode/layertools/IndexedLayersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,13 +47,13 @@ class IndexedLayersTests { @Test void createWhenIndexFileIsEmptyThrowsException() { assertThatIllegalStateException().isThrownBy(() -> new IndexedLayers(" \n ")) - .withMessage("Empty layer index file loaded"); + .withMessage("Empty layer index file loaded"); } @Test void createWhenIndexFileIsMalformedThrowsException() { assertThatIllegalStateException().isThrownBy(() -> new IndexedLayers("test")) - .withMessage("Layer index file is malformed"); + .withMessage("Layer index file is malformed"); } @Test @@ -73,7 +73,7 @@ class IndexedLayersTests { void getLayerWhenMatchesNameForMissingLayerThrowsException() throws Exception { IndexedLayers layers = new IndexedLayers(getIndex()); assertThatIllegalStateException().isThrownBy(() -> layers.getLayer(mockEntry("file.jar"))) - .withMessage("No layer defined in index for file " + "'file.jar'"); + .withMessage("No layer defined in index for file " + "'file.jar'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java index 61ec3eb5fc..815e0ee4a9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -229,7 +229,7 @@ public abstract class Packager { if (zipEntry != null) { try (InputStream inputStream = sourceJar.getInputStream(zipEntry)) { ReachabilityMetadataProperties properties = ReachabilityMetadataProperties - .fromInputStream(inputStream); + .fromInputStream(inputStream); if (properties.isOverridden()) { excludes.add(entry.getKey()); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java index af9eec3d98..3429e4af90 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java @@ -105,7 +105,7 @@ abstract class AbstractPackagerTests

{ execute(packager, NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -121,7 +121,7 @@ abstract class AbstractPackagerTests

{ execute(packager, NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -133,7 +133,7 @@ abstract class AbstractPackagerTests

{ execute(packager, NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -143,8 +143,8 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/D.class", ClassWithMainMethod.class); P packager = createPackager(); - assertThatIllegalStateException().isThrownBy(() -> execute(packager, NO_LIBRARIES)).withMessageContaining( - "Unable to find a single main class from the following candidates [a.b.C, a.b.D]"); + assertThatIllegalStateException().isThrownBy(() -> execute(packager, NO_LIBRARIES)) + .withMessageContaining("Unable to find a single main class from the following candidates [a.b.C, a.b.D]"); } @Test @@ -152,7 +152,7 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); P packager = createPackager(this.testJarFile.getFile()); assertThatIllegalStateException().isThrownBy(() -> execute(packager, NO_LIBRARIES)) - .withMessageContaining("Unable to find main class"); + .withMessageContaining("Unable to find main class"); } @Test @@ -182,7 +182,7 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); P packager = createPackager(); assertThatIllegalArgumentException().isThrownBy(() -> execute(packager, null)) - .withMessageContaining("Libraries must not be null"); + .withMessageContaining("Libraries must not be null"); } @Test @@ -235,7 +235,8 @@ abstract class AbstractPackagerTests

{ String index = getPackagedEntryContent("BOOT-INF/classpath.idx"); String[] libraries = index.split("\\r?\\n"); List expected = Stream.of(libJarFile1, libJarFile2, libJarFile3) - .map((jar) -> "- \"BOOT-INF/lib/" + jar.getName() + "\"").toList(); + .map((jar) -> "- \"BOOT-INF/lib/" + jar.getName() + "\"") + .toList(); assertThat(Arrays.asList(libraries)).containsExactlyElementsOf(expected); } @@ -266,7 +267,8 @@ abstract class AbstractPackagerTests

{ assertThat(hasPackagedEntry("BOOT-INF/classpath.idx")).isTrue(); String classpathIndex = getPackagedEntryContent("BOOT-INF/classpath.idx"); List expectedClasspathIndex = Stream.of(libJarFile1, libJarFile2, libJarFile3) - .map((file) -> "- \"BOOT-INF/lib/" + file.getName() + "\"").toList(); + .map((file) -> "- \"BOOT-INF/lib/" + file.getName() + "\"") + .toList(); assertThat(Arrays.asList(classpathIndex.split("\\n"))).containsExactlyElementsOf(expectedClasspathIndex); assertThat(hasPackagedEntry("BOOT-INF/layers.idx")).isTrue(); String layersIndex = getPackagedEntryContent("BOOT-INF/layers.idx"); @@ -284,7 +286,7 @@ abstract class AbstractPackagerTests

{ expectedLayers.add("- '0003':"); expectedLayers.add(" - 'BOOT-INF/lib/" + libJarFile3.getName() + "'"); assertThat(layersIndex.split("\\n")) - .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); + .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); } @Test @@ -297,7 +299,7 @@ abstract class AbstractPackagerTests

{ assertThat(hasPackagedEntry("BOOT-INF/classpath.idx")).isTrue(); String classpathIndex = getPackagedEntryContent("BOOT-INF/classpath.idx"); assertThat(Arrays.asList(classpathIndex.split("\\n"))) - .containsExactly("- \"BOOT-INF/lib/spring-boot-jarmode-layertools.jar\""); + .containsExactly("- \"BOOT-INF/lib/spring-boot-jarmode-layertools.jar\""); assertThat(hasPackagedEntry("BOOT-INF/layers.idx")).isTrue(); String layersIndex = getPackagedEntryContent("BOOT-INF/layers.idx"); List expectedLayers = new ArrayList<>(); @@ -306,7 +308,7 @@ abstract class AbstractPackagerTests

{ expectedLayers.add(" - 'META-INF/'"); expectedLayers.add(" - 'org/'"); assertThat(layersIndex.split("\\n")) - .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); + .containsExactly(expectedLayers.stream().map((s) -> s.replace('\'', '"')).toArray(String[]::new)); } @Test @@ -395,7 +397,7 @@ abstract class AbstractPackagerTests

{ this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); Packager packager = createPackager(); assertThatIllegalArgumentException().isThrownBy(() -> packager.setLayout(null)) - .withMessageContaining("Layout must not be null"); + .withMessageContaining("Layout must not be null"); } @Test @@ -649,7 +651,7 @@ abstract class AbstractPackagerTests

{ expected.add("\\Q" + libraryTwo.getName() + "\\E"); expected.add("^/META-INF/native-image/.*"); assertThat(getPackagedEntryContent("META-INF/native-image/argfile")) - .isEqualTo(expected.stream().collect(Collectors.joining("\n")) + "\n"); + .isEqualTo(expected.stream().collect(Collectors.joining("\n")) + "\n"); } private File createLibraryJar() throws IOException { @@ -675,8 +677,9 @@ abstract class AbstractPackagerTests

{ protected abstract void execute(P packager, Libraries libraries) throws IOException; protected Collection getPackagedEntryNames() throws IOException { - return getAllPackagedEntries().stream().map(ZipArchiveEntry::getName) - .collect(Collectors.toCollection(ArrayList::new)); + return getAllPackagedEntries().stream() + .map(ZipArchiveEntry::getName) + .collect(Collectors.toCollection(ArrayList::new)); } protected boolean hasPackagedLauncherClasses() throws IOException { @@ -689,8 +692,10 @@ abstract class AbstractPackagerTests

{ } protected ZipEntry getPackagedEntry(String name) throws IOException { - return getAllPackagedEntries().stream().filter((entry) -> name.equals(entry.getName())).findFirst() - .orElse(null); + return getAllPackagedEntries().stream() + .filter((entry) -> name.equals(entry.getName())) + .findFirst() + .orElse(null); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java index 6c381b298e..042a811eaf 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ImplicitLayerResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,26 +63,26 @@ class ImplicitLayerResolverTests { @Test void getLayerWhenLoaderClassReturnsLoaderLayer() { assertThat(this.layers.getLayer("org/springframework/boot/loader/Launcher.class")) - .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); + .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); assertThat(this.layers.getLayer("org/springframework/boot/loader/Utils.class")) - .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); + .isEqualTo(StandardLayers.SPRING_BOOT_LOADER); } @Test void getLayerWhenLibraryIsSnapshotReturnsSnapshotLayer() { assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0.BUILD-SNAPSHOT.jar"))) - .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); + .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0-SNAPSHOT.jar"))) - .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); + .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0.SNAPSHOT.jar"))) - .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); + .isEqualTo(StandardLayers.SNAPSHOT_DEPENDENCIES); } @Test void getLayerWhenLibraryIsNotSnapshotReturnsDependenciesLayer() { assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0.jar"))).isEqualTo(StandardLayers.DEPENDENCIES); assertThat(this.layers.getLayer(mockLibrary("spring-boot.2.0.0-classified.jar"))) - .isEqualTo(StandardLayers.DEPENDENCIES); + .isEqualTo(StandardLayers.DEPENDENCIES); } private Library mockLibrary(String name) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java index 74cc3afcfd..0328e2b9f1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayerTests.java @@ -42,7 +42,7 @@ class LayerTests { @Test void createWhenNameContainsBadCharsThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Layer("bad!name")) - .withMessage("Malformed layer name 'bad!name'"); + .withMessage("Malformed layer name 'bad!name'"); } @Test @@ -62,11 +62,11 @@ class LayerTests { @Test void createWhenUsingReservedNameThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Layer("ext")) - .withMessage("Layer name 'ext' is reserved"); + .withMessage("Layer name 'ext' is reserved"); assertThatIllegalArgumentException().isThrownBy(() -> new Layer("ExT")) - .withMessage("Layer name 'ExT' is reserved"); + .withMessage("Layer name 'ExT' is reserved"); assertThatIllegalArgumentException().isThrownBy(() -> new Layer("springbootloader")) - .withMessage("Layer name 'springbootloader' is reserved"); + .withMessage("Layer name 'springbootloader' is reserved"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java index 52ef2e6144..4a074f1c9d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ class LayoutsTests { @Test void unknownFile() { assertThatIllegalStateException().isThrownBy(() -> Layouts.forFile(new File("test.txt"))) - .withMessageContaining("Unable to deduce layout for 'test.txt'"); + .withMessageContaining("Unable to deduce layout for 'test.txt'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java index fe2214b246..3a273b8895 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java @@ -85,8 +85,8 @@ class MainClassFinderTests { this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); try (JarFile jarFile = this.testJarFile.getJarFile()) { assertThatIllegalStateException().isThrownBy(() -> MainClassFinder.findSingleMainClass(jarFile, "")) - .withMessageContaining( - "Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); + .withMessageContaining( + "Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); } } @@ -142,9 +142,8 @@ class MainClassFinderTests { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); assertThatIllegalStateException() - .isThrownBy(() -> MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource())) - .withMessageContaining( - "Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); + .isThrownBy(() -> MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource())) + .withMessageContaining("Unable to find a single main class from the following candidates [a.B, a.b.c.E]"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ReachabilityMetadataPropertiesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ReachabilityMetadataPropertiesTests.java index f7e4b16dba..8c6f6eb262 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ReachabilityMetadataPropertiesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/ReachabilityMetadataPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,16 +35,16 @@ class ReachabilityMetadataPropertiesTests { void shouldReadFromInputStream() throws IOException { String propertiesContent = "override=true\n"; ReachabilityMetadataProperties properties = ReachabilityMetadataProperties - .fromInputStream(new ByteArrayInputStream(propertiesContent.getBytes(StandardCharsets.UTF_8))); + .fromInputStream(new ByteArrayInputStream(propertiesContent.getBytes(StandardCharsets.UTF_8))); assertThat(properties.isOverridden()).isTrue(); } @Test void shouldFormatLocation() { String location = ReachabilityMetadataProperties - .getLocation(LibraryCoordinates.of("group-id", "artifact-id", "1.0.0")); + .getLocation(LibraryCoordinates.of("group-id", "artifact-id", "1.0.0")); assertThat(location) - .isEqualTo("META-INF/native-image/group-id/artifact-id/1.0.0/reachability-metadata.properties"); + .isEqualTo("META-INF/native-image/group-id/artifact-id/1.0.0/reachability-metadata.properties"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index a981d86a27..0912ffca20 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -79,7 +79,7 @@ class RepackagerTests extends AbstractPackagerTests { repackager.repackage(NO_LIBRARIES); Manifest actualManifest = getPackagedManifest(); assertThat(actualManifest.getMainAttributes().getValue("Main-Class")) - .isEqualTo("org.springframework.boot.loader.JarLauncher"); + .isEqualTo("org.springframework.boot.loader.JarLauncher"); assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C"); assertThat(hasPackagedLauncherClasses()).isTrue(); } @@ -121,7 +121,7 @@ class RepackagerTests extends AbstractPackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = createRepackager(this.testJarFile.getFile(), true); assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES)) - .withMessageContaining("Invalid destination"); + .withMessageContaining("Invalid destination"); } @Test @@ -129,7 +129,7 @@ class RepackagerTests extends AbstractPackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = createRepackager(this.testJarFile.getFile(), true); assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(this.tempDir, NO_LIBRARIES)) - .withMessageContaining("Invalid destination"); + .withMessageContaining("Invalid destination"); } @Test @@ -166,7 +166,7 @@ class RepackagerTests extends AbstractPackagerTests { } try { assertThat(Files.getPosixFilePermissions(this.destination.toPath())) - .contains(PosixFilePermission.OWNER_EXECUTE); + .contains(PosixFilePermission.OWNER_EXECUTE); } catch (UnsupportedOperationException ex) { // Probably running the test on Windows @@ -185,8 +185,10 @@ class RepackagerTests extends AbstractPackagerTests { timestamp = entry.getTime(); } else { - assertThat(entry.getTime()).withFailMessage("Expected time %d to be equal to %d for entry %s", - entry.getTime(), timestamp, entry.getName()).isEqualTo(timestamp); + assertThat(entry.getTime()) + .withFailMessage("Expected time %d to be equal to %d for entry %s", entry.getTime(), timestamp, + entry.getName()) + .isEqualTo(timestamp); } } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java index beed00e11d..2ce128cc64 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/TestJarFile.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,7 +59,7 @@ public class TestJarFile { File file = getFilePath(filename); file.getParentFile().mkdirs(); InputStream inputStream = getClass() - .getResourceAsStream("/" + classToCopy.getName().replace('.', '/') + ".class"); + .getResourceAsStream("/" + classToCopy.getName().replace('.', '/') + ".class"); copyToFile(inputStream, file); if (time != null) { file.setLastModified(time); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java index 36bbec3084..fd2e7838f9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/ApplicationContentFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -33,13 +33,13 @@ class ApplicationContentFilterTests { @Test void createWhenPatternIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContentFilter(null)) - .withMessage("Pattern must not be empty"); + .withMessage("Pattern must not be empty"); } @Test void createWhenPatternIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ApplicationContentFilter("")) - .withMessage("Pattern must not be empty"); + .withMessage("Pattern must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java index f5efbfe924..f012acdcab 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -39,16 +39,17 @@ class IncludeExcludeContentSelectorTests { @Test void createWhenLayerIsNullThrowsException() { - assertThatIllegalArgumentException().isThrownBy( - () -> new IncludeExcludeContentSelector<>(null, Collections.emptyList(), Collections.emptyList())) - .withMessage("Layer must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new IncludeExcludeContentSelector<>(null, Collections.emptyList(), Collections.emptyList())) + .withMessage("Layer must not be null"); } @Test void createWhenFactoryIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new IncludeExcludeContentSelector<>(LAYER, null, null, null)) - .withMessage("FilterFactory must not be null"); + .isThrownBy(() -> new IncludeExcludeContentSelector<>(LAYER, null, null, null)) + .withMessage("FilterFactory must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java index bcdaf986d2..b6dd41c06c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/LibraryContentFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -38,13 +38,13 @@ class LibraryContentFilterTests { @Test void createWhenCoordinatesPatternIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new LibraryContentFilter(null)) - .withMessage("CoordinatesPattern must not be empty"); + .withMessage("CoordinatesPattern must not be empty"); } @Test void createWhenCoordinatesPatternIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new LibraryContentFilter("")) - .withMessage("CoordinatesPattern must not be empty"); + .withMessage("CoordinatesPattern must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java index acc05a439f..19c88dda52 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/CentralDirectoryFileHeader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -162,8 +162,10 @@ final class CentralDirectoryFileHeader implements FileHeader { int hour = getChronoValue((datetime >> 11) & 0x1f, ChronoField.HOUR_OF_DAY); int minute = getChronoValue((datetime >> 5) & 0x3f, ChronoField.MINUTE_OF_HOUR); int second = getChronoValue((datetime << 1) & 0x3e, ChronoField.SECOND_OF_MINUTE); - return ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.systemDefault()).toInstant() - .truncatedTo(ChronoUnit.SECONDS).toEpochMilli(); + return ZonedDateTime.of(year, month, day, hour, minute, second, 0, ZoneId.systemDefault()) + .toInstant() + .truncatedTo(ChronoUnit.SECONDS) + .toEpochMilli(); } long getCrc() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java index c8f96b4f0b..d151c8d80a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileEntries.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -86,14 +86,14 @@ class JarFileEntries implements CentralDirectoryVisitor, Iterable { private JarEntryCertification[] certifications; private final Map entriesCache = Collections - .synchronizedMap(new LinkedHashMap<>(16, 0.75f, true) { + .synchronizedMap(new LinkedHashMap<>(16, 0.75f, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() >= ENTRY_CACHE_SIZE; - } + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() >= ENTRY_CACHE_SIZE; + } - }); + }); JarFileEntries(JarFile jarFile, JarEntryFilter filter) { this.jarFile = jarFile; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java index a7e74a6fa5..4cd1b4e8d2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/ClassPathIndexFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,8 +44,8 @@ class ClassPathIndexFileTests { @Test void loadIfPossibleWhenRootIsNotFileReturnsNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> ClassPathIndexFile.loadIfPossible(new URL("https://example.com/file"), "test.idx")) - .withMessage("URL does not reference a file"); + .isThrownBy(() -> ClassPathIndexFile.loadIfPossible(new URL("https://example.com/file"), "test.idx")) + .withMessage("URL does not reference a file"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index 387ebb9625..ab7c296b38 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -99,7 +99,7 @@ class PropertiesLauncherTests { @SuppressWarnings("unchecked") private void clearHandlerCache() throws Exception { Map rootFileCache = ((SoftReference>) ReflectionTestUtils - .getField(Handler.class, "rootFileCache")).get(); + .getField(Handler.class, "rootFileCache")).get(); if (rootFileCache != null) { for (JarFile rootJarFile : rootFileCache.values()) { rootJarFile.close(); @@ -127,7 +127,8 @@ class PropertiesLauncherTests { void testNonExistentHome() { System.setProperty("loader.home", "src/test/resources/nonexistent"); assertThatIllegalStateException().isThrownBy(PropertiesLauncher::new) - .withMessageContaining("Invalid source directory").withCauseInstanceOf(IllegalArgumentException.class); + .withMessageContaining("Invalid source directory") + .withCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -194,7 +195,7 @@ class PropertiesLauncherTests { System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/"); this.launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(this.launcher, "paths")) - .hasToString("[jar:file:./src/test/resources/nested-jars/app.jar!/]"); + .hasToString("[jar:file:./src/test/resources/nested-jars/app.jar!/]"); List archives = new ArrayList<>(); this.launcher.getClassPathArchivesIterator().forEachRemaining(archives::add); assertThat(archives).areExactly(1, endingWith("foo.jar!/")); @@ -237,7 +238,7 @@ class PropertiesLauncherTests { System.setProperty("loader.main", "demo.Application"); this.launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(this.launcher, "paths")) - .hasToString("[nested-jars/nested-jar-app.jar!/BOOT-INF/classes/]"); + .hasToString("[nested-jars/nested-jar-app.jar!/BOOT-INF/classes/]"); this.launcher.launch(new String[0]); waitFor("Hello World"); } @@ -277,7 +278,7 @@ class PropertiesLauncherTests { System.setProperty("loader.classLoader", URLClassLoader.class.getName()); this.launcher = new PropertiesLauncher(); assertThat(ReflectionTestUtils.getField(this.launcher, "paths")) - .hasToString("[more-jars/app.jar, jars/app.jar]"); + .hasToString("[more-jars/app.jar, jars/app.jar]"); this.launcher.launch(new String[0]); waitFor("Hello Other World"); } @@ -393,7 +394,7 @@ class PropertiesLauncherTests { catch (Exception ex) { // Expected ClassNotFoundException LaunchedURLClassLoader classLoader = (LaunchedURLClassLoader) Thread.currentThread() - .getContextClassLoader(); + .getContextClassLoader(); classLoader.close(); } URL resource = new URL("jar:" + jarFile.toURI() + "!/nested.jar!/3.dat"); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java index 55ce623a3e..4b2ce93af6 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java @@ -136,7 +136,7 @@ class JarFileArchiveTests { setup(true); try (Archive nestedArchive = this.archive.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")); Archive anotherNestedArchive = this.archive - .getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar"))) { + .getNestedArchive(getEntriesMap(this.archive).get("another-nested.jar"))) { File nested = new File(nestedArchive.getUrl().toURI()); File anotherNested = new File(anotherNestedArchive.getUrl().toURI()); assertThat(nested).hasParent(anotherNested.getParent()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index 0262856d01..6713814def 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -79,14 +79,14 @@ class RandomAccessDataFileTests { @Test void fileNotNull() { assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(null)) - .withMessageContaining("File must not be null"); + .withMessageContaining("File must not be null"); } @Test void fileExists() { File file = new File("/does/not/exist"); assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(file)) - .withMessageContaining(String.format("File %s must exist", file.getAbsolutePath())); + .withMessageContaining(String.format("File %s must exist", file.getAbsolutePath())); } @Test @@ -127,13 +127,13 @@ class RandomAccessDataFileTests { @Test void inputStreamReadNullBytes() { assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null)) - .withMessage("Bytes must not be null"); + .withMessage("Bytes must not be null"); } @Test void inputStreamReadNullBytesWithOffset() { assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null, 0, 1)) - .withMessage("Bytes must not be null"); + .withMessage("Bytes must not be null"); } @Test @@ -286,7 +286,7 @@ class RandomAccessDataFileTests { for (int i = 0; i < 100; i++) { results.add(executorService.submit(() -> { InputStream subsectionInputStream = RandomAccessDataFileTests.this.file.getSubsection(0, 256) - .getInputStream(); + .getInputStream(); byte[] b = new byte[256]; subsectionInputStream.read(b); return Arrays.equals(b, BYTES); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java index c3fad4da72..1a64de6431 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/HandlerTests.java @@ -96,32 +96,36 @@ class HandlerTests { @Test void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"), - new URL("jar:file:/foo.jar!/content.txt"))).isFalse(); + new URL("jar:file:/foo.jar!/content.txt"))) + .isFalse(); } @Test void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), - new URL("jar:file:/second.jar!/content.txt"))).isFalse(); + new URL("jar:file:/second.jar!/content.txt"))) + .isFalse(); } @Test void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"), - new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))).isTrue(); + new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))) + .isTrue(); } @Test void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { assertThat(this.handler.sameFile(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"), - new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))).isTrue(); + new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))) + .isTrue(); } @Test void hashCodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException { assertThat(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"))) - .isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); + .isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))); } @Test @@ -157,11 +161,12 @@ class HandlerTests { File testJar = new File(tempDir, "test.jar"); TestJarCreator.createTestJar(testJar); URLConnection connection = new URL(null, "jar:" + testJar.toURI().toURL() + "!/nested.jar!/", this.handler) - .openConnection(); + .openConnection(); assertThat(connection).isInstanceOf(JarURLConnection.class); ((JarURLConnection) connection).getJarFile().close(); URLConnection jdkConnection = new URL(null, "jar:file:" + testJar.toURI().toURL() + "!/nested.jar!/", - this.handler).openConnection(); + this.handler) + .openConnection(); assertThat(jdkConnection).isNotInstanceOf(JarURLConnection.class); assertThat(jdkConnection.getClass().getName()).endsWith(".JarURLConnection"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java index 9bdb8130ec..1188dd0ba8 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java @@ -234,7 +234,7 @@ class JarFileTests { void getEntryTime() throws Exception { java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile); assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime()) - .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime()); + .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime()); jdkJarFile.close(); } @@ -280,7 +280,7 @@ class JarFileTests { URL url = new URL(this.jarFile.getUrl(), "missing.dat"); assertThat(url).hasToString("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); assertThatExceptionOfType(FileNotFoundException.class) - .isThrownBy(((JarURLConnection) url.openConnection())::getJarEntry); + .isThrownBy(((JarURLConnection) url.openConnection())::getJarEntry); } @Test @@ -442,9 +442,9 @@ class JarFileTests { StreamUtils.drain(expected.getInputStream(expectedEntry)); if (!actualEntry.getName().equals("META-INF/MANIFEST.MF")) { assertThat(actualEntry.getCertificates()).as(actualEntry.getName()) - .isEqualTo(expectedEntry.getCertificates()); + .isEqualTo(expectedEntry.getCertificates()); assertThat(actualEntry.getCodeSigners()).as(actualEntry.getName()) - .isEqualTo(expectedEntry.getCodeSigners()); + .isEqualTo(expectedEntry.getCodeSigners()); } } assertThat(stopWatch.getTotalTimeSeconds()).isLessThan(3.0); @@ -542,10 +542,11 @@ class JarFileTests { try (JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"))) { URL context = nested.getUrl(); new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat").openConnection() - .getInputStream().close(); + .getInputStream() + .close(); assertThatExceptionOfType(FileNotFoundException.class) - .isThrownBy(new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") - .openConnection()::getInputStream); + .isThrownBy(new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") + .openConnection()::getInputStream); } } finally { @@ -630,7 +631,7 @@ class JarFileTests { } try (JarFile outerJarFile = new JarFile(outer)) { try (JarFile nestedZip64JarFile = outerJarFile - .getNestedJarFile(outerJarFile.getJarEntry("nested-zip64.jar"))) { + .getNestedJarFile(outerJarFile.getJarEntry("nested-zip64.jar"))) { List entries = Collections.list(nestedZip64JarFile.entries()); assertThat(entries).hasSize(65537); for (int i = 0; i < entries.size(); i++) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java index d38f06c01a..8ae25b72e1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -148,7 +148,7 @@ class JarFileWrapperTests { // of additional memory being used since cleanup only occurs when the // finalizer thread runs. See gh-22991 assertThatExceptionOfType(NoSuchMethodException.class) - .isThrownBy(() -> JarFileWrapper.class.getDeclaredMethod("close")); + .isThrownBy(() -> JarFileWrapper.class.getDeclaredMethod("close")); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java index 39b30bda02..d962a72fc5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java @@ -173,7 +173,7 @@ class JarURLConnectionTests { URL url = new URL("jar:" + this.rootJarFile.toURI().toURL() + "!/w.jar!/3.dat"); try (JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"))) { assertThatExceptionOfType(FileNotFoundException.class) - .isThrownBy(JarURLConnection.get(url, nested)::getInputStream); + .isThrownBy(JarURLConnection.get(url, nested)::getInputStream); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java index a99ace59d7..d9e5eb2814 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarUrlProtocolHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class JarUrlProtocolHandler implements BeforeEachCallback, AfterEachCallback { @SuppressWarnings("unchecked") public void afterEach(ExtensionContext context) throws Exception { Map rootFileCache = ((SoftReference>) ReflectionTestUtils - .getField(Handler.class, "rootFileCache")).get(); + .getField(Handler.class, "rootFileCache")).get(); if (rootFileCache != null) { for (JarFile rootJarFile : rootFileCache.values()) { rootJarFile.close(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java index 34e62d1c7e..ee7170f08c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java @@ -32,25 +32,25 @@ class StringSequenceTests { @Test void createWhenSourceIsNullShouldThrowException() { assertThatNullPointerException().isThrownBy(() -> new StringSequence(null)) - .withMessage("Source must not be null"); + .withMessage("Source must not be null"); } @Test void createWithIndexWhenSourceIsNullShouldThrowException() { assertThatNullPointerException().isThrownBy(() -> new StringSequence(null, 0, 0)) - .withMessage("Source must not be null"); + .withMessage("Source must not be null"); } @Test void createWhenStartIsLessThanZeroShouldThrowException() { assertThatExceptionOfType(StringIndexOutOfBoundsException.class) - .isThrownBy(() -> new StringSequence("x", -1, 0)); + .isThrownBy(() -> new StringSequence("x", -1, 0)); } @Test void createWhenEndIsGreaterThanLengthShouldThrowException() { assertThatExceptionOfType(StringIndexOutOfBoundsException.class) - .isThrownBy(() -> new StringSequence("x", 0, 2)); + .isThrownBy(() -> new StringSequence("x", 0, 2)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java index 28d8b30112..aeeb85e9fe 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AbstractArchiveIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,7 @@ abstract class AbstractArchiveIntegrationTests { } else if (line.startsWith(entryPrefix)) { index.computeIfAbsent(layer, (key) -> new ArrayList<>()) - .add(line.substring(entryPrefix.length() + 1, line.length() - 1)); + .add(line.substring(entryPrefix.length() + 1, line.length() - 1)); } line = reader.readLine(); } @@ -146,7 +146,7 @@ abstract class AbstractArchiveIntegrationTests { withJarFile((jarFile) -> { withEntries(jarFile, (entries) -> { Optional match = entries.filter((entry) -> entry.getName().startsWith(prefix)) - .findFirst(); + .findFirst(); assertThat(match).hasValueSatisfying((entry) -> assertThat(entry.getComment()).isNull()); }); }); @@ -157,9 +157,9 @@ abstract class AbstractArchiveIntegrationTests { withJarFile((jarFile) -> { withEntries(jarFile, (entries) -> { Optional match = entries.filter((entry) -> entry.getName().startsWith(prefix)) - .findFirst(); + .findFirst(); assertThat(match).as("Name starting with %s", prefix) - .hasValueSatisfying((entry) -> assertThat(entry.getComment()).startsWith("UNPACK:")); + .hasValueSatisfying((entry) -> assertThat(entry.getComment()).startsWith("UNPACK:")); }); }); return this; @@ -169,7 +169,7 @@ abstract class AbstractArchiveIntegrationTests { withJarFile((jarFile) -> { withEntries(jarFile, (entries) -> { Optional match = entries.filter((entry) -> entry.getName().startsWith(prefix)) - .findFirst(); + .findFirst(); assertThat(match).isNotPresent(); }); }); @@ -178,8 +178,10 @@ abstract class AbstractArchiveIntegrationTests { ListAssert entryNamesInPath(String path) { List matches = new ArrayList<>(); - withJarFile((jarFile) -> withEntries(jarFile, (entries) -> matches.addAll(entries.map(ZipEntry::getName) - .filter((name) -> name.startsWith(path) && name.length() > path.length()).toList()))); + withJarFile((jarFile) -> withEntries(jarFile, + (entries) -> matches.addAll(entries.map(ZipEntry::getName) + .filter((name) -> name.startsWith(path) && name.length() > path.length()) + .toList()))); return new ListAssert<>(matches); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AotTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AotTests.java index 962b7c7875..f205215898 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AotTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/AotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class AotTests { mavenBuild.project("aot").goals("package").execute((project) -> { Path aotDirectory = project.toPath().resolve("target/spring-aot/main"); assertThat(collectRelativePaths(aotDirectory.resolve("sources"))) - .contains(Path.of("org", "test", "SampleApplication__ApplicationContextInitializer.java")); + .contains(Path.of("org", "test", "SampleApplication__ApplicationContextInitializer.java")); }); } @@ -84,7 +84,7 @@ class AotTests { mavenBuild.project("aot-class-proxy").goals("package").execute((project) -> { Path aotDirectory = project.toPath().resolve("target/spring-aot/main"); assertThat(collectRelativePaths(aotDirectory.resolve("classes"))) - .contains(Path.of("org", "test", "SampleRunner$$SpringCGLIB$$0.class")); + .contains(Path.of("org", "test", "SampleRunner$$SpringCGLIB$$0.class")); }); } @@ -93,7 +93,7 @@ class AotTests { mavenBuild.project("aot-profile").goals("package").execute((project) -> { Path aotDirectory = project.toPath().resolve("target/spring-aot/main"); assertThat(collectRelativePaths(aotDirectory.resolve("sources"))) - .contains(Path.of("org", "test", "TestProfileConfiguration__BeanDefinitions.java")); + .contains(Path.of("org", "test", "TestProfileConfiguration__BeanDefinitions.java")); }); } @@ -102,7 +102,7 @@ class AotTests { mavenBuild.project("aot-arguments").goals("package").execute((project) -> { Path aotDirectory = project.toPath().resolve("target/spring-aot/main"); assertThat(collectRelativePaths(aotDirectory.resolve("sources"))) - .contains(Path.of("org", "test", "TestProfileConfiguration__BeanDefinitions.java")); + .contains(Path.of("org", "test", "TestProfileConfiguration__BeanDefinitions.java")); }); } @@ -111,7 +111,7 @@ class AotTests { mavenBuild.project("aot-jvm-arguments").goals("package").execute((project) -> { Path aotDirectory = project.toPath().resolve("target/spring-aot/main"); assertThat(collectRelativePaths(aotDirectory.resolve("sources"))) - .contains(Path.of("org", "test", "TestProfileConfiguration__BeanDefinitions.java")); + .contains(Path.of("org", "test", "TestProfileConfiguration__BeanDefinitions.java")); }); } @@ -120,14 +120,16 @@ class AotTests { mavenBuild.project("aot-release").goals("package").execute((project) -> { Path aotDirectory = project.toPath().resolve("target/spring-aot/main"); assertThat(collectRelativePaths(aotDirectory.resolve("sources"))) - .contains(Path.of("org", "test", "SampleApplication__ApplicationContextInitializer.java")); + .contains(Path.of("org", "test", "SampleApplication__ApplicationContextInitializer.java")); }); } @TestTemplate void whenAotRunsWithInvalidCompilerArgumentsCompileFails(MavenBuild mavenBuild) { - mavenBuild.project("aot-compiler-arguments").goals("package").executeAndFail( - (project) -> assertThat(buildLog(project)).contains("invalid flag: --invalid-compiler-arg")); + mavenBuild.project("aot-compiler-arguments") + .goals("package") + .executeAndFail( + (project) -> assertThat(buildLog(project)).contains("invalid flag: --invalid-compiler-arg")); } @TestTemplate @@ -135,7 +137,7 @@ class AotTests { mavenBuild.project("aot").goals("package").execute((project) -> { Path classesDirectory = project.toPath().resolve("target/classes"); assertThat(collectRelativePaths(classesDirectory)) - .contains(Path.of("org", "test", "SampleApplication__ApplicationContextInitializer.class")); + .contains(Path.of("org", "test", "SampleApplication__ApplicationContextInitializer.class")); }); } @@ -156,7 +158,7 @@ class AotTests { mavenBuild.project("aot-class-proxy").goals("package").execute((project) -> { Path classesDirectory = project.toPath().resolve("target/classes/"); assertThat(collectRelativePaths(classesDirectory)) - .contains(Path.of("org", "test", "SampleRunner$$SpringCGLIB$$0.class")); + .contains(Path.of("org", "test", "SampleRunner$$SpringCGLIB$$0.class")); }); } @@ -177,7 +179,8 @@ class AotTests { List collectRelativePaths(Path sourceDirectory) { try (Stream pathStream = Files.walk(sourceDirectory)) { return pathStream.filter(Files::isRegularFile) - .map((path) -> path.subpath(sourceDirectory.getNameCount(), path.getNameCount())).toList(); + .map((path) -> path.subpath(sourceDirectory.getNameCount(), path.getNameCount())) + .toList(); } catch (IOException ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java index 3a8de6021f..fb0d88aeac 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageRegistryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class BuildImageRegistryIntegrationTests extends AbstractArchiveIntegrationTests @Container static final RegistryContainer registry = new RegistryContainer().withStartupAttempts(5) - .withStartupTimeout(Duration.ofMinutes(3)); + .withStartupTimeout(Duration.ofMinutes(3)); DockerClient dockerClient; @@ -64,17 +64,20 @@ class BuildImageRegistryIntegrationTests extends AbstractArchiveIntegrationTests void whenBuildImageIsInvokedWithPublish(MavenBuild mavenBuild) { String repoName = "test-image"; String imageName = this.registryAddress + "/" + repoName; - mavenBuild.project("build-image-publish").goals("package") - .systemProperty("spring-boot.build-image.imageName", imageName).execute((project) -> { - assertThat(buildLog(project)).contains("Building image").contains("Successfully built image") - .contains("Pushing image '" + imageName + ":latest" + "'") - .contains("Pushed image '" + imageName + ":latest" + "'"); - ImageReference imageReference = ImageReference.of(imageName); - DockerApi.ImageApi imageApi = new DockerApi().image(); - Image pulledImage = imageApi.pull(imageReference, UpdateListener.none()); - assertThat(pulledImage).isNotNull(); - imageApi.remove(imageReference, false); - }); + mavenBuild.project("build-image-publish") + .goals("package") + .systemProperty("spring-boot.build-image.imageName", imageName) + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("Successfully built image") + .contains("Pushing image '" + imageName + ":latest" + "'") + .contains("Pushed image '" + imageName + ":latest" + "'"); + ImageReference imageReference = ImageReference.of(imageName); + DockerApi.ImageApi imageApi = new DockerApi().image(); + Image pulledImage = imageApi.pull(imageReference, UpdateListener.none()); + assertThat(pulledImage).isNotNull(); + imageApi.remove(imageReference, false); + }); } private static class RegistryContainer extends GenericContainer { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java index b94a8ef4dc..888d87529a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildImageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,333 +49,386 @@ class BuildImageTests extends AbstractArchiveIntegrationTests { @TestTemplate void whenBuildImageIsInvokedWithoutRepackageTheArchiveIsRepackagedOnTheFly(MavenBuild mavenBuild) { - mavenBuild.project("build-image").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, "target/build-image-0.0.1.BUILD-SNAPSHOT.jar.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedOnTheCommandLineWithoutRepackageTheArchiveIsRepackagedOnTheFly(MavenBuild mavenBuild) { - mavenBuild.project("build-image-cmd-line").goals("spring-boot:build-image") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-cmd-line-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, "target/build-image-cmd-line-0.0.1.BUILD-SNAPSHOT.jar.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-cmd-line:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-cmd-line", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-cmd-line") + .goals("spring-boot:build-image") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-cmd-line-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, "target/build-image-cmd-line-0.0.1.BUILD-SNAPSHOT.jar.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-cmd-line:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-cmd-line", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierWithoutRepackageTheArchiveIsRepackagedOnTheFly(MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File classifier = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(classifier).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-classifier:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-classifier", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File classifier = new File(project, "target/build-image-classifier-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(classifier).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierSourceWithoutRepackageTheArchiveIsRepackagedOnTheFly( MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier-source").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-classifier-source:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-classifier-source", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier-source") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier-source:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier-source", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithRepackageTheExistingArchiveIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("build-image-with-repackage").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar.original"); - assertThat(original).isFile(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-with-repackage:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-with-repackage", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-with-repackage") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-with-repackage-0.0.1.BUILD-SNAPSHOT.jar.original"); + assertThat(original).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-with-repackage:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-with-repackage", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierAndRepackageTheExistingArchiveIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier-with-repackage").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, - "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(original).isFile(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-classifier-with-repackage:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-classifier-with-repackage", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier-with-repackage") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-classifier-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(original).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier-with-repackage:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier-with-repackage", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithClassifierSourceAndRepackageTheExistingArchiveIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("build-image-classifier-source-with-repackage").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File jar = new File(project, - "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar.original"); - assertThat(original).isFile(); - assertThat(buildLog(project)).contains("Building image").contains( - "docker.io/library/build-image-classifier-source-with-repackage:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-classifier-source-with-repackage", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-classifier-source-with-repackage") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File jar = new File(project, + "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar"); + assertThat(jar).isFile(); + File original = new File(project, + "target/build-image-classifier-source-with-repackage-0.0.1.BUILD-SNAPSHOT-test.jar.original"); + assertThat(original).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-classifier-source-with-repackage:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-classifier-source-with-repackage", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithWarPackaging(MavenBuild mavenBuild) { - mavenBuild.project("build-image-war-packaging").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - File war = new File(project, "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war"); - assertThat(war).isFile(); - File original = new File(project, - "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-war-packaging:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-war-packaging", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-war-packaging") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + File war = new File(project, "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war"); + assertThat(war).isFile(); + File original = new File(project, "target/build-image-war-packaging-0.0.1.BUILD-SNAPSHOT.war.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-war-packaging:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-war-packaging", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithCustomImageName(MavenBuild mavenBuild) { - mavenBuild.project("build-image-custom-name").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .systemProperty("spring-boot.build-image.imageName", "example.com/test/property-ignored:pom-preferred") - .execute((project) -> { - File jar = new File(project, "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - File original = new File(project, - "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar.original"); - assertThat(original).doesNotExist(); - assertThat(buildLog(project)).contains("Building image") - .contains("example.com/test/build-image:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("example.com/test/build-image", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-custom-name") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .systemProperty("spring-boot.build-image.imageName", "example.com/test/property-ignored:pom-preferred") + .execute((project) -> { + File jar = new File(project, "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + File original = new File(project, "target/build-image-custom-name-0.0.1.BUILD-SNAPSHOT.jar.original"); + assertThat(original).doesNotExist(); + assertThat(buildLog(project)).contains("Building image") + .contains("example.com/test/build-image:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("example.com/test/build-image", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithCommandLineParameters(MavenBuild mavenBuild) { - mavenBuild.project("build-image").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .systemProperty("spring-boot.build-image.imageName", "example.com/test/cmd-property-name:v1") - .systemProperty("spring-boot.build-image.builder", - "projects.registry.vmware.com/springboot/spring-boot-cnb-builder:0.0.1") - .systemProperty("spring-boot.build-image.runImage", - "projects.registry.vmware.com/springboot/run:tiny-cnb") - .execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("example.com/test/cmd-property-name:v1") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("example.com/test/cmd-property-name", "v1"); - }); + mavenBuild.project("build-image") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .systemProperty("spring-boot.build-image.imageName", "example.com/test/cmd-property-name:v1") + .systemProperty("spring-boot.build-image.builder", + "projects.registry.vmware.com/springboot/spring-boot-cnb-builder:0.0.1") + .systemProperty("spring-boot.build-image.runImage", "projects.registry.vmware.com/springboot/run:tiny-cnb") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("example.com/test/cmd-property-name:v1") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("example.com/test/cmd-property-name", "v1"); + }); } @TestTemplate void whenBuildImageIsInvokedWithCustomBuilderImageAndRunImage(MavenBuild mavenBuild) { - mavenBuild.project("build-image-custom-builder").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-v2-builder:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("docker.io/library/build-image-v2-builder", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-custom-builder") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-v2-builder:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("docker.io/library/build-image-v2-builder", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithEmptyEnvEntry(MavenBuild mavenBuild) { - mavenBuild.project("build-image-empty-env-entry").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .prepare(this::writeLongNameResource).execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-empty-env-entry:0.0.1.BUILD-SNAPSHOT") - .contains("---> Test Info buildpack building").contains("---> Test Info buildpack done") - .contains("Successfully built image"); - removeImage("build-image-empty-env-entry", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-empty-env-entry") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .prepare(this::writeLongNameResource) + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-empty-env-entry:0.0.1.BUILD-SNAPSHOT") + .contains("---> Test Info buildpack building") + .contains("---> Test Info buildpack done") + .contains("Successfully built image"); + removeImage("build-image-empty-env-entry", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithZipPackaging(MavenBuild mavenBuild) { - mavenBuild.project("build-image-zip-packaging").goals("package").prepare(this::writeLongNameResource) - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - File jar = new File(project, "target/build-image-zip-packaging-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar).isFile(); - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-zip-packaging:0.0.1.BUILD-SNAPSHOT") - .contains("Main-Class: org.springframework.boot.loader.PropertiesLauncher") - .contains("Successfully built image"); - removeImage("build-image-zip-packaging", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-zip-packaging") + .goals("package") + .prepare(this::writeLongNameResource) + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + File jar = new File(project, "target/build-image-zip-packaging-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar).isFile(); + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-zip-packaging:0.0.1.BUILD-SNAPSHOT") + .contains("Main-Class: org.springframework.boot.loader.PropertiesLauncher") + .contains("Successfully built image"); + removeImage("build-image-zip-packaging", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithBuildpacks(MavenBuild mavenBuild) { - mavenBuild.project("build-image-custom-buildpacks").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-custom-buildpacks:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image"); - removeImage("build-image-custom-buildpacks", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-custom-buildpacks") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-custom-buildpacks:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image"); + removeImage("build-image-custom-buildpacks", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithBinding(MavenBuild mavenBuild) { - mavenBuild.project("build-image-bindings").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-bindings:0.0.1.BUILD-SNAPSHOT") - .contains("binding: ca-certificates/type=ca-certificates") - .contains("binding: ca-certificates/test.crt=---certificate one---") - .contains("Successfully built image"); - removeImage("build-image-bindings", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-bindings") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-bindings:0.0.1.BUILD-SNAPSHOT") + .contains("binding: ca-certificates/type=ca-certificates") + .contains("binding: ca-certificates/test.crt=---certificate one---") + .contains("Successfully built image"); + removeImage("build-image-bindings", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithNetworkModeNone(MavenBuild mavenBuild) { - mavenBuild.project("build-image-network").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-network:0.0.1.BUILD-SNAPSHOT") - .contains("Network status: curl failed").contains("Successfully built image"); - removeImage("build-image-network", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-network") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-network:0.0.1.BUILD-SNAPSHOT") + .contains("Network status: curl failed") + .contains("Successfully built image"); + removeImage("build-image-network", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedOnMultiModuleProjectWithPackageGoal(MavenBuild mavenBuild) { - mavenBuild.project("build-image-multi-module").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-multi-module-app:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image"); - removeImage("build-image-multi-module-app", "0.0.1.BUILD-SNAPSHOT"); - }); + mavenBuild.project("build-image-multi-module") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-multi-module-app:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image"); + removeImage("build-image-multi-module-app", "0.0.1.BUILD-SNAPSHOT"); + }); } @TestTemplate void whenBuildImageIsInvokedWithTags(MavenBuild mavenBuild) { - mavenBuild.project("build-image-tags").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-tags:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image").contains("docker.io/library/build-image-tags:latest") - .contains("Successfully created image tag"); - removeImage("build-image-tags", "0.0.1.BUILD-SNAPSHOT"); - removeImage("build-image-tags", "latest"); - }); + mavenBuild.project("build-image-tags") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-tags:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image") + .contains("docker.io/library/build-image-tags:latest") + .contains("Successfully created image tag"); + removeImage("build-image-tags", "0.0.1.BUILD-SNAPSHOT"); + removeImage("build-image-tags", "latest"); + }); } @TestTemplate void whenBuildImageIsInvokedWithVolumeCaches(MavenBuild mavenBuild) { String testBuildId = randomString(); - mavenBuild.project("build-image-caches").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .systemProperty("test-build-id", testBuildId).execute((project) -> { - assertThat(buildLog(project)).contains("Building image") - .contains("docker.io/library/build-image-caches:0.0.1.BUILD-SNAPSHOT") - .contains("Successfully built image"); - removeImage("build-image-caches", "0.0.1.BUILD-SNAPSHOT"); - deleteVolumes("cache-" + testBuildId + ".build", "cache-" + testBuildId + ".launch"); - }); + mavenBuild.project("build-image-caches") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .systemProperty("test-build-id", testBuildId) + .execute((project) -> { + assertThat(buildLog(project)).contains("Building image") + .contains("docker.io/library/build-image-caches:0.0.1.BUILD-SNAPSHOT") + .contains("Successfully built image"); + removeImage("build-image-caches", "0.0.1.BUILD-SNAPSHOT"); + deleteVolumes("cache-" + testBuildId + ".build", "cache-" + testBuildId + ".launch"); + }); } @TestTemplate void failsWhenBuildImageIsInvokedOnMultiModuleProjectWithBuildImageGoal(MavenBuild mavenBuild) { - mavenBuild.project("build-image-multi-module").goals("spring-boot:build-image") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT").executeAndFail( - (project) -> assertThat(buildLog(project)).contains("Error packaging archive for image")); + mavenBuild.project("build-image-multi-module") + .goals("spring-boot:build-image") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .executeAndFail((project) -> assertThat(buildLog(project)).contains("Error packaging archive for image")); } @TestTemplate void failsWhenBuilderFails(MavenBuild mavenBuild) { - mavenBuild.project("build-image-builder-error").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .executeAndFail((project) -> assertThat(buildLog(project)).contains("Building image") - .contains("---> Test Info buildpack building").contains("Forced builder failure") - .containsPattern("Builder lifecycle '.*' failed with status code")); + mavenBuild.project("build-image-builder-error") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .executeAndFail((project) -> assertThat(buildLog(project)).contains("Building image") + .contains("---> Test Info buildpack building") + .contains("Forced builder failure") + .containsPattern("Builder lifecycle '.*' failed with status code")); } @TestTemplate void failsWithBuildpackNotInBuilder(MavenBuild mavenBuild) { - mavenBuild.project("build-image-bad-buildpack").goals("package") - .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") - .executeAndFail((project) -> assertThat(buildLog(project)) - .contains("'urn:cnb:builder:example/does-not-exist:0.0.1' not found in builder")); + mavenBuild.project("build-image-bad-buildpack") + .goals("package") + .systemProperty("spring-boot.build-image.pullPolicy", "IF_NOT_PRESENT") + .executeAndFail((project) -> assertThat(buildLog(project)) + .contains("'urn:cnb:builder:example/does-not-exist:0.0.1' not found in builder")); } @TestTemplate void failsWhenFinalNameIsMisconfigured(MavenBuild mavenBuild) { - mavenBuild.project("build-image-final-name").goals("package") - .executeAndFail((project) -> assertThat(buildLog(project)).contains("final-name.jar.original") - .contains("is required for building an image")); + mavenBuild.project("build-image-final-name") + .goals("package") + .executeAndFail((project) -> assertThat(buildLog(project)).contains("final-name.jar.original") + .contains("is required for building an image")); } @TestTemplate void failsWhenCachesAreConfiguredTwice(MavenBuild mavenBuild) { - mavenBuild.project("build-image-caches-multiple").goals("package") - .executeAndFail((project) -> assertThat(buildLog(project)) - .contains("Each image building cache can be configured only once")); + mavenBuild.project("build-image-caches-multiple") + .goals("package") + .executeAndFail((project) -> assertThat(buildLog(project)) + .contains("Each image building cache can be configured only once")); } private void writeLongNameResource(File project) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java index aed0440a5d..036aa6912d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/BuildInfoIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,67 +42,86 @@ class BuildInfoIntegrationTests { @TestTemplate void buildInfoPropertiesAreGenerated(MavenBuild mavenBuild) { - mavenBuild.project("build-info").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info") - .hasBuildName("Generate build info").hasBuildVersion("0.0.1.BUILD-SNAPSHOT").containsBuildTime())); + mavenBuild.project("build-info") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info") + .hasBuildName("Generate build info") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .containsBuildTime())); } @TestTemplate void generatedBuildInfoIncludesAdditionalProperties(MavenBuild mavenBuild) { - mavenBuild.project("build-info-additional-properties").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-additional-properties") - .hasBuildName("Generate build info with additional properties").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") - .containsBuildTime().containsEntry("build.foo", "bar").containsEntry("build.encoding", "UTF-8") + mavenBuild.project("build-info-additional-properties") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-additional-properties") + .hasBuildName("Generate build info with additional properties") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .containsBuildTime() + .containsEntry("build.foo", "bar") + .containsEntry("build.encoding", "UTF-8") .containsEntry("build.java.source", "1.8"))); } @TestTemplate void generatedBuildInfoUsesCustomBuildTime(MavenBuild mavenBuild) { - mavenBuild.project("build-info-custom-build-time").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-custom-build-time") - .hasBuildName("Generate build info with custom build time").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + mavenBuild.project("build-info-custom-build-time") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-custom-build-time") + .hasBuildName("Generate build info with custom build time") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") .hasBuildTime("2019-07-08T08:00:00Z"))); } @TestTemplate void generatedBuildInfoReproducible(MavenBuild mavenBuild) { mavenBuild.project("build-info-reproducible") - .execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-reproducible") - .hasBuildName("Generate build info with build time from project.build.outputTimestamp") - .hasBuildVersion("0.0.1.BUILD-SNAPSHOT").hasBuildTime("2021-04-21T11:22:33Z"))); + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-reproducible") + .hasBuildName("Generate build info with build time from project.build.outputTimestamp") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .hasBuildTime("2021-04-21T11:22:33Z"))); } @TestTemplate void buildInfoPropertiesAreGeneratedToCustomOutputLocation(MavenBuild mavenBuild) { mavenBuild.project("build-info-custom-file") - .execute(buildInfo("target/build.info", - (buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") - .hasBuildArtifact("build-info-custom-file").hasBuildName("Generate custom build info") - .hasBuildVersion("0.0.1.BUILD-SNAPSHOT").containsBuildTime())); + .execute(buildInfo("target/build.info", + (buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-custom-file") + .hasBuildName("Generate custom build info") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + .containsBuildTime())); } @TestTemplate void whenBuildTimeIsDisabledIfDoesNotAppearInGeneratedBuildInfo(MavenBuild mavenBuild) { - mavenBuild.project("build-info-disable-build-time").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-disable-build-time") - .hasBuildName("Generate build info with disabled build time").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + mavenBuild.project("build-info-disable-build-time") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-disable-build-time") + .hasBuildName("Generate build info with disabled build time") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") .doesNotContainBuildTime())); } @TestTemplate void whenBuildTimeIsExcludedIfDoesNotAppearInGeneratedBuildInfo(MavenBuild mavenBuild) { - mavenBuild.project("build-info-exclude-build-time").execute(buildInfo((buildInfo) -> assertThat(buildInfo) - .hasBuildGroup("org.springframework.boot.maven.it").hasBuildArtifact("build-info-exclude-build-time") - .hasBuildName("Generate build info with excluded build time").hasBuildVersion("0.0.1.BUILD-SNAPSHOT") + mavenBuild.project("build-info-exclude-build-time") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("org.springframework.boot.maven.it") + .hasBuildArtifact("build-info-exclude-build-time") + .hasBuildName("Generate build info with excluded build time") + .hasBuildVersion("0.0.1.BUILD-SNAPSHOT") .doesNotContainBuildTime())); } @TestTemplate void whenBuildPropertiesAreExcludedTheyDoNotAppearInGeneratedBuildInfo(MavenBuild mavenBuild) { - mavenBuild.project("build-info-exclude-build-properties").execute( - buildInfo((buildInfo) -> assertThat(buildInfo).doesNotContainBuildGroup().doesNotContainBuildArtifact() - .doesNotContainBuildName().doesNotContainBuildVersion().containsBuildTime())); + mavenBuild.project("build-info-exclude-build-properties") + .execute(buildInfo((buildInfo) -> assertThat(buildInfo).doesNotContainBuildGroup() + .doesNotContainBuildArtifact() + .doesNotContainBuildName() + .doesNotContainBuildVersion() + .containsBuildTime())); } private ProjectCallback buildInfo(Consumer> buildInfo) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java index de5e91023d..d473fc0e28 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/JarIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,14 +59,16 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { manifest.hasMainClass("org.springframework.boot.loader.JarLauncher"); manifest.hasStartClass("some.random.Main"); manifest.hasAttribute("Not-Used", "Foo"); - }).hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jakarta.servlet-api-6") - .hasEntryWithName("BOOT-INF/classes/org/test/SampleApplication.class") - .hasEntryWithName("org/springframework/boot/loader/JarLauncher.class"); + }) + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jakarta.servlet-api-6") + .hasEntryWithName("BOOT-INF/classes/org/test/SampleApplication.class") + .hasEntryWithName("org/springframework/boot/loader/JarLauncher.class"); assertThat(buildLog(project)).contains("Replacing main artifact with repackaged archive") - .contains("Installing " + repackaged + " to").doesNotContain("Installing " + original + " to"); + .contains("Installing " + repackaged + " to") + .doesNotContain("Installing " + original + " to"); }); } @@ -78,7 +80,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { File main = new File(project, "target/jar-attach-disabled-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(main).isFile(); assertThat(buildLog(project)).contains("Updating main artifact " + main + " to " + original) - .contains("Installing " + original + " to").doesNotContain("Installing " + main + " to"); + .contains("Installing " + original + " to") + .doesNotContain("Installing " + main + " to"); }); } @@ -87,15 +90,16 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { MavenBuild mavenBuild) { mavenBuild.project("jar-classifier-main").goals("install").execute((project) -> { assertThat(new File(project, "target/jar-classifier-main-0.0.1.BUILD-SNAPSHOT.jar.original")) - .doesNotExist(); + .doesNotExist(); File main = new File(project, "target/jar-classifier-main-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(main).isFile(); File repackaged = new File(project, "target/jar-classifier-main-0.0.1.BUILD-SNAPSHOT-test.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(buildLog(project)) - .contains("Attaching repackaged archive " + repackaged + " with classifier test") - .doesNotContain("Creating repackaged archive " + repackaged + " with classifier test") - .contains("Installing " + main + " to").contains("Installing " + repackaged + " to"); + .contains("Attaching repackaged archive " + repackaged + " with classifier test") + .doesNotContain("Creating repackaged archive " + repackaged + " with classifier test") + .contains("Installing " + main + " to") + .contains("Installing " + repackaged + " to"); }); } @@ -108,7 +112,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { File repackaged = new File(project, "target/jar-classifier-source-0.0.1.BUILD-SNAPSHOT-test.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(buildLog(project)).contains("Replacing artifact with classifier test with repackaged archive") - .doesNotContain("Installing " + original + " to").contains("Installing " + repackaged + " to"); + .doesNotContain("Installing " + original + " to") + .contains("Installing " + repackaged + " to"); }); } @@ -122,9 +127,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { "target/jar-classifier-source-attach-disabled-0.0.1.BUILD-SNAPSHOT-test.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(buildLog(project)) - .doesNotContain("Attaching repackaged archive " + repackaged + " with classifier test") - .contains("Updating artifact with classifier test " + repackaged + " to " + original) - .contains("Installing " + original + " to").doesNotContain("Installing " + repackaged + " to"); + .doesNotContain("Attaching repackaged archive " + repackaged + " with classifier test") + .contains("Updating artifact with classifier test " + repackaged + " to " + original) + .contains("Installing " + original + " to") + .doesNotContain("Installing " + repackaged + " to"); }); } @@ -161,10 +167,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-exclude-entry").goals("install").execute((project) -> { File repackaged = new File(project, "target/jar-exclude-entry-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") - .doesNotHaveEntryWithName("BOOT-INF/lib/servlet-api-2.5.jar"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") + .doesNotHaveEntryWithName("BOOT-INF/lib/servlet-api-2.5.jar"); }); } @@ -173,10 +179,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-exclude-group").goals("install").execute((project) -> { File repackaged = new File(project, "target/jar-exclude-group-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") - .doesNotHaveEntryWithName("BOOT-INF/lib/log4j-api-2.4.1.jar"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-core") + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-jcl") + .doesNotHaveEntryWithName("BOOT-INF/lib/log4j-api-2.4.1.jar"); }); } @@ -186,7 +192,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { File repackaged = new File(project, "target/jar-executable-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/"); assertThat(launchScript(repackaged)).contains("Spring Boot Startup Script") - .contains("MyFullyExecutableJarName").contains("MyFullyExecutableJarDesc"); + .contains("MyFullyExecutableJarName") + .contains("MyFullyExecutableJarDesc"); }); } @@ -195,10 +202,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-lib-name-conflict").execute((project) -> { File repackaged = new File(project, "test-project/target/test-project-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithName( - "BOOT-INF/lib/org.springframework.boot.maven.it-acme-lib-0.0.1.BUILD-SNAPSHOT.jar") - .hasEntryWithName( - "BOOT-INF/lib/org.springframework.boot.maven.it.another-acme-lib-0.0.1.BUILD-SNAPSHOT.jar"); + .hasEntryWithName("BOOT-INF/lib/org.springframework.boot.maven.it-acme-lib-0.0.1.BUILD-SNAPSHOT.jar") + .hasEntryWithName( + "BOOT-INF/lib/org.springframework.boot.maven.it.another-acme-lib-0.0.1.BUILD-SNAPSHOT.jar"); }); } @@ -244,7 +250,7 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-test-scope").execute((project) -> { File main = new File(project, "target/jar-test-scope-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(main)).doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/log4j") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-"); }); } @@ -258,14 +264,15 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { @TestTemplate void whenAProjectIsBuiltWithALayoutPropertyTheSpecifiedLayoutIsUsed(MavenBuild mavenBuild) { - mavenBuild.project("jar-with-layout-property").goals("package", "-Dspring-boot.repackage.layout=ZIP") - .execute((project) -> { - File main = new File(project, "target/jar-with-layout-property-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar(main)).manifest( - (manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") - .hasStartClass("org.test.SampleApplication")); - assertThat(buildLog(project)).contains("Layout: ZIP"); - }); + mavenBuild.project("jar-with-layout-property") + .goals("package", "-Dspring-boot.repackage.layout=ZIP") + .execute((project) -> { + File main = new File(project, "target/jar-with-layout-property-0.0.1.BUILD-SNAPSHOT.jar"); + assertThat(jar(main)) + .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") + .hasStartClass("org.test.SampleApplication")); + assertThat(buildLog(project)).contains("Layout: ZIP"); + }); } @TestTemplate @@ -273,8 +280,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-with-zip-layout").execute((project) -> { File main = new File(project, "target/jar-with-zip-layout-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(main)) - .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") - .hasStartClass("org.test.SampleApplication")); + .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.PropertiesLauncher") + .hasStartClass("org.test.SampleApplication")); assertThat(buildLog(project)).contains("Layout: ZIP"); }); } @@ -284,7 +291,7 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-with-unpack").execute((project) -> { File main = new File(project, "target/jar-with-unpack-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(main)).hasUnpackEntryWithNameStartingWith("BOOT-INF/lib/spring-core-") - .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context-"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/spring-context-"); }); } @@ -292,9 +299,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { void whenJarIsRepackagedWithACustomLayoutTheJarUsesTheLayout(MavenBuild mavenBuild) { mavenBuild.project("jar-custom-layout").execute((project) -> { assertThat(jar(new File(project, "custom/target/custom-0.0.1.BUILD-SNAPSHOT.jar"))) - .hasEntryWithName("custom"); + .hasEntryWithName("custom"); assertThat(jar(new File(project, "default/target/default-0.0.1.BUILD-SNAPSHOT.jar"))) - .hasEntryWithName("sample"); + .hasEntryWithName("sample"); }); } @@ -303,9 +310,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot").hasEntryWithNameStartingWith( - "BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith( + "BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("dependencies", "spring-boot-loader", @@ -313,7 +321,7 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(layerIndex.get("application")).contains("BOOT-INF/lib/jar-release-0.0.1.RELEASE.jar", "BOOT-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(layerIndex.get("dependencies")) - .anyMatch((dependency) -> dependency.startsWith("BOOT-INF/lib/log4j-api-2")); + .anyMatch((dependency) -> dependency.startsWith("BOOT-INF/lib/log4j-api-2")); } catch (IOException ex) { } @@ -325,10 +333,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered-disabled").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") - .doesNotHaveEntryWithName("BOOT-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") + .doesNotHaveEntryWithName("BOOT-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -337,10 +345,10 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered-no-layer-tools").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") - .hasEntryWithNameStartingWith("BOOT-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith("BOOT-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("BOOT-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -349,17 +357,17 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("jar-layered-custom").execute((project) -> { File repackaged = new File(project, "jar/target/jar-layered-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("BOOT-INF/classes/") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") - .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot"); + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-release") + .hasEntryWithNameStartingWith("BOOT-INF/lib/jar-snapshot"); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("my-dependencies-name", "snapshot-dependencies", "configuration", "application"); assertThat(layerIndex.get("application")) - .contains("BOOT-INF/lib/jar-release-0.0.1.RELEASE.jar", - "BOOT-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", - "BOOT-INF/lib/jar-classifier-0.0.1-bravo.jar") - .doesNotContain("BOOT-INF/lib/jar-classifier-0.0.1-alpha.jar"); + .contains("BOOT-INF/lib/jar-release-0.0.1.RELEASE.jar", + "BOOT-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", + "BOOT-INF/lib/jar-classifier-0.0.1-bravo.jar") + .doesNotContain("BOOT-INF/lib/jar-classifier-0.0.1-alpha.jar"); } }); } @@ -368,8 +376,8 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { void repackagedJarContainsClasspathIndex(MavenBuild mavenBuild) { mavenBuild.project("jar").execute((project) -> { File repackaged = new File(project, "target/jar-0.0.1.BUILD-SNAPSHOT.jar"); - assertThat(jar(repackaged)).manifest( - (manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "BOOT-INF/classpath.idx")); + assertThat(jar(repackaged)) + .manifest((manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "BOOT-INF/classpath.idx")); assertThat(jar(repackaged)).hasEntryWithName("BOOT-INF/classpath.idx"); try (JarFile jarFile = new JarFile(repackaged)) { List index = readClasspathIndex(jarFile, "BOOT-INF/classpath.idx"); @@ -395,8 +403,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(repackaged.lastModified()).isEqualTo(1584352800000L); try (JarFile jar = new JarFile(repackaged)) { List unreproducibleEntries = jar.stream() - .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) - .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()).toList(); + .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) + .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()) + .toList(); assertThat(unreproducibleEntries).isEmpty(); jarHash.set(FileUtils.sha1Hash(repackaged)); FileSystemUtils.deleteRecursively(project); @@ -416,8 +425,9 @@ class JarIntegrationTests extends AbstractArchiveIntegrationTests { "BOOT-INF/lib/spring-beans", "BOOT-INF/lib/spring-boot-jarmode-layertools", "BOOT-INF/lib/spring-context", "BOOT-INF/lib/spring-core", "BOOT-INF/lib/spring-expression", "BOOT-INF/lib/spring-jcl"); - assertThat(jar(repackaged)).entryNamesInPath("BOOT-INF/lib/").zipSatisfy(sortedLibs, - (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); + assertThat(jar(repackaged)).entryNamesInPath("BOOT-INF/lib/") + .zipSatisfy(sortedLibs, + (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java index c106f58d6c..2cd9cfb98c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java @@ -157,9 +157,8 @@ class MavenBuild { }); String settingsXml = Files.readString(Paths.get("src", "intTest", "projects", "settings.xml")) - .replace("@localCentralUrl@", - new File("build/int-test-maven-repository").toURI().toURL().toString()) - .replace("@localRepositoryPath@", new File("build/local-maven-repository").getAbsolutePath()); + .replace("@localCentralUrl@", new File("build/int-test-maven-repository").toURI().toURL().toString()) + .replace("@localRepositoryPath@", new File("build/local-maven-repository").getAbsolutePath()); Files.writeString(destination.resolve("settings.xml"), settingsXml, StandardOpenOption.CREATE_NEW); request.setBaseDirectory(this.temp); request.setJavaHome(new File(System.getProperty("java.home"))); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java index 742801cef5..ec9f69901b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/RunIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,90 +44,104 @@ class RunIntegrationTests { @TestTemplate void whenEnvironmentVariablesAreConfiguredTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-envargs").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-envargs") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenExclusionsAreConfiguredExcludedDependenciesDoNotAppearOnTheClasspath(MavenBuild mavenBuild) { - mavenBuild.project("run-exclude").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-exclude") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenSystemPropertiesAndJvmArgumentsAreConfiguredTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-jvm-system-props").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvm-system-props") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenJvmArgumentsAreConfiguredTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-jvmargs").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvmargs") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenCommandLineSpecifiesJvmArgumentsTheyAreAvailableToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-jvmargs-commandline").goals("spring-boot:run") - .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvmargs-commandline") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenPomAndCommandLineSpecifyJvmArgumentsThenPomOverrides(MavenBuild mavenBuild) { - mavenBuild.project("run-jvmargs").goals("spring-boot:run") - .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-jvmargs") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.jvmArguments", "-Dfoo=value-from-cmd") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenProfilesAreConfiguredTheyArePassedToTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-profiles").goals("spring-boot:run", "-X").execute( - (project) -> assertThat(buildLog(project)).contains("I haz been run with profile(s) 'foo,bar'")); + mavenBuild.project("run-profiles") + .goals("spring-boot:run", "-X") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run with profile(s) 'foo,bar'")); } @TestTemplate void whenUseTestClasspathIsEnabledTheApplicationHasTestDependenciesOnItsClasspath(MavenBuild mavenBuild) { - mavenBuild.project("run-use-test-classpath").goals("spring-boot:run") - .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); + mavenBuild.project("run-use-test-classpath") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).contains("I haz been run")); } @TestTemplate void whenAWorkingDirectoryIsConfiguredTheApplicationIsRunFromThatDirectory(MavenBuild mavenBuild) { - mavenBuild.project("run-working-directory").goals("spring-boot:run").execute( - (project) -> assertThat(buildLog(project)).containsPattern("I haz been run from.*src.main.java")); + mavenBuild.project("run-working-directory") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)).containsPattern("I haz been run from.*src.main.java")); } @TestTemplate @DisabledOnOs(OS.WINDOWS) void whenAToolchainIsConfiguredItIsUsedToRunTheApplication(MavenBuild mavenBuild) { - mavenBuild.project("run-toolchains").goals("verify", "-t", "toolchains.xml") - .execute((project) -> assertThat(buildLog(project)).contains("The Maven Toolchains is awesome!")); + mavenBuild.project("run-toolchains") + .goals("verify", "-t", "toolchains.xml") + .execute((project) -> assertThat(buildLog(project)).contains("The Maven Toolchains is awesome!")); } @TestTemplate void whenPomSpecifiesRunArgumentsContainingCommasTheyArePassedToTheApplicationCorrectly(MavenBuild mavenBuild) { - mavenBuild.project("run-arguments").goals("spring-boot:run").execute((project) -> assertThat(buildLog(project)) + mavenBuild.project("run-arguments") + .goals("spring-boot:run") + .execute((project) -> assertThat(buildLog(project)) .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info'")); } @TestTemplate void whenCommandLineSpecifiesRunArgumentsContainingCommasTheyArePassedToTheApplicationCorrectly( MavenBuild mavenBuild) { - mavenBuild.project("run-arguments-commandline").goals("spring-boot:run").systemProperty( - "spring-boot.run.arguments", - "--management.endpoints.web.exposure.include=prometheus,info,health,metrics --spring.profiles.active=foo,bar") - .execute((project) -> assertThat(buildLog(project)).contains( - "I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info,health,metrics'")); + mavenBuild.project("run-arguments-commandline") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.arguments", + "--management.endpoints.web.exposure.include=prometheus,info,health,metrics --spring.profiles.active=foo,bar") + .execute((project) -> assertThat(buildLog(project)) + .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info,health,metrics'")); } @TestTemplate void whenPomAndCommandLineSpecifyRunArgumentsThenPomOverrides(MavenBuild mavenBuild) { - mavenBuild.project("run-arguments").goals("spring-boot:run") - .systemProperty("spring-boot.run.arguments", - "--management.endpoints.web.exposure.include=one,two,three --spring.profiles.active=test") - .execute((project) -> assertThat(buildLog(project)) - .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info'")); + mavenBuild.project("run-arguments") + .goals("spring-boot:run") + .systemProperty("spring-boot.run.arguments", + "--management.endpoints.web.exposure.include=one,two,three --spring.profiles.active=test") + .execute((project) -> assertThat(buildLog(project)) + .contains("I haz been run with profile(s) 'foo,bar' and endpoint(s) 'prometheus,info'")); } private String buildLog(File project) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java index 1ccee63552..b79ce9da90 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/StartStopIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -34,14 +34,18 @@ class StartStopIntegrationTests { @TestTemplate void startStopWaitsForApplicationToBeReadyAndThenRequestsShutdown(MavenBuild mavenBuild) { - mavenBuild.project("start-stop").goals("verify").execute( - (project) -> assertThat(buildLog(project)).contains("isReady: true").contains("Shutdown requested")); + mavenBuild.project("start-stop") + .goals("verify") + .execute((project) -> assertThat(buildLog(project)).contains("isReady: true") + .contains("Shutdown requested")); } @TestTemplate void whenSkipIsTrueStartAndStopAreSkipped(MavenBuild mavenBuild) { - mavenBuild.project("start-stop-skip").goals("verify").execute((project) -> assertThat(buildLog(project)) - .doesNotContain("Ooops, I haz been run").doesNotContain("Stopping application")); + mavenBuild.project("start-stop-skip") + .goals("verify") + .execute((project) -> assertThat(buildLog(project)).doesNotContain("Ooops, I haz been run") + .doesNotContain("Stopping application")); } private String buildLog(File project) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java index 710b8ed543..b1fb9c19eb 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/WarIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,33 +51,34 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { @TestTemplate void warRepackaging(MavenBuild mavenBuild) { mavenBuild.project("war") - .execute((project) -> assertThat(jar(new File(project, "target/war-0.0.1.BUILD-SNAPSHOT.war"))) - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-core") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl") - .hasEntryWithNameStartingWith("WEB-INF/lib-provided/jakarta.servlet-api-6") - .hasEntryWithName("org/springframework/boot/loader/WarLauncher.class") - .hasEntryWithName("WEB-INF/classes/org/test/SampleApplication.class") - .hasEntryWithName("index.html") - .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.WarLauncher") - .hasStartClass("org.test.SampleApplication").hasAttribute("Not-Used", "Foo"))); + .execute((project) -> assertThat(jar(new File(project, "target/war-0.0.1.BUILD-SNAPSHOT.war"))) + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-core") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl") + .hasEntryWithNameStartingWith("WEB-INF/lib-provided/jakarta.servlet-api-6") + .hasEntryWithName("org/springframework/boot/loader/WarLauncher.class") + .hasEntryWithName("WEB-INF/classes/org/test/SampleApplication.class") + .hasEntryWithName("index.html") + .manifest((manifest) -> manifest.hasMainClass("org.springframework.boot.loader.WarLauncher") + .hasStartClass("org.test.SampleApplication") + .hasAttribute("Not-Used", "Foo"))); } @TestTemplate void jarDependencyWithCustomFinalNameBuiltInSameReactorIsPackagedUsingArtifactIdAndVersion(MavenBuild mavenBuild) { mavenBuild.project("war-reactor") - .execute(((project) -> assertThat(jar(new File(project, "war/target/war-0.0.1.BUILD-SNAPSHOT.war"))) - .hasEntryWithName("WEB-INF/lib/jar-0.0.1.BUILD-SNAPSHOT.jar") - .doesNotHaveEntryWithName("WEB-INF/lib/jar.jar"))); + .execute(((project) -> assertThat(jar(new File(project, "war/target/war-0.0.1.BUILD-SNAPSHOT.war"))) + .hasEntryWithName("WEB-INF/lib/jar-0.0.1.BUILD-SNAPSHOT.jar") + .doesNotHaveEntryWithName("WEB-INF/lib/jar.jar"))); } @TestTemplate void whenRequiresUnpackConfigurationIsProvidedItIsReflectedInTheRepackagedWar(MavenBuild mavenBuild) { - mavenBuild.project("war-with-unpack").execute( - (project) -> assertThat(jar(new File(project, "target/war-with-unpack-0.0.1.BUILD-SNAPSHOT.war"))) - .hasUnpackEntryWithNameStartingWith("WEB-INF/lib/spring-core-") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context-") - .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl-")); + mavenBuild.project("war-with-unpack") + .execute((project) -> assertThat(jar(new File(project, "target/war-with-unpack-0.0.1.BUILD-SNAPSHOT.war"))) + .hasUnpackEntryWithNameStartingWith("WEB-INF/lib/spring-core-") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-context-") + .hasEntryWithNameStartingWith("WEB-INF/lib/spring-jcl-")); } @TestTemplate @@ -97,8 +98,9 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(repackaged.lastModified()).isEqualTo(1584352800000L); try (JarFile jar = new JarFile(repackaged)) { List unreproducibleEntries = jar.stream() - .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) - .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()).toList(); + .filter((entry) -> entry.getLastModifiedTime().toMillis() != 1584352800000L) + .map((entry) -> entry.getName() + ": " + entry.getLastModifiedTime()) + .toList(); assertThat(unreproducibleEntries).isEmpty(); warHash.set(FileUtils.sha1Hash(repackaged)); FileSystemUtils.deleteRecursively(project); @@ -122,8 +124,9 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { // these libraries are contributed by Spring Boot repackaging, and // sorted separately "WEB-INF/lib/spring-boot-jarmode-layertools"); - assertThat(jar(repackaged)).entryNamesInPath("WEB-INF/lib/").zipSatisfy(sortedLibs, - (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); + assertThat(jar(repackaged)).entryNamesInPath("WEB-INF/lib/") + .zipSatisfy(sortedLibs, + (String jarLib, String expectedLib) -> assertThat(jarLib).startsWith(expectedLib)); }); } @@ -141,9 +144,10 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot").hasEntryWithNameStartingWith( - "WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith( + "WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getCoordinates().getArtifactId()); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("dependencies", "spring-boot-loader", @@ -154,9 +158,9 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { assertThat(layerIndex.get("application")).contains("WEB-INF/lib/jar-release-0.0.1.RELEASE.jar", "WEB-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar"); assertThat(dependenciesAndSnapshotDependencies) - .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib/spring-context")); + .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib/spring-context")); assertThat(layerIndex.get("dependencies")) - .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib-provided/")); + .anyMatch((dependency) -> dependency.startsWith("WEB-INF/lib-provided/")); } catch (IOException ex) { } @@ -168,10 +172,10 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered-disabled").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") - .doesNotHaveEntryWithName("WEB-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") + .doesNotHaveEntryWithName("WEB-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -180,10 +184,10 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered-no-layer-tools").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") - .hasEntryWithNameStartingWith("WEB-INF/layers.idx") - .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot") + .hasEntryWithNameStartingWith("WEB-INF/layers.idx") + .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/" + JarModeLibrary.LAYER_TOOLS.getName()); }); } @@ -192,17 +196,17 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-layered-custom").execute((project) -> { File repackaged = new File(project, "war/target/war-layered-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(repackaged)).hasEntryWithNameStartingWith("WEB-INF/classes/") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") - .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot"); + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-release") + .hasEntryWithNameStartingWith("WEB-INF/lib/jar-snapshot"); try (JarFile jarFile = new JarFile(repackaged)) { Map> layerIndex = readLayerIndex(jarFile); assertThat(layerIndex.keySet()).containsExactly("my-dependencies-name", "snapshot-dependencies", "configuration", "application"); assertThat(layerIndex.get("application")) - .contains("WEB-INF/lib/jar-release-0.0.1.RELEASE.jar", - "WEB-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", - "WEB-INF/lib/jar-classifier-0.0.1-bravo.jar") - .doesNotContain("WEB-INF/lib/jar-classifier-0.0.1-alpha.jar"); + .contains("WEB-INF/lib/jar-release-0.0.1.RELEASE.jar", + "WEB-INF/lib/jar-snapshot-0.0.1.BUILD-SNAPSHOT.jar", + "WEB-INF/lib/jar-classifier-0.0.1-bravo.jar") + .doesNotContain("WEB-INF/lib/jar-classifier-0.0.1-alpha.jar"); } }); } @@ -211,13 +215,13 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { void repackagedWarContainsClasspathIndex(MavenBuild mavenBuild) { mavenBuild.project("war").execute((project) -> { File repackaged = new File(project, "target/war-0.0.1.BUILD-SNAPSHOT.war"); - assertThat(jar(repackaged)).manifest( - (manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "WEB-INF/classpath.idx")); + assertThat(jar(repackaged)) + .manifest((manifest) -> manifest.hasAttribute("Spring-Boot-Classpath-Index", "WEB-INF/classpath.idx")); assertThat(jar(repackaged)).hasEntryWithName("WEB-INF/classpath.idx"); try (JarFile jarFile = new JarFile(repackaged)) { List index = readClasspathIndex(jarFile, "WEB-INF/classpath.idx"); - assertThat(index).allMatch( - (entry) -> entry.startsWith("WEB-INF/lib/") || entry.startsWith("WEB-INF/lib-provided/")); + assertThat(index) + .allMatch((entry) -> entry.startsWith("WEB-INF/lib/") || entry.startsWith("WEB-INF/lib-provided/")); } }); } @@ -227,7 +231,7 @@ class WarIntegrationTests extends AbstractArchiveIntegrationTests { mavenBuild.project("war-exclude-entry").execute((project) -> { File war = new File(project, "target/war-exclude-entry-0.0.1.BUILD-SNAPSHOT.war"); assertThat(jar(war)).hasEntryWithNameStartingWith("WEB-INF/lib/spring-context") - .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/spring-core"); + .doesNotHaveEntryWithNameStartingWith("WEB-INF/lib/spring-core"); }); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractAotMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractAotMojo.java index a128b8c978..89287a2985 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractAotMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractAotMojo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -113,9 +113,11 @@ public abstract class AbstractAotMojo extends AbstractDependencyFilterMojo { protected void generateAotAssets(URL[] classPath, String processorClassName, String... arguments) throws Exception { List command = CommandLineBuilder.forMainClass(processorClassName) - .withSystemProperties(this.systemPropertyVariables) - .withJvmArguments(new RunArguments(this.jvmArguments).asArray()).withClasspath(classPath) - .withArguments(arguments).build(); + .withSystemProperties(this.systemPropertyVariables) + .withJvmArguments(new RunArguments(this.jvmArguments).asArray()) + .withClasspath(classPath) + .withArguments(arguments) + .build(); if (getLog().isDebugEnabled()) { getLog().debug("Generating AOT assets using command: " + command); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java index 06647169f4..8cff9304f6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/AbstractRunMojo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -269,9 +269,10 @@ public abstract class AbstractRunMojo extends AbstractDependencyFilterMojo { protected RunArguments resolveJvmArguments() { StringBuilder stringBuilder = new StringBuilder(); if (this.systemPropertyVariables != null) { - stringBuilder.append(this.systemPropertyVariables.entrySet().stream() - .map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue())) - .collect(Collectors.joining(" "))); + stringBuilder.append(this.systemPropertyVariables.entrySet() + .stream() + .map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue())) + .collect(Collectors.joining(" "))); } if (this.jvmArguments != null) { stringBuilder.append(" ").append(this.jvmArguments); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CommandLineBuilder.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CommandLineBuilder.java index 0b98e90806..1fa1324650 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CommandLineBuilder.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CommandLineBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,10 @@ final class CommandLineBuilder { CommandLineBuilder withSystemProperties(Map systemProperties) { if (systemProperties != null) { - systemProperties.entrySet().stream().map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue())) - .forEach(this.options::add); + systemProperties.entrySet() + .stream() + .map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue())) + .forEach(this.options::add); } return this; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java index 14be4fdc2d..e78d817e34 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -130,13 +130,15 @@ class CustomLayersProvider { List excludes = getChildNodeTextContent(element, "exclude"); Element includeModuleDependencies = getChildElement(element, "includeModuleDependencies"); Element excludeModuleDependencies = getChildElement(element, "excludeModuleDependencies"); - List> includeFilters = includes.stream().map(filterFactory) - .collect(Collectors.toCollection(ArrayList::new)); + List> includeFilters = includes.stream() + .map(filterFactory) + .collect(Collectors.toCollection(ArrayList::new)); if (includeModuleDependencies != null) { includeFilters.add(Library::isLocal); } - List> excludeFilters = excludes.stream().map(filterFactory) - .collect(Collectors.toCollection(ArrayList::new)); + List> excludeFilters = excludes.stream() + .map(filterFactory) + .collect(Collectors.toCollection(ArrayList::new)); if (excludeModuleDependencies != null) { excludeFilters.add(Library::isLocal); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java index a05f3f8ada..05f29c1bee 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ import org.apache.maven.artifact.Artifact; class JarTypeFilter extends DependencyFilter { private static final Set EXCLUDED_JAR_TYPES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList("annotation-processor", "dependencies-starter"))); + .unmodifiableSet(new HashSet<>(Arrays.asList("annotation-processor", "dependencies-starter"))); JarTypeFilter() { super(Collections.emptyList()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java index 7e2b8d4756..822bff323a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/LoggingMainClassTimeoutWarningListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -37,8 +37,9 @@ class LoggingMainClassTimeoutWarningListener implements MainClassTimeoutWarningL @Override public void handleTimeoutWarning(long duration, String mainMethod) { - this.log.get().warn("Searching for the main-class is taking some time, " - + "consider using the mainClass configuration parameter"); + this.log.get() + .warn("Searching for the main-class is taking some time, " + + "consider using the mainClass configuration parameter"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ProcessTestAotMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ProcessTestAotMojo.java index 0d1a68d583..ea888c5992 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ProcessTestAotMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/ProcessTestAotMojo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -150,7 +150,7 @@ public class ProcessTestAotMojo extends AbstractAotMojo { this.generatedClasses }; URL[] classPath = getClassPath(directories); if (!includeJUnitPlatformLauncher || this.project.getArtifactMap() - .containsKey(JUNIT_PLATFORM_GROUP_ID + ":" + JUNIT_PLATFORM_LAUNCHER_ARTIFACT_ID)) { + .containsKey(JUNIT_PLATFORM_GROUP_ID + ":" + JUNIT_PLATFORM_LAUNCHER_ARTIFACT_ID)) { return classPath; } return addJUnitPlatformLauncher(classPath); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java index 7645fa338c..6c0579c721 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,9 +63,10 @@ public class RunMojo extends AbstractRunMojo { @Override protected void run(JavaProcessExecutor processExecutor, File workingDirectory, List args, Map environmentVariables) throws MojoExecutionException, MojoFailureException { - processExecutor.withRunProcessCustomizer( - (runProcess) -> Runtime.getRuntime().addShutdownHook(new Thread(new RunProcessKiller(runProcess)))) - .run(workingDirectory, args, environmentVariables); + processExecutor + .withRunProcessCustomizer( + (runProcess) -> Runtime.getRuntime().addShutdownHook(new Thread(new RunProcessKiller(runProcess)))) + .run(workingDirectory, args, environmentVariables); } private static final class RunProcessKiller implements Runnable { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java index 649708c587..744418aae6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/ArtifactsLibrariesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -143,11 +143,11 @@ class ArtifactsLibrariesTests { given(snapshotArtifact.getArtifactHandler()).willReturn(this.artifactHandler); this.artifacts = Collections.singleton(snapshotArtifact); new ArtifactsLibraries(this.artifacts, Collections.emptyList(), null, mock(Log.class)) - .doWithLibraries((library) -> { - assertThat(library.isIncluded()).isTrue(); - assertThat(library.isLocal()).isFalse(); - assertThat(library.getCoordinates().getVersion()).isEqualTo("1.0-SNAPSHOT"); - }); + .doWithLibraries((library) -> { + assertThat(library.isIncluded()).isTrue(); + assertThat(library.isLocal()).isFalse(); + assertThat(library.getCoordinates().getVersion()).isEqualTo("1.0-SNAPSHOT"); + }); } @Test @@ -162,7 +162,7 @@ class ArtifactsLibrariesTests { given(mavenProject.getArtifact()).willReturn(artifact); this.artifacts = Collections.singleton(artifact); new ArtifactsLibraries(this.artifacts, Collections.singleton(mavenProject), null, mock(Log.class)) - .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); + .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); } @Test @@ -179,7 +179,7 @@ class ArtifactsLibrariesTests { given(mavenProject.getAttachedArtifacts()).willReturn(Collections.singletonList(attachedArtifact)); this.artifacts = Collections.singleton(attachedArtifact); new ArtifactsLibraries(this.artifacts, Collections.singleton(mavenProject), null, mock(Log.class)) - .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); + .doWithLibraries((library) -> assertThat(library.isLocal()).isTrue()); } @Test @@ -194,7 +194,8 @@ class ArtifactsLibrariesTests { given(mavenProject.getArtifact()).willReturn(artifact); this.artifacts = Collections.singleton(artifact); new ArtifactsLibraries(this.artifacts, Collections.emptySet(), Collections.singleton(mavenProject), null, - mock(Log.class)).doWithLibraries((library) -> assertThat(library.isIncluded()).isFalse()); + mock(Log.class)) + .doWithLibraries((library) -> assertThat(library.isIncluded()).isFalse()); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CommandLineBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CommandLineBuilderTests.java index aa2430f47a..aedd17bd48 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CommandLineBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CommandLineBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,43 +36,44 @@ class CommandLineBuilderTests { @Test void buildWithNullJvmArgumentsIsIgnored() { assertThat(CommandLineBuilder.forMainClass(CLASS_NAME).withJvmArguments((String[]) null).build()) - .containsExactly(CLASS_NAME); + .containsExactly(CLASS_NAME); } @Test void buildWithNullIntermediateJvmArgumentIsIgnored() { - assertThat(CommandLineBuilder.forMainClass(CLASS_NAME).withJvmArguments("-verbose:class", null, "-verbose:gc") - .build()).containsExactly("-verbose:class", "-verbose:gc", CLASS_NAME); + assertThat(CommandLineBuilder.forMainClass(CLASS_NAME) + .withJvmArguments("-verbose:class", null, "-verbose:gc") + .build()).containsExactly("-verbose:class", "-verbose:gc", CLASS_NAME); } @Test void buildWithJvmArgument() { assertThat(CommandLineBuilder.forMainClass(CLASS_NAME).withJvmArguments("-verbose:class").build()) - .containsExactly("-verbose:class", CLASS_NAME); + .containsExactly("-verbose:class", CLASS_NAME); } @Test void buildWithNullSystemPropertyIsIgnored() { assertThat(CommandLineBuilder.forMainClass(CLASS_NAME).withSystemProperties(null).build()) - .containsExactly(CLASS_NAME); + .containsExactly(CLASS_NAME); } @Test void buildWithSystemProperty() { assertThat(CommandLineBuilder.forMainClass(CLASS_NAME).withSystemProperties(Map.of("flag", "enabled")).build()) - .containsExactly("-Dflag=\"enabled\"", CLASS_NAME); + .containsExactly("-Dflag=\"enabled\"", CLASS_NAME); } @Test void buildWithNullArgumentsIsIgnored() { assertThat(CommandLineBuilder.forMainClass(CLASS_NAME).withArguments((String[]) null).build()) - .containsExactly(CLASS_NAME); + .containsExactly(CLASS_NAME); } @Test void buildWithNullIntermediateArgumentIsIgnored() { assertThat(CommandLineBuilder.forMainClass(CLASS_NAME).withArguments("--test", null, "--another").build()) - .containsExactly(CLASS_NAME, "--test", "--another"); + .containsExactly(CLASS_NAME, "--test", "--another"); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java index e9fe181edd..8fafbcf875 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/CustomLayersProviderTests.java @@ -52,8 +52,9 @@ class CustomLayersProviderTests { @Test void getLayerResolverWhenDocumentValid() throws Exception { CustomLayers layers = this.customLayersProvider.getLayers(getDocument("layers.xml")); - assertThat(layers).extracting("name").containsExactly("my-deps", "my-dependencies-name", - "snapshot-dependencies", "my-resources", "configuration", "application"); + assertThat(layers).extracting("name") + .containsExactly("my-deps", "my-dependencies-name", "snapshot-dependencies", "my-resources", + "configuration", "application"); Library snapshot = mockLibrary("test-SNAPSHOT.jar", "org.foo", "1.0.0-SNAPSHOT"); Library groupId = mockLibrary("my-library", "com.acme", null); Library otherDependency = mockLibrary("other-library", "org.foo", null); @@ -81,7 +82,7 @@ class CustomLayersProviderTests { Library library = mockLibrary("my-library", "com.acme", null); assertThat(layers.getLayer(library)).hasToString("my-deps"); assertThatIllegalStateException().isThrownBy(() -> layers.getLayer("application.yml")) - .withMessageContaining("match any layer"); + .withMessageContaining("match any layer"); } @Test @@ -90,7 +91,7 @@ class CustomLayersProviderTests { Library library = mockLibrary("my-library", "com.acme", null); assertThat(layers.getLayer("application.yml")).hasToString("my-layer"); assertThatIllegalStateException().isThrownBy(() -> layers.getLayer(library)) - .withMessageContaining("match any layer"); + .withMessageContaining("match any layer"); } private Document getDocument(String resourceName) throws Exception { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java index 5a83b17b24..1fd381ee28 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/DockerTests.java @@ -41,8 +41,10 @@ class DockerTests { assertThat(dockerConfiguration.getHost()).isNull(); assertThat(dockerConfiguration.getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -59,8 +61,10 @@ class DockerTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isFalse(); assertThat(docker.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -78,8 +82,10 @@ class DockerTests { assertThat(dockerConfiguration.isBindHostToBuilder()).isTrue(); assertThat(docker.asDockerConfiguration().getBuilderRegistryAuthentication()).isNull(); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"\"").contains("\"password\" : \"\"").contains("\"email\" : \"\"") - .contains("\"serveraddress\" : \"\""); + .contains("\"username\" : \"\"") + .contains("\"password\" : \"\"") + .contains("\"email\" : \"\"") + .contains("\"serveraddress\" : \"\""); } @Test @@ -91,13 +97,15 @@ class DockerTests { new Docker.DockerRegistry("user2", "secret2", "https://docker2.example.com", "docker2@example.com")); DockerConfiguration dockerConfiguration = docker.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user1\"").contains("\"password\" : \"secret1\"") - .contains("\"email\" : \"docker1@example.com\"") - .contains("\"serveraddress\" : \"https://docker1.example.com\""); + .contains("\"username\" : \"user1\"") + .contains("\"password\" : \"secret1\"") + .contains("\"email\" : \"docker1@example.com\"") + .contains("\"serveraddress\" : \"https://docker1.example.com\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"username\" : \"user2\"").contains("\"password\" : \"secret2\"") - .contains("\"email\" : \"docker2@example.com\"") - .contains("\"serveraddress\" : \"https://docker2.example.com\""); + .contains("\"username\" : \"user2\"") + .contains("\"password\" : \"secret2\"") + .contains("\"email\" : \"docker2@example.com\"") + .contains("\"serveraddress\" : \"https://docker2.example.com\""); } @Test @@ -106,7 +114,7 @@ class DockerTests { docker.setBuilderRegistry( new Docker.DockerRegistry("user", null, "https://docker.example.com", "docker@example.com")); assertThatIllegalArgumentException().isThrownBy(docker::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } @Test @@ -115,7 +123,7 @@ class DockerTests { docker.setPublishRegistry( new Docker.DockerRegistry("user", null, "https://docker.example.com", "docker@example.com")); assertThatIllegalArgumentException().isThrownBy(docker::asDockerConfiguration) - .withMessageContaining("Invalid Docker publish registry configuration"); + .withMessageContaining("Invalid Docker publish registry configuration"); } @Test @@ -125,9 +133,9 @@ class DockerTests { docker.setPublishRegistry(new Docker.DockerRegistry("token2")); DockerConfiguration dockerConfiguration = docker.asDockerConfiguration(); assertThat(decoded(dockerConfiguration.getBuilderRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token1\""); + .contains("\"identitytoken\" : \"token1\""); assertThat(decoded(dockerConfiguration.getPublishRegistryAuthentication().getAuthHeader())) - .contains("\"identitytoken\" : \"token2\""); + .contains("\"identitytoken\" : \"token2\""); } @Test @@ -139,7 +147,7 @@ class DockerTests { Docker docker = new Docker(); docker.setBuilderRegistry(dockerRegistry); assertThatIllegalArgumentException().isThrownBy(docker::asDockerConfiguration) - .withMessageContaining("Invalid Docker builder registry configuration"); + .withMessageContaining("Invalid Docker builder registry configuration"); } String decoded(String value) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java index 3d371661bb..c3fd8b1806 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/test/java/org/springframework/boot/maven/JavaCompilerPluginConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -93,7 +93,7 @@ class JavaCompilerPluginConfigurationTests { private Xpp3Dom buildConfigurationDom(String... properties) throws IOException, XmlPullParserException { return Xpp3DomBuilder - .build(new StringReader("" + Arrays.toString(properties) + "")); + .build(new StringReader("" + Arrays.toString(properties) + "")); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java index a3f0883b46..0e42af8eb1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -77,7 +77,7 @@ class PropertiesMigrationListener implements ApplicationListener> getContent( Function> extractor) { - return this.content.entrySet().stream().filter((entry) -> !extractor.apply(entry.getValue()).isEmpty()).collect( - Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue())))); + return this.content.entrySet() + .stream() + .filter((entry) -> !extractor.apply(entry.getValue()).isEmpty()) + .collect( + Collectors.toMap(Map.Entry::getKey, (entry) -> new ArrayList<>(extractor.apply(entry.getValue())))); } private void append(StringBuilder report, Map> content) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java index 0c608d1939..8e495f8eb1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java @@ -80,8 +80,9 @@ class PropertiesMigrationReporter { private PropertySource mapPropertiesWithReplacement(PropertiesMigrationReport report, String name, List properties) { report.add(name, properties); - List renamed = properties.stream().filter(PropertyMigration::isCompatibleType) - .collect(Collectors.toList()); + List renamed = properties.stream() + .filter(PropertyMigration::isCompatibleType) + .collect(Collectors.toList()); if (renamed.isEmpty()) { return null; } @@ -103,8 +104,10 @@ class PropertiesMigrationReporter { private Map> getMatchingProperties( Predicate filter) { MultiValueMap result = new LinkedMultiValueMap<>(); - List candidates = this.allProperties.values().stream().filter(filter) - .collect(Collectors.toList()); + List candidates = this.allProperties.values() + .stream() + .filter(filter) + .collect(Collectors.toList()); getPropertySourcesAsMap().forEach((propertySourceName, propertySource) -> candidates.forEach((metadata) -> { ConfigurationPropertyName metadataName = ConfigurationPropertyName.isValid(metadata.getId()) ? ConfigurationPropertyName.of(metadata.getId()) @@ -118,12 +121,13 @@ class PropertiesMigrationReporter { // Prefix match for maps if (isMapType(metadata) && propertySource instanceof IterableConfigurationPropertySource) { IterableConfigurationPropertySource iterableSource = (IterableConfigurationPropertySource) propertySource; - iterableSource.stream().filter(metadataName::isAncestorOf).map(propertySource::getConfigurationProperty) - .forEach((property) -> { - ConfigurationMetadataProperty replacement = determineReplacementMetadata(metadata); - result.add(propertySourceName, - new PropertyMigration(property, metadata, replacement, true)); - }); + iterableSource.stream() + .filter(metadataName::isAncestorOf) + .map(propertySource::getConfigurationProperty) + .forEach((property) -> { + ConfigurationMetadataProperty replacement = determineReplacementMetadata(metadata); + result.add(propertySourceName, new PropertyMigration(property, metadata, replacement, true)); + }); } })); return result; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java index 5be2c95d11..9364679469 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertyMigration.java @@ -38,7 +38,7 @@ import org.springframework.util.StringUtils; class PropertyMigration { public static final Comparator COMPARATOR = Comparator - .comparing((property) -> property.getMetadata().getId()); + .comparing((property) -> property.getMetadata().getId()); private final ConfigurationProperty property; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java index 1de7023cbe..3e8dd69ef0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,9 +48,10 @@ class PropertiesMigrationListenerTests { @Test void sampleReport(CapturedOutput output) { this.context = createSampleApplication().run("--logging.file=test.log"); - assertThat(output).contains("commandLineArgs").contains("logging.file.name") - .contains("Each configuration key has been temporarily mapped") - .doesNotContain("Please refer to the release notes"); + assertThat(output).contains("commandLineArgs") + .contains("logging.file.name") + .contains("Each configuration key has been temporarily mapped") + .doesNotContain("Please refer to the release notes"); } private SpringApplication createSampleApplication() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java index 44382f77ca..b6e5135128 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-properties-migrator/src/test/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporterTests.java @@ -90,7 +90,7 @@ class PropertiesMigrationReporterTests { @Test void errorReport() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("test1", "config/config-warnings.properties")); + .addFirst(loadPropertySource("test1", "config/config-warnings.properties")); this.environment.getPropertySources().addFirst(loadPropertySource("test2", "config/config-error.properties")); String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); @@ -102,7 +102,7 @@ class PropertiesMigrationReporterTests { @Test void errorReportNoReplacement() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("first", "config/config-error-no-replacement.properties")); + .addFirst(loadPropertySource("first", "config/config-error-no-replacement.properties")); this.environment.getPropertySources().addFirst(loadPropertySource("second", "config/config-error.properties")); String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); @@ -134,7 +134,7 @@ class PropertiesMigrationReporterTests { @Test void reasonIsProvidedIfPropertyCouldNotBeRenamed() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("test", "config/config-error-no-compatible-type.properties")); + .addFirst(loadPropertySource("test", "config/config-error-no-compatible-type.properties")); String report = createErrorReport(loadRepository("metadata/type-conversion-metadata.json")); assertThat(report).isNotNull(); assertThat(report).containsSubsequence("Property source 'test'", "wrong.inconvertible", "Line: 1", @@ -144,7 +144,7 @@ class PropertiesMigrationReporterTests { @Test void invalidReplacementHandled() throws IOException { this.environment.getPropertySources() - .addFirst(loadPropertySource("first", "config/config-error-invalid-replacement.properties")); + .addFirst(loadPropertySource("first", "config/config-error-invalid-replacement.properties")); String report = createErrorReport(loadRepository("metadata/sample-metadata-invalid-replacement.json")); assertThat(report).isNotNull(); assertThat(report).containsSubsequence("Property source 'first'", "deprecated.six.test", "Line: 1", "Reason", @@ -155,7 +155,7 @@ class PropertiesMigrationReporterTests { @Test void invalidNameHandledGracefully() { this.environment.getPropertySources() - .addFirst(new MapPropertySource("first", Collections.singletonMap("invalid.property-name", "value"))); + .addFirst(new MapPropertySource("first", Collections.singletonMap("invalid.property-name", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata-invalid-name.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: invalid.propertyname").contains("Replacement: valid.property-name"); @@ -163,42 +163,46 @@ class PropertiesMigrationReporterTests { @Test void mapPropertiesDeprecatedNoReplacement() throws IOException { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.map-no-replacement.key", "value"))); + this.environment.getPropertySources() + .addFirst( + new MapPropertySource("first", Collections.singletonMap("custom.map-no-replacement.key", "value"))); String report = createErrorReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.map-no-replacement.key") - .contains("Reason: This is no longer supported."); + .contains("Reason: This is no longer supported."); } @Test void mapPropertiesDeprecatedWithReplacement() throws IOException { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.map-with-replacement.key", "value"))); + this.environment.getPropertySources() + .addFirst(new MapPropertySource("first", + Collections.singletonMap("custom.map-with-replacement.key", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.map-with-replacement.key") - .contains("Replacement: custom.the-map-replacement.key"); + .contains("Replacement: custom.the-map-replacement.key"); } @Test void mapPropertiesDeprecatedWithReplacementRelaxedBindingUnderscore() { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.map_with_replacement.key", "value"))); + this.environment.getPropertySources() + .addFirst(new MapPropertySource("first", + Collections.singletonMap("custom.map_with_replacement.key", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.mapwithreplacement.key") - .contains("Replacement: custom.the-map-replacement.key"); + .contains("Replacement: custom.the-map-replacement.key"); } @Test void mapPropertiesDeprecatedWithReplacementRelaxedBindingCamelCase() { - this.environment.getPropertySources().addFirst( - new MapPropertySource("first", Collections.singletonMap("custom.MapWithReplacement.key", "value"))); + this.environment.getPropertySources() + .addFirst( + new MapPropertySource("first", Collections.singletonMap("custom.MapWithReplacement.key", "value"))); String report = createWarningReport(loadRepository("metadata/sample-metadata.json")); assertThat(report).isNotNull(); assertThat(report).contains("Key: custom.mapwithreplacement.key") - .contains("Replacement: custom.the-map-replacement.key"); + .contains("Replacement: custom.the-map-replacement.key"); } private List mapToNames(PropertySources sources) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java index 995aca6cba..fdd5f0c915 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -96,7 +96,8 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { candidates.add(testMethod); candidates.addAll(getAnnotatedElements(arguments.toArray())); List annotatedElements = candidates.stream() - .filter(ModifiedClassPathClassLoader::hasAnnotation).collect(Collectors.toList()); + .filter(ModifiedClassPathClassLoader::hasAnnotation) + .collect(Collectors.toList()); if (annotatedElements.isEmpty()) { return null; } @@ -126,8 +127,8 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { private static ModifiedClassPathClassLoader compute(ClassLoader classLoader, List annotatedClasses) { List annotations = annotatedClasses.stream() - .map((source) -> MergedAnnotations.from(source, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY)) - .toList(); + .map((source) -> MergedAnnotations.from(source, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY)) + .toList(); return new ModifiedClassPathClassLoader(processUrls(extractUrls(classLoader), annotations), classLoader.getParent(), classLoader); } @@ -150,7 +151,7 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { return Stream.of(urlClassLoader.getURLs()); } return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(ModifiedClassPathClassLoader::toURL); + .map(ModifiedClassPathClassLoader::toURL); } private static URL toURL(String entry) { @@ -237,7 +238,8 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); RemoteRepository remoteRepository = new RemoteRepository.Builder("central", "default", - "https://repo.maven.apache.org/maven2").build(); + "https://repo.maven.apache.org/maven2") + .build(); session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); for (int i = 0; i < MAX_RESOLUTION_ATTEMPTS; i++) { CollectRequest collectRequest = new CollectRequest(null, Arrays.asList(remoteRepository)); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java index ddac249c72..bb4912acbd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -109,7 +109,8 @@ class ModifiedClassPathExtension implements InvocationInterceptor { private void runTest(String testId) throws Throwable { LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() - .selectors(DiscoverySelectors.selectUniqueId(testId)).build(); + .selectors(DiscoverySelectors.selectUniqueId(testId)) + .build(); Launcher launcher = LauncherFactory.create(); TestPlan testPlan = launcher.discover(request); SummaryGeneratingListener listener = new SummaryGeneratingListener(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java index 3968c0ba6a..855bcde7a0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/junit/DisabledOnOsCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class DisabledOnOsCondition implements ExecutionCondition { } } return ConditionEvaluationResult - .enabled(String.format("Enabled on OS = %s, architecture = %s", os, architecture)); + .enabled(String.format("Enabled on OS = %s, architecture = %s", os, architecture)); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java index e4687d793f..44e3473755 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/web/servlet/MockServletWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -87,9 +87,10 @@ public abstract class MockServletWebServer { return null; }).when(this.servletContext).setInitParameter(anyString(), anyString()); given(this.servletContext.getInitParameterNames()) - .willReturn(Collections.enumeration(initParameters.keySet())); - lenient().doAnswer((invocation) -> initParameters.get(invocation.getArgument(0))).when(this.servletContext) - .getInitParameter(anyString()); + .willReturn(Collections.enumeration(initParameters.keySet())); + lenient().doAnswer((invocation) -> initParameters.get(invocation.getArgument(0))) + .when(this.servletContext) + .getInitParameter(anyString()); given(this.servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); for (Initializer initializer : this.initializers) { initializer.onStartup(this.servletContext); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java index 76000a7182..74dea7879c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesParameterizedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class ModifiedClassPathExtensionOverridesParameterizedTests { @MethodSource("parameter") void classesAreLoadedFromParameter(Class type) { assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-context-4.1.0.RELEASE.jar"); + .endsWith("spring-context-4.1.0.RELEASE.jar"); } static Class[] parameter() { @@ -51,7 +51,7 @@ class ModifiedClassPathExtensionOverridesParameterizedTests { @MethodSource("arrayParameter") void classesAreLoadedFromParameterInArray(Object[] types) { assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-context-4.1.0.RELEASE.jar"); + .endsWith("spring-context-4.1.0.RELEASE.jar"); } static Stream arrayParameter() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java index b114a1b837..f188f7c965 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtensionOverridesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,13 +34,13 @@ class ModifiedClassPathExtensionOverridesTests { @Test void classesAreLoadedFromOverride() { assertThat(ApplicationContext.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-context-4.1.0.RELEASE.jar"); + .endsWith("spring-context-4.1.0.RELEASE.jar"); } @Test void classesAreLoadedFromTransitiveDependencyOfOverride() { assertThat(StringUtils.class.getProtectionDomain().getCodeSource().getLocation().toString()) - .endsWith("spring-core-4.1.0.RELEASE.jar"); + .endsWith("spring-core-4.1.0.RELEASE.jar"); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java index 62bdd48df4..ceecb07bc1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -262,7 +262,7 @@ class BeanDefinitionLoader { // Attempt to find a class in this package ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); Resource[] resources = resolver - .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); + .getResources(ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); for (Resource resource : resources) { String className = StringUtils.stripFilenameExtension(resource.getFilename()); load(Class.forName(source.toString() + "." + className)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java index 82ef359a8f..b983d03f41 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BootstrapRegistry.java @@ -164,6 +164,7 @@ public interface BootstrapRegistry { /** * The scope of an instance. + * * @since 2.4.2 */ enum Scope { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index fa81e685cf..2ebe1bd5a5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java @@ -276,13 +276,15 @@ public class SpringApplication { } private Class deduceMainApplicationClass() { - return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk(this::findMainClass) - .orElse(null); + return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE) + .walk(this::findMainClass) + .orElse(null); } private Optional> findMainClass(Stream stack) { - return stack.filter((frame) -> Objects.equals(frame.getMethodName(), "main")).findFirst() - .map(StackWalker.StackFrame::getDeclaringClass); + return stack.filter((frame) -> Objects.equals(frame.getMethodName(), "main")) + .findFirst() + .map(StackWalker.StackFrame::getDeclaringClass); } /** @@ -364,7 +366,7 @@ public class SpringApplication { private Class deduceEnvironmentClass() { Class environmentType = this.applicationContextFactory - .getEnvironmentType(this.webApplicationType); + .getEnvironmentType(this.webApplicationType); if (environmentType == null && this.applicationContextFactory != ApplicationContextFactory.DEFAULT) { environmentType = ApplicationContextFactory.DEFAULT.getEnvironmentType(this.webApplicationType); } @@ -506,8 +508,8 @@ public class SpringApplication { if (sources.contains(name)) { PropertySource source = sources.get(name); CompositePropertySource composite = new CompositePropertySource(name); - composite.addPropertySource( - new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); + composite + .addPropertySource(new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); composite.addPropertySource(source); sources.replace(name, composite); } @@ -572,8 +574,8 @@ public class SpringApplication { */ protected void postProcessApplicationContext(ConfigurableApplicationContext context) { if (this.beanNameGenerator != null) { - context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, - this.beanNameGenerator); + context.getBeanFactory() + .registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator); } if (this.resourceLoader != null) { if (context instanceof GenericApplicationContext genericApplicationContext) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationAotProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationAotProcessor.java index 32bd200ca7..6eec7ad6c2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationAotProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationAotProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,9 +68,13 @@ public class SpringApplicationAotProcessor extends ContextAotProcessor { Assert.isTrue(args.length >= requiredArgs, () -> "Usage: " + SpringApplicationAotProcessor.class.getName() + " "); Class application = Class.forName(args[0]); - Settings settings = Settings.builder().sourceOutput(Paths.get(args[1])).resourceOutput(Paths.get(args[2])) - .classOutput(Paths.get(args[3])).groupId((StringUtils.hasText(args[4])) ? args[4] : "unspecified") - .artifactId(args[5]).build(); + Settings settings = Settings.builder() + .sourceOutput(Paths.get(args[1])) + .resourceOutput(Paths.get(args[2])) + .classOutput(Paths.get(args[3])) + .groupId((StringUtils.hasText(args[4])) ? args[4] : "unspecified") + .artifactId(args[5]) + .build(); String[] applicationArgs = (args.length > requiredArgs) ? Arrays.copyOfRange(args, requiredArgs, args.length) : new String[0]; new SpringApplicationAotProcessor(application, settings, applicationArgs).process(); @@ -113,7 +117,7 @@ public class SpringApplicationAotProcessor extends ContextAotProcessor { } throw new IllegalStateException( "No application context available after calling main method of '%s'. Does it run a SpringApplication?" - .formatted(this.application.getName())); + .formatted(this.application.getName())); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java index e551800cad..805b3bf162 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -207,7 +207,7 @@ class SpringApplicationShutdownHook implements Runnable { ApplicationContext applicationContext = event.getApplicationContext(); SpringApplicationShutdownHook.this.contexts.remove(applicationContext); SpringApplicationShutdownHook.this.closedContexts - .add((ConfigurableApplicationContext) applicationContext); + .add((ConfigurableApplicationContext) applicationContext); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java index ad1ebf8aee..653e27cc10 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -194,8 +194,9 @@ public class SpringApplicationBuilder { child.sources(sources); // Copy environment stuff from parent to child - child.properties(this.defaultProperties).environment(this.environment) - .additionalProfiles(this.additionalProfiles); + child.properties(this.defaultProperties) + .environment(this.environment) + .additionalProfiles(this.additionalProfiles); child.parent = this; // It's not possible if embedded web server are enabled to support web contexts as @@ -221,7 +222,8 @@ public class SpringApplicationBuilder { public SpringApplicationBuilder parent(Class... sources) { if (this.parent == null) { this.parent = new SpringApplicationBuilder(sources).web(WebApplicationType.NONE) - .properties(this.defaultProperties).environment(this.environment); + .properties(this.defaultProperties) + .environment(this.environment); } else { this.parent.sources(sources); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java index 14d7c12f35..7bf6cbc03a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -108,7 +108,7 @@ public enum CloudPlatform { private boolean isAutoDetected(ConfigurableEnvironment environment) { PropertySource environmentPropertySource = environment.getPropertySources() - .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); if (environmentPropertySource != null) { if (environmentPropertySource.containsProperty(KUBERNETES_SERVICE_HOST) && environmentPropertySource.containsProperty(KUBERNETES_SERVICE_PORT)) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java index 26889c08c5..7ea589cbd8 100755 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ConfigurationWarningsApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -161,7 +161,7 @@ public class ConfigurationWarningsApplicationContextInitializer private void addComponentScanningPackages(Set packages, AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); + .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); if (attributes != null) { addPackages(packages, attributes.getStringArray("value")); addPackages(packages, attributes.getStringArray("basePackages")); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java index 522c1469bc..49031a6e0c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ import org.springframework.util.ClassUtils; public abstract class Configurations { private static final Comparator COMPARATOR = OrderComparator.INSTANCE - .thenComparing((other) -> other.getClass().getName()); + .thenComparing((other) -> other.getClass().getName()); private final Set> classes; @@ -120,8 +120,9 @@ public abstract class Configurations { List ordered = new ArrayList<>(configurations); ordered.sort(COMPARATOR); List collated = collate(ordered); - LinkedHashSet> classes = collated.stream().flatMap(Configurations::streamClasses) - .collect(Collectors.toCollection(LinkedHashSet::new)); + LinkedHashSet> classes = collated.stream() + .flatMap(Configurations::streamClasses) + .collect(Collectors.toCollection(LinkedHashSet::new)); return ClassUtils.toClassArray(classes); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java index 931f021bbe..f17855aaad 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/AnsiOutputApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,9 @@ public class AnsiOutputApplicationListener @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); - Binder.get(environment).bind("spring.output.ansi.enabled", AnsiOutput.Enabled.class) - .ifBound(AnsiOutput::setEnabled); + Binder.get(environment) + .bind("spring.output.ansi.enabled", AnsiOutput.Enabled.class) + .ifBound(AnsiOutput::setEnabled); AnsiOutput.setConsoleAvailable(environment.getProperty("spring.output.ansi.console-available", Boolean.class)); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java index 932b123296..15c556e703 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java @@ -96,7 +96,7 @@ class ConfigDataEnvironment { private static final ConfigDataLocation[] EMPTY_LOCATIONS = new ConfigDataLocation[0]; private static final Bindable CONFIG_DATA_LOCATION_ARRAY = Bindable - .of(ConfigDataLocation[].class); + .of(ConfigDataLocation[].class); private static final Bindable> STRING_LIST = Bindable.listOf(String.class); @@ -142,7 +142,7 @@ class ConfigDataEnvironment { this.logFactory = logFactory; this.logger = logFactory.getLog(getClass()); this.notFoundAction = binder.bind(ON_NOT_FOUND_PROPERTY, ConfigDataNotFoundAction.class) - .orElse(ConfigDataNotFoundAction.FAIL); + .orElse(ConfigDataNotFoundAction.FAIL); this.bootstrapContext = bootstrapContext; this.environment = environment; this.resolvers = createConfigDataLocationResolvers(logFactory, bootstrapContext, binder, resourceLoader); @@ -317,8 +317,9 @@ class ConfigDataEnvironment { private void registerBootstrapBinder(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext, BinderOption... binderOptions) { - this.bootstrapContext.register(Binder.class, InstanceSupplier - .from(() -> contributors.getBinder(activationContext, binderOptions)).withScope(Scope.PROTOTYPE)); + this.bootstrapContext.register(Binder.class, + InstanceSupplier.from(() -> contributors.getBinder(activationContext, binderOptions)) + .withScope(Scope.PROTOTYPE)); } private void applyToEnvironment(ConfigDataEnvironmentContributors contributors, @@ -344,12 +345,12 @@ class ConfigDataEnvironment { PropertySource propertySource = contributor.getPropertySource(); if (contributor.getKind() == ConfigDataEnvironmentContributor.Kind.BOUND_IMPORT && propertySource != null) { if (!contributor.isActive(activationContext)) { - this.logger.trace( - LogMessage.format("Skipping inactive property source '%s'", propertySource.getName())); + this.logger + .trace(LogMessage.format("Skipping inactive property source '%s'", propertySource.getName())); } else { this.logger - .trace(LogMessage.format("Adding imported property source '%s'", propertySource.getName())); + .trace(LogMessage.format("Adding imported property source '%s'", propertySource.getName())); propertySources.addLast(propertySource); this.environmentUpdateListener.onPropertySourceAdded(propertySource, contributor.getLocation(), contributor.getResource()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java index 75f356050e..4311c48e05 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ import org.springframework.util.CollectionUtils; class ConfigDataEnvironmentContributor implements Iterable { private static final ConfigData.Options EMPTY_LOCATION_OPTIONS = ConfigData.Options - .of(ConfigData.Option.IGNORE_IMPORTS); + .of(ConfigData.Option.IGNORE_IMPORTS); private final ConfigDataLocation location; @@ -304,8 +304,9 @@ class ConfigDataEnvironmentContributor implements Iterable child.hasConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC))) { + if (contributor.getChildren(importPhase) + .stream() + .anyMatch((child) -> child.hasConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC))) { return true; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java index 79fffde312..c7a26a98fd 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -88,7 +88,7 @@ class ConfigDataEnvironmentContributorPlaceholdersResolver implements Placeholde return contributor.isActive(this.activationContext); } return contributor.withBoundProperties(this.contributors, this.activationContext) - .isActive(this.activationContext); + .isActive(this.activationContext); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java index 7085d0c977..b9c9b0ca29 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -220,8 +220,11 @@ class ConfigDataEnvironmentContributors implements Iterable getBinderSources(Predicate filter) { - return this.root.stream().filter(this::hasConfigurationPropertySource).filter(filter) - .map(ConfigDataEnvironmentContributor::getConfigurationPropertySource).iterator(); + return this.root.stream() + .filter(this::hasConfigurationPropertySource) + .filter(filter) + .map(ConfigDataEnvironmentContributor::getConfigurationPropertySource) + .iterator(); } private boolean hasConfigurationPropertySource(ConfigDataEnvironmentContributor contributor) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java index a6b89d9ae2..76628b1973 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationBindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,9 @@ class ConfigDataLocationBindHandler extends AbstractBindHandler { return withOrigin(context, location); } if (result instanceof List) { - List list = ((List) result).stream().filter(Objects::nonNull) - .collect(Collectors.toCollection(ArrayList::new)); + List list = ((List) result).stream() + .filter(Objects::nonNull) + .collect(Collectors.toCollection(ArrayList::new)); for (int i = 0; i < list.size(); i++) { Object element = list.get(i); if (element instanceof ConfigDataLocation location) { @@ -56,8 +57,9 @@ class ConfigDataLocationBindHandler extends AbstractBindHandler { return list; } if (result instanceof ConfigDataLocation[] unfilteredLocations) { - ConfigDataLocation[] locations = Arrays.stream(unfilteredLocations).filter(Objects::nonNull) - .toArray(ConfigDataLocation[]::new); + ConfigDataLocation[] locations = Arrays.stream(unfilteredLocations) + .filter(Objects::nonNull) + .toArray(ConfigDataLocation[]::new); for (int i = 0; i < locations.length; i++) { locations[i] = withOrigin(context, locations[i]); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHints.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHints.java index 80fe18d803..a3920df086 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHints.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -90,7 +90,7 @@ class ConfigDataLocationRuntimeHints implements RuntimeHintsRegistrar { protected List getExtensions(ClassLoader classLoader) { List extensions = new ArrayList<>(); List propertySourceLoaders = getSpringFactoriesLoader(classLoader) - .load(PropertySourceLoader.class); + .load(PropertySourceLoader.class); for (PropertySourceLoader propertySourceLoader : propertySourceLoaders) { for (String fileExtension : propertySourceLoader.getFileExtensions()) { String candidate = "." + fileExtension; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataPropertiesRuntimeHints.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataPropertiesRuntimeHints.java index 5a54442a9a..71b90cfb28 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataPropertiesRuntimeHints.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataPropertiesRuntimeHints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -32,8 +32,9 @@ class ConfigDataPropertiesRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { BindableRuntimeHintsRegistrar.forTypes(ConfigDataProperties.class).registerHints(hints); - hints.reflection().registerMethod(ReflectionUtils.findMethod(ConfigDataLocation.class, "of", String.class), - ExecutableMode.INVOKE); + hints.reflection() + .registerMethod(ReflectionUtils.findMethod(ConfigDataLocation.class, "of", String.class), + ExecutableMode.INVOKE); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java index ef22da174a..27cfd9fc79 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -57,10 +57,10 @@ public class Profiles implements Iterable { public static final String INCLUDE_PROFILES_PROPERTY_NAME = "spring.profiles.include"; static final ConfigurationPropertyName INCLUDE_PROFILES = ConfigurationPropertyName - .of(Profiles.INCLUDE_PROFILES_PROPERTY_NAME); + .of(Profiles.INCLUDE_PROFILES_PROPERTY_NAME); private static final Bindable> STRING_STRINGS_MAP = Bindable - .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class)); + .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class)); private static final Bindable> STRING_SET = Bindable.setOf(String.class); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java index 89e623b714..e5f9db7c44 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -287,9 +287,10 @@ public class StandardConfigDataLocationResolver String message = String.format("Config data location '%s' contains no subdirectories", location); throw new ConfigDataLocationNotFoundException(location, message, null); } - return Arrays.stream(subdirectories).filter(Resource::exists) - .map((resource) -> new StandardConfigDataResource(reference, resource, true)) - .collect(Collectors.toCollection(LinkedHashSet::new)); + return Arrays.stream(subdirectories) + .filter(Resource::exists) + .map((resource) -> new StandardConfigDataResource(reference, resource, true)) + .collect(Collectors.toCollection(LinkedHashSet::new)); } private List resolve(StandardConfigDataReference reference) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java index ba1e7dc50c..16027ecabd 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -101,7 +101,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { LogLevel.class); private static final Bindable>> STRING_STRINGS_MAP = Bindable - .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class).asMap()); + .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class).asMap()); /** * The default order for the LoggingApplicationListener. @@ -378,7 +378,7 @@ public class LoggingApplicationListener implements GenericApplicationListener { protected void initializeSpringBootLogging(LoggingSystem system, LogLevel springBootLogging) { BiConsumer configurer = getLogLevelConfigurer(system); SPRING_BOOT_LOGGING_LOGGERS.getOrDefault(springBootLogging, Collections.emptyList()) - .forEach((name) -> configureLogLevel(name, springBootLogging, configurer)); + .forEach((name) -> configureLogLevel(name, springBootLogging, configurer)); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java index c8616d08d1..a41f8e43d8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/BoundConfigurationProperties.java @@ -82,7 +82,7 @@ public class BoundConfigurationProperties { Assert.notNull(registry, "Registry must not be null"); if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder.genericBeanDefinition(BoundConfigurationProperties.class) - .getBeanDefinition(); + .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_NAME, definition); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java index a4ee220fb8..d3396f7c4f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java @@ -307,7 +307,7 @@ public final class ConfigurationPropertiesBean { } if (!annotation.isPresent() && AopUtils.isAopProxy(instance)) { annotation = MergedAnnotations.from(AopUtils.getTargetClass(instance), SearchStrategy.TYPE_HIERARCHY) - .get(annotationType); + .get(annotationType); } return annotation.isPresent() ? annotation.synthesize() : null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java index 2988233dc2..875d5ae37f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,8 @@ final class ConfigurationPropertiesBeanRegistrar { void register(Class type) { MergedAnnotation annotation = MergedAnnotations - .from(type, SearchStrategy.TYPE_HIERARCHY).get(ConfigurationProperties.class); + .from(type, SearchStrategy.TYPE_HIERARCHY) + .get(ConfigurationProperties.class); register(type, annotation); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessor.java index ca4177ea0f..b0392723cf 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,7 +64,7 @@ class ConfigurationPropertiesBeanRegistrationAotProcessor implements BeanRegistr extends BeanRegistrationCodeFragmentsDecorator { private static final Predicate INCLUDE_BIND_METHOD_ATTRIBUTE_FILTER = (name) -> name - .equals(BindMethod.class.getName()); + .equals(BindMethod.class.getName()); private static final String REGISTERED_BEAN_PARAMETER_NAME = "registeredBean"; @@ -91,13 +91,14 @@ class ConfigurationPropertiesBeanRegistrationAotProcessor implements BeanRegistr GeneratedMethod generatedMethod = beanRegistrationCode.getMethods().add("getInstance", (method) -> { Class beanClass = this.registeredBean.getBeanClass(); method.addJavadoc("Get the bean instance for '$L'.", this.registeredBean.getBeanName()) - .addModifiers(Modifier.PRIVATE, Modifier.STATIC).returns(beanClass) - .addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER_NAME) - .addStatement("$T beanFactory = registeredBean.getBeanFactory()", BeanFactory.class) - .addStatement("$T beanName = registeredBean.getBeanName()", String.class) - .addStatement("$T beanClass = registeredBean.getBeanClass()", Class.class) - .addStatement("return ($T) $T.from(beanFactory, beanName, beanClass)", beanClass, - ConstructorBound.class); + .addModifiers(Modifier.PRIVATE, Modifier.STATIC) + .returns(beanClass) + .addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER_NAME) + .addStatement("$T beanFactory = registeredBean.getBeanFactory()", BeanFactory.class) + .addStatement("$T beanName = registeredBean.getBeanName()", String.class) + .addStatement("$T beanClass = registeredBean.getBeanClass()", Class.class) + .addStatement("return ($T) $T.from(beanFactory, beanName, beanClass)", beanClass, + ConstructorBound.class); }); return CodeBlock.of("$T.of($T::$L)", InstanceSupplier.class, beanRegistrationCode.getClassName(), generatedMethod.getName()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java index 4f730235e3..86b60f7c4e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java @@ -156,8 +156,9 @@ class ConfigurationPropertiesBinder { } private List getBindHandlerAdvisors() { - return this.applicationContext.getBeanProvider(ConfigurationPropertiesBindHandlerAdvisor.class).orderedStream() - .toList(); + return this.applicationContext.getBeanProvider(ConfigurationPropertiesBindHandlerAdvisor.class) + .orderedStream() + .toList(); } private Binder getBinder() { @@ -190,7 +191,8 @@ class ConfigurationPropertiesBinder { static void register(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(ConfigurationPropertiesBinderFactory.class).getBeanDefinition(); + .rootBeanDefinition(ConfigurationPropertiesBinderFactory.class) + .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(ConfigurationPropertiesBinder.BEAN_NAME, definition); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java index 9c27808ff1..3134b2d218 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java @@ -83,7 +83,7 @@ public class ConfigurationPropertiesBindingPostProcessor private boolean hasBoundValueObject(String beanName) { return this.registry.containsBeanDefinition(beanName) && BindMethod.VALUE_OBJECT - .equals(this.registry.getBeanDefinition(beanName).getAttribute(BindMethod.class.getName())); + .equals(this.registry.getBeanDefinition(beanName).getAttribute(BindMethod.class.getName())); } private void bind(ConfigurationPropertiesBean bean) { @@ -110,7 +110,8 @@ public class ConfigurationPropertiesBindingPostProcessor Assert.notNull(registry, "Registry must not be null"); if (!registry.containsBeanDefinition(BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class).getBeanDefinition(); + .rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class) + .getBeanDefinition(); definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN_NAME, definition); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java index 56bb818571..7563db4731 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrar.java @@ -64,7 +64,7 @@ class ConfigurationPropertiesScanRegistrar implements ImportBeanDefinitionRegist private Set getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ConfigurationPropertiesScan.class.getName())); + .fromMap(metadata.getAnnotationAttributes(ConfigurationPropertiesScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java index 9fb9b5b3af..3593faf423 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class ConversionServiceDeducer { List getConversionServices() { if (hasUserDefinedConfigurationServiceBean()) { return Collections.singletonList(this.applicationContext - .getBean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); + .getBean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } if (this.applicationContext instanceof ConfigurableApplicationContext configurableContext) { return getConversionServices(configurableContext); @@ -74,7 +74,7 @@ class ConversionServiceDeducer { private boolean hasUserDefinedConfigurationServiceBean() { String beanName = ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME; return this.applicationContext.containsBean(beanName) && this.applicationContext.getAutowireCapableBeanFactory() - .isTypeMatch(beanName, ConversionService.class); + .isTypeMatch(beanName, ConversionService.class); } private static class ConverterBeans { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java index cd9c18058e..2a0fc229f6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ import org.springframework.core.type.AnnotationMetadata; class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegistrar { private static final String METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME = Conventions - .getQualifiedAttributeName(EnableConfigurationPropertiesRegistrar.class, "methodValidationExcludeFilter"); + .getQualifiedAttributeName(EnableConfigurationPropertiesRegistrar.class, "methodValidationExcludeFilter"); @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { @@ -50,9 +50,11 @@ class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegi } private Set> getTypes(AnnotationMetadata metadata) { - return metadata.getAnnotations().stream(EnableConfigurationProperties.class) - .flatMap((annotation) -> Arrays.stream(annotation.getClassArray(MergedAnnotation.VALUE))) - .filter((type) -> void.class != type).collect(Collectors.toSet()); + return metadata.getAnnotations() + .stream(EnableConfigurationProperties.class) + .flatMap((annotation) -> Arrays.stream(annotation.getClassArray(MergedAnnotation.VALUE))) + .filter((type) -> void.class != type) + .collect(Collectors.toSet()); } static void registerInfrastructureBeans(BeanDefinitionRegistry registry) { @@ -63,9 +65,10 @@ class EnableConfigurationPropertiesRegistrar implements ImportBeanDefinitionRegi static void registerMethodValidationExcludeFilter(BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME)) { BeanDefinition definition = BeanDefinitionBuilder - .rootBeanDefinition(MethodValidationExcludeFilter.class, "byAnnotation") - .addConstructorArgValue(ConfigurationProperties.class).setRole(BeanDefinition.ROLE_INFRASTRUCTURE) - .getBeanDefinition(); + .rootBeanDefinition(MethodValidationExcludeFilter.class, "byAnnotation") + .addConstructorArgValue(ConfigurationProperties.class) + .setRole(BeanDefinition.ROLE_INFRASTRUCTURE) + .getBeanDefinition(); registry.registerBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME, definition); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java index 914496efca..5769f61c6e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzer.java @@ -64,7 +64,7 @@ class NotConstructorBoundInjectionFailureAnalyzer if (injectionPoint != null && injectionPoint.getMember() instanceof Constructor constructor) { Class declaringClass = constructor.getDeclaringClass(); MergedAnnotation configurationProperties = MergedAnnotations.from(declaringClass) - .get(ConfigurationProperties.class); + .get(ConfigurationProperties.class); return configurationProperties.isPresent() && BindMethod.get(constructor.getDeclaringClass()) == BindMethod.VALUE_OBJECT; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java index bc97bfe1d7..8570a149d5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class PropertySourcesDeducer { private PropertySourcesPlaceholderConfigurer getSinglePropertySourcesPlaceholderConfigurer() { // Take care not to cause early instantiation of all FactoryBeans Map beans = this.applicationContext - .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false); + .getBeansOfType(PropertySourcesPlaceholderConfigurer.class, false, false); if (beans.size() == 1) { return beans.values().iterator().next(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java index 96c88a864f..3734469d1f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -175,8 +175,10 @@ public class BindableRuntimeHintsRegistrar implements RuntimeHintsRegistrar { } return; } - Arrays.stream(this.type.getDeclaredConstructors()).filter(this::hasNoParameters).findFirst() - .ifPresent((constructor) -> hints.registerConstructor(constructor, ExecutableMode.INVOKE)); + Arrays.stream(this.type.getDeclaredConstructors()) + .filter(this::hasNoParameters) + .findFirst() + .ifPresent((constructor) -> hints.registerConstructor(constructor, ExecutableMode.INVOKE)); } private void verifyParameterNamesAreAvailable() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java index eb3c9c34f3..ffbf3df7b4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ import org.springframework.util.Assert; public class Binder { private static final Set> NON_BEAN_CLASSES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(Object.class, Class.class))); + .unmodifiableSet(new HashSet<>(Arrays.asList(Object.class, Class.class))); private final Iterable sources; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProvider.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProvider.java index d5bf68a783..85cbec9d3e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProvider.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProvider.java @@ -111,8 +111,9 @@ class DefaultBindConstructorProvider implements BindConstructorProvider { } private static boolean isAutowiredPresent(Class type) { - if (Stream.of(type.getDeclaredConstructors()).map(MergedAnnotations::from) - .anyMatch((annotations) -> annotations.isPresent(Autowired.class))) { + if (Stream.of(type.getDeclaredConstructors()) + .map(MergedAnnotations::from) + .anyMatch((annotations) -> annotations.isPresent(Autowired.class))) { return true; } Class userClass = ClassUtils.getUserClass(type); @@ -124,7 +125,8 @@ class DefaultBindConstructorProvider implements BindConstructorProvider { return new Constructor[0]; } return Arrays.stream(type.getDeclaredConstructors()) - .filter((constructor) -> isNonSynthetic(constructor, type)).toArray(Constructor[]::new); + .filter((constructor) -> isNonSynthetic(constructor, type)) + .toArray(Constructor[]::new); } private static boolean isInnerClass(Class type) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java index cbf2668856..fa7704959d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -132,8 +132,11 @@ abstract class IndexedElementsBinder extends AggregateBinder { private void assertNoUnboundChildren(ConfigurationPropertySource source, MultiValueMap children) { if (!children.isEmpty()) { - throw new UnboundConfigurationPropertiesException(children.values().stream().flatMap(List::stream) - .map(source::getConfigurationProperty).collect(Collectors.toCollection(TreeSet::new))); + throw new UnboundConfigurationPropertiesException(children.values() + .stream() + .flatMap(List::stream) + .map(source::getConfigurationProperty) + .collect(Collectors.toCollection(TreeSet::new))); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java index 1b30b96829..3f1eaf61f8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class MapBinder extends AggregateBinder> { protected Object bindAggregate(ConfigurationPropertyName name, Bindable target, AggregateElementBinder elementBinder) { Map map = CollectionFactory - .createMap((target.getValue() != null) ? Map.class : target.getType().resolve(Object.class), 0); + .createMap((target.getValue() != null) ? Map.class : target.getType().resolve(Object.class), 0); Bindable resolvedTarget = resolveTarget(target); boolean hasDescendants = hasDescendants(name); for (ConfigurationPropertySource source : getContext().getSources()) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java index adec2a071a..7a68330b7b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -222,7 +222,7 @@ class ValueObjectBinder implements DataObjectBinder { for (KParameter parameter : parameters) { String name = getParameterName(parameter); ResolvableType parameterType = ResolvableType - .forType(ReflectJvmMapping.getJavaType(parameter.getType()), type); + .forType(ReflectJvmMapping.getJavaType(parameter.getType()), type); Annotation[] annotations = parameter.getAnnotations().toArray(ANNOTATION_ARRAY); result.add(new ConstructorParameter(name, parameterType, annotations)); } @@ -231,7 +231,9 @@ class ValueObjectBinder implements DataObjectBinder { private String getParameterName(KParameter parameter) { return MergedAnnotations.from(parameter, parameter.getAnnotations().toArray(ANNOTATION_ARRAY)) - .get(Name.class).getValue(MergedAnnotation.VALUE, String.class).orElseGet(parameter::getName); + .get(Name.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElseGet(parameter::getName); } @Override @@ -271,8 +273,10 @@ class ValueObjectBinder implements DataObjectBinder { Parameter[] parameters = constructor.getParameters(); List result = new ArrayList<>(parameters.length); for (int i = 0; i < parameters.length; i++) { - String name = MergedAnnotations.from(parameters[i]).get(Name.class) - .getValue(MergedAnnotation.VALUE, String.class).orElse(names[i]); + String name = MergedAnnotations.from(parameters[i]) + .get(Name.class) + .getValue(MergedAnnotation.VALUE, String.class) + .orElse(names[i]); ResolvableType parameterType = ResolvableType.forMethodParameter(new MethodParameter(constructor, i), type); Annotation[] annotations = parameters[i].getDeclaredAnnotations(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java index 4789e9434a..26224addd9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -236,8 +236,8 @@ public class ValidationBindHandler extends AbstractBindHandler { ValidationErrors getValidationErrors() { Set boundProperties = ValidationBindHandler.this.boundProperties.stream() - .filter((property) -> this.name.isAncestorOf(property.getName())) - .collect(Collectors.toCollection(LinkedHashSet::new)); + .filter((property) -> this.name.isAncestorOf(property.getName())) + .collect(Collectors.toCollection(LinkedHashSet::new)); return new ValidationErrors(this.name, boundProperties, getAllErrors()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java index 94dcd536a8..27f4948e1a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationProperty.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -111,8 +111,10 @@ public final class ConfigurationProperty implements OriginProvider, Comparable e.getValue().contains(alias)).map(Map.Entry::getKey) - .findFirst().orElse(null); + return this.aliases.entrySet() + .stream() + .filter((e) -> e.getValue().contains(alias)) + .map(Map.Entry::getKey) + .findFirst() + .orElse(null); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java index 0f1501729a..dac0b10513 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -117,7 +117,7 @@ public final class ConfigurationPropertySources { Assert.isInstanceOf(ConfigurableEnvironment.class, environment); MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources(); ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) sources - .get(ATTACHED_PROPERTY_SOURCE_NAME); + .get(ATTACHED_PROPERTY_SOURCE_NAME); if (attached == null) { return from(sources); } @@ -153,8 +153,9 @@ public final class ConfigurationPropertySources { } private static Stream> streamPropertySources(PropertySources sources) { - return sources.stream().flatMap(ConfigurationPropertySources::flatten) - .filter(ConfigurationPropertySources::isIncluded); + return sources.stream() + .flatMap(ConfigurationPropertySources::flatten) + .filter(ConfigurationPropertySources::isIncluded); } private static Stream> flatten(PropertySource source) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java index 73f491684c..f11fc89dc7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -99,7 +99,7 @@ class ConfigurationPropertySourcesPropertyResolver extends AbstractPropertyResol private ConfigurationPropertySourcesPropertySource getAttached() { ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) ConfigurationPropertySources - .getAttached(this.propertySources); + .getAttached(this.propertySources); Iterable attachedSource = (attached != null) ? attached.getSource() : null; if ((attachedSource instanceof SpringConfigurationPropertySources springSource) && springSource.isUsingSources(this.propertySources)) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java index 97f96cf4b1..3509489087 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -98,8 +98,11 @@ public class MutuallyExclusiveConfigurationPropertiesException extends RuntimeEx public static void throwIfMultipleNonNullValuesIn(Consumer> entries) { Map map = new LinkedHashMap<>(); entries.accept(map); - Set configuredNames = map.entrySet().stream().filter((entry) -> entry.getValue() != null) - .map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new)); + Set configuredNames = map.entrySet() + .stream() + .filter((entry) -> entry.getValue() != null) + .map(Map.Entry::getKey) + .collect(Collectors.toCollection(LinkedHashSet::new)); if (configuredNames.size() > 1) { throw new MutuallyExclusiveConfigurationPropertiesException(configuredNames, map.keySet()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java index deb3a22223..280b1d81bc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope private BiPredicate getAncestorOfCheck( PropertyMapper[] mappers) { BiPredicate ancestorOfCheck = mappers[0] - .getAncestorOfCheck(); + .getAncestorOfCheck(); for (int i = 1; i < mappers.length; i++) { ancestorOfCheck = ancestorOfCheck.or(mappers[i].getAncestorOfCheck()); } @@ -147,7 +147,7 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope ConfigurationPropertyName[] configurationPropertyNames = this.configurationPropertyNames; if (configurationPropertyNames == null) { configurationPropertyNames = getMappings() - .getConfigurationPropertyNames(getPropertySource().getPropertyNames()); + .getConfigurationPropertyNames(getPropertySource().getPropertyNames()); this.configurationPropertyNames = configurationPropertyNames; } return configurationPropertyNames; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java index dcc8b705ae..754a7c328a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/UnboundElementsSourceFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,8 +37,8 @@ import org.springframework.core.env.StandardEnvironment; public class UnboundElementsSourceFilter implements Function { private static final Set BENIGN_PROPERTY_SOURCE_NAMES = Collections - .unmodifiableSet(new HashSet<>(Arrays.asList(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); + .unmodifiableSet(new HashSet<>(Arrays.asList(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME))); @Override public Boolean apply(ConfigurationPropertySource configurationPropertySource) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java index 66bb03612a..0346fd8ea2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CollectionToDelimitedStringConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -66,8 +66,9 @@ final class CollectionToDelimitedStringConverter implements ConditionalGenericCo if (source.isEmpty()) { return ""; } - return source.stream().map((element) -> convertElement(element, sourceType, targetType)) - .collect(Collectors.joining(getDelimiter(sourceType))); + return source.stream() + .map((element) -> convertElement(element, sourceType, targetType)) + .collect(Collectors.joining(getDelimiter(sourceType))); } private CharSequence getDelimiter(TypeDescriptor sourceType) { @@ -76,8 +77,8 @@ final class CollectionToDelimitedStringConverter implements ConditionalGenericCo } private String convertElement(Object element, TypeDescriptor sourceType, TypeDescriptor targetType) { - return String.valueOf( - this.conversionService.convert(element, sourceType.elementTypeDescriptor(element), targetType)); + return String + .valueOf(this.conversionService.convert(element, sourceType.elementTypeDescriptor(element), targetType)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java index 65102a619e..61833f0c97 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ public enum DurationStyle { Assert.state(matcher.matches(), "Does not match simple duration pattern"); String suffix = matcher.group(2); return (StringUtils.hasLength(suffix) ? Unit.fromSuffix(suffix) : Unit.fromChronoUnit(unit)) - .parse(matcher.group(1)); + .parse(matcher.group(1)); } catch (Exception ex) { throw new IllegalArgumentException("'" + value + "' is not a valid simple duration", ex); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java index abf2bae3f1..5db8f13f8e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/DurationToNumberConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ final class DurationToNumberConverter implements GenericConverter { private Object convert(Duration source, ChronoUnit unit, Class type) { try { return type.getConstructor(String.class) - .newInstance(String.valueOf(DurationStyle.Unit.fromChronoUnit(unit).longValue(source))); + .newInstance(String.valueOf(DurationStyle.Unit.fromChronoUnit(unit).longValue(source))); } catch (Exception ex) { ReflectionUtils.rethrowRuntimeException(ex); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java index 868def2b73..7bc894dd53 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/LenientObjectToEnumConverterFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -95,8 +95,10 @@ abstract class LenientObjectToEnumConverterFactory implements ConverterFactor private String getCanonicalName(String name) { StringBuilder canonicalName = new StringBuilder(name.length()); - name.chars().filter(Character::isLetterOrDigit).map(Character::toLowerCase) - .forEach((c) -> canonicalName.append((char) c)); + name.chars() + .filter(Character::isLetterOrDigit) + .map(Character::toLowerCase) + .forEach((c) -> canonicalName.append((char) c)); return canonicalName.toString(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java index af14ea0de8..7a905a8fcb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/FailureAnalyzers.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,8 +69,8 @@ final class FailureAnalyzers implements SpringBootExceptionReporter { List analyzers = springFactoriesLoader.load(FailureAnalyzer.class, getArgumentResolver(context), FailureHandler.logging(logger)); List awareAnalyzers = analyzers.stream() - .filter((analyzer) -> analyzer instanceof BeanFactoryAware || analyzer instanceof EnvironmentAware) - .toList(); + .filter((analyzer) -> analyzer instanceof BeanFactoryAware || analyzer instanceof EnvironmentAware) + .toList(); if (!awareAnalyzers.isEmpty()) { String awareAnalyzerNames = StringUtils.collectionToCommaDelimitedString( awareAnalyzers.stream().map((analyzer) -> analyzer.getClass().getName()).toList()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java index af546dd1a9..b3baa188df 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,15 +62,17 @@ class InvalidConfigurationPropertyValueFailureAnalyzer private List getDescriptors(String propertyName) { return getPropertySources().filter((source) -> source.containsProperty(propertyName)) - .map((source) -> Descriptor.get(source, propertyName)).toList(); + .map((source) -> Descriptor.get(source, propertyName)) + .toList(); } private Stream> getPropertySources() { if (this.environment == null) { return Stream.empty(); } - return this.environment.getPropertySources().stream() - .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); + return this.environment.getPropertySources() + .stream() + .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); } private void appendDetails(StringBuilder message, InvalidConfigurationPropertyValueException cause, @@ -95,9 +97,9 @@ class InvalidConfigurationPropertyValueFailureAnalyzer private void appendAdditionalProperties(StringBuilder message, List descriptors) { List others = descriptors.subList(1, descriptors.size()); if (!others.isEmpty()) { - message.append( - String.format("%n%nAdditionally, this property is also set in the following property %s:%n%n", - (others.size() > 1) ? "sources" : "source")); + message + .append(String.format("%n%nAdditionally, this property is also set in the following property %s:%n%n", + (others.size() > 1) ? "sources" : "source")); for (Descriptor other : others) { message.append("\t- In '").append(other.getPropertySource()).append("'"); message.append(" with the value '").append(other.getValue()).append("'"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java index ab0d98414e..e3d95d3658 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java @@ -71,15 +71,17 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzer private List getDescriptors(String propertyName) { return getPropertySources().filter((source) -> source.containsProperty(propertyName)) - .map((source) -> Descriptor.get(source, propertyName)).toList(); + .map((source) -> Descriptor.get(source, propertyName)) + .toList(); } private Stream> getPropertySources() { if (this.environment == null) { return Stream.empty(); } - return this.environment.getPropertySources().stream() - .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); + return this.environment.getPropertySources() + .stream() + .filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source)); } private void appendDetails(StringBuilder message, MutuallyExclusiveConfigurationPropertiesException cause, @@ -87,7 +89,7 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzer descriptors.sort(Comparator.comparing((descriptor) -> descriptor.propertyName)); message.append(String.format("The following configuration properties are mutually exclusive:%n%n")); sortedStrings(cause.getMutuallyExclusiveNames()) - .forEach((name) -> message.append(String.format("\t%s%n", name))); + .forEach((name) -> message.append(String.format("\t%s%n", name))); message.append(String.format("%n")); message.append( String.format("However, more than one of those properties has been configured at the same time:%n%n")); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java index 1b0214beba..16ea0e5d36 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -116,7 +116,7 @@ class NoSuchMethodFailureAnalyzer extends AbstractFailureAnalyzer findCandidates(String className) { try { return Collections.list(NoSuchMethodFailureAnalyzer.class.getClassLoader() - .getResources(ClassUtils.convertClassNameToResourcePath(className) + ".class")); + .getResources(ClassUtils.convertClassNameToResourcePath(className) + ".class")); } catch (Throwable ex) { return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceRuntimeHints.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceRuntimeHints.java index 76b51333dc..24be1714cc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceRuntimeHints.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/PropertySourceRuntimeHints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -29,8 +29,9 @@ class PropertySourceRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - hints.reflection().registerTypeIfPresent(classLoader, "org.yaml.snakeyaml.Yaml", - (typeHint) -> typeHint.onReachableType(TypeReference.of(YamlPropertySourceLoader.class))); + hints.reflection() + .registerTypeIfPresent(classLoader, "org.yaml.snakeyaml.Yaml", + (typeHint) -> typeHint.onReachableType(TypeReference.of(YamlPropertySourceLoader.class))); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java index 0e1189be04..5dc701e1a2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -93,8 +93,11 @@ public class SpringApplicationJsonEnvironmentPostProcessor implements Environmen @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { MutablePropertySources propertySources = environment.getPropertySources(); - propertySources.stream().map(JsonPropertyValue::get).filter(Objects::nonNull).findFirst() - .ifPresent((v) -> processJson(environment, v)); + propertySources.stream() + .map(JsonPropertyValue::get) + .filter(Objects::nonNull) + .findFirst() + .ifPresent((v) -> processJson(environment, v)); } private void processJson(ConfigurableEnvironment environment, JsonPropertyValue propertyValue) { @@ -160,8 +163,9 @@ public class SpringApplicationJsonEnvironmentPostProcessor implements Environmen private String findPropertySource(MutablePropertySources sources) { if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null)) { PropertySource servletPropertySource = sources.stream() - .filter((source) -> SERVLET_ENVIRONMENT_PROPERTY_SOURCES.contains(source.getName())).findFirst() - .orElse(null); + .filter((source) -> SERVLET_ENVIRONMENT_PROPERTY_SOURCES.contains(source.getName())) + .findFirst() + .orElse(null); if (servletPropertySource != null) { return servletPropertySource.getName(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java index efbc13065a..b41e15b951 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/info/BuildProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -97,7 +97,7 @@ public class BuildProperties extends InfoProperties { if (value != null) { try { String updatedValue = String - .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); + .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); properties.setProperty(key, updatedValue); } catch (DateTimeException ex) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java index dac8c4aaf4..e5e2d20fbc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -94,7 +94,8 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar private void addJsonBean(Object bean) { MergedAnnotation annotation = MergedAnnotations - .from(bean.getClass(), SearchStrategy.TYPE_HIERARCHY).get(JsonComponent.class); + .from(bean.getClass(), SearchStrategy.TYPE_HIERARCHY) + .get(JsonComponent.class); Class[] types = annotation.getClassArray("type"); Scope scope = annotation.getEnum("scope", JsonComponent.Scope.class); addJsonBean(bean, types, scope); @@ -127,7 +128,7 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar @SuppressWarnings("unchecked") private void addJsonSerializerBean(JsonSerializer serializer, JsonComponent.Scope scope, Class[] types) { Class baseType = (Class) ResolvableType.forClass(JsonSerializer.class, serializer.getClass()) - .resolveGeneric(); + .resolveGeneric(); addBeanToModule(serializer, baseType, types, (scope == Scope.VALUES) ? this::addSerializer : this::addKeySerializer); @@ -136,7 +137,7 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar @SuppressWarnings("unchecked") private void addJsonDeserializerBean(JsonDeserializer deserializer, Class[] types) { Class baseType = (Class) ResolvableType.forClass(JsonDeserializer.class, deserializer.getClass()) - .resolveGeneric(); + .resolveGeneric(); addBeanToModule(deserializer, baseType, types, this::addDeserializer); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntries.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntries.java index 8c044c4a78..828cd44599 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntries.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntries.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,8 @@ public final class JsonMixinModuleEntries { private static void registerMixinClass(Builder builder, Class mixinClass) { MergedAnnotation annotation = MergedAnnotations - .from(mixinClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(JsonMixin.class); + .from(mixinClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY) + .get(JsonMixin.class); for (Class targetType : annotation.getClassArray("type")) { builder.and(targetType, mixinClass); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessor.java index 090999126f..980928d762 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class JsonMixinModuleEntriesBeanRegistrationAotProcessor implements BeanRegistra public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { if (registeredBean.getBeanClass().equals(JsonMixinModuleEntries.class)) { return BeanRegistrationAotContribution - .withCustomCodeFragments((codeFragments) -> new AotContribution(codeFragments, registeredBean)); + .withCustomCodeFragments((codeFragments) -> new AotContribution(codeFragments, registeredBean)); } return null; } @@ -69,7 +69,7 @@ class JsonMixinModuleEntriesBeanRegistrationAotProcessor implements BeanRegistra BeanRegistrationCode beanRegistrationCode, Executable constructorOrFactoryMethod, boolean allowDirectSupplierShortcut) { JsonMixinModuleEntries entries = this.registeredBean.getBeanFactory() - .getBean(this.registeredBean.getBeanName(), JsonMixinModuleEntries.class); + .getBean(this.registeredBean.getBeanName(), JsonMixinModuleEntries.class); contributeHints(generationContext.getRuntimeHints(), entries); GeneratedMethod generatedMethod = beanRegistrationCode.getMethods().add("getInstance", (method) -> { Class beanType = JsonMixinModuleEntries.class; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java index 7ba507e6bd..60cc940a84 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -345,7 +345,7 @@ public final class DataSourceBuilder { @SuppressWarnings("unchecked") MappedDataSourceProperties() { this.dataSourceType = (Class) ResolvableType.forClass(MappedDataSourceProperties.class, getClass()) - .resolveGeneric(); + .resolveGeneric(); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHints.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHints.java index 52305b881d..a91efdf7b2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHints.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHints.java @@ -52,8 +52,9 @@ class DataSourceBuilderRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { for (String typeName : TYPE_NAMES) { - hints.reflection().registerTypeIfPresent(classLoader, typeName, - (hint) -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)); + hints.reflection() + .registerTypeIfPresent(classLoader, typeName, + (hint) -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java index 10f9760463..35b9fc1ff5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -151,8 +151,10 @@ public enum EmbeddedDatabaseConnection { } private static EmbeddedDatabaseConnection getEmbeddedDatabaseConnection(String driverClass) { - return Stream.of(H2, HSQLDB, DERBY).filter((connection) -> connection.isDriverCompatible(driverClass)) - .findFirst().orElse(NONE); + return Stream.of(H2, HSQLDB, DERBY) + .filter((connection) -> connection.isDriverCompatible(driverClass)) + .findFirst() + .orElse(NONE); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java index 4ff7693649..c28837788e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/java/JavaLoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -103,7 +103,7 @@ public class JavaLoggingSystem extends AbstractLoggingSystem { Assert.notNull(location, "Location must not be null"); try { String configuration = FileCopyUtils - .copyToString(new InputStreamReader(ResourceUtils.getURL(location).openStream())); + .copyToString(new InputStreamReader(ResourceUtils.getURL(location).openStream())); if (logFile != null) { configuration = configuration.replace("${LOG_FILE}", StringUtils.cleanPath(logFile.toString())); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java index 2dc0600417..7d261dc849 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -153,7 +153,7 @@ public class Log4J2LoggingSystem extends AbstractLoggingSystem { } locations.add("log4j2.xml"); String propertyDefinedLocation = new PropertiesUtil(new Properties()) - .getStringProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); + .getStringProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); if (propertyDefinedLocation != null) { locations.add(propertyDefinedLocation); } @@ -258,7 +258,7 @@ public class Log4J2LoggingSystem extends AbstractLoggingSystem { private List getOverrides(LoggingInitializationContext initializationContext) { BindResult> overrides = Binder.get(initializationContext.getEnvironment()) - .bind("logging.log4j2.config.override", Bindable.listOf(String.class)); + .bind("logging.log4j2.config.override", Bindable.listOf(String.class)); return overrides.orElse(Collections.emptyList()); } @@ -308,7 +308,7 @@ public class Log4J2LoggingSystem extends AbstractLoggingSystem { return new ConfigurationSource(url.openStream(), ResourceUtils.getFile(url)); } AuthorizationProvider authorizationProvider = ConfigurationFactory - .authorizationProvider(PropertiesUtil.getProperties()); + .authorizationProvider(PropertiesUtil.getProperties()); SslConfiguration sslConfiguration = url.getProtocol().equals("https") ? SslConfigurationFactory.getSslConfiguration() : null; URLConnection connection = UrlConnectionFactory.createConnection(url, 0, sslConfiguration, @@ -381,8 +381,8 @@ public class Log4J2LoggingSystem extends AbstractLoggingSystem { private void setLogLevel(String loggerName, LoggerConfig logger, Level level) { if (logger == null) { - getLoggerContext().getConfiguration().addLogger(loggerName, - new LevelSetLoggerConfig(loggerName, level, true)); + getLoggerContext().getConfiguration() + .addLogger(loggerName, new LevelSetLoggerConfig(loggerName, level, true)); } else { logger.setLevel(level); @@ -504,7 +504,7 @@ public class Log4J2LoggingSystem extends AbstractLoggingSystem { public static class Factory implements LoggingSystemFactory { private static final boolean PRESENT = ClassUtils - .isPresent("org.apache.logging.log4j.core.impl.Log4jContextFactory", Factory.class.getClassLoader()); + .isPresent("org.apache.logging.log4j.core.impl.Log4jContextFactory", Factory.class.getClassLoader()); @Override public LoggingSystem getLoggingSystem(ClassLoader classLoader) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java index 0009dec9f8..b3ef8e87d2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ public class SpringBootPropertySource implements PropertySource { private static final String PREFIX = "log4j."; private final Map properties = Collections - .singletonMap(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, "false"); + .singletonMap(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, "false"); @Override public void forEach(BiConsumer action) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java index 3ed66dd5a6..5d884861c8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,18 +69,20 @@ class DefaultLogbackConfiguration { config.conversionRule("clr", ColorConverter.class); config.conversionRule("wex", WhitespaceThrowableProxyConverter.class); config.conversionRule("wEx", ExtendedWhitespaceThrowableProxyConverter.class); - config.getContext().putProperty("CONSOLE_LOG_PATTERN", resolve(config, "${CONSOLE_LOG_PATTERN:-" - + "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) " - + "%clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} " - + "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); + config.getContext() + .putProperty("CONSOLE_LOG_PATTERN", resolve(config, "${CONSOLE_LOG_PATTERN:-" + + "%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) " + + "%clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} " + + "%clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); String defaultCharset = Charset.defaultCharset().name(); - config.getContext().putProperty("CONSOLE_LOG_CHARSET", - resolve(config, "${CONSOLE_LOG_CHARSET:-" + defaultCharset + "}")); - config.getContext().putProperty("FILE_LOG_PATTERN", resolve(config, "${FILE_LOG_PATTERN:-" - + "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] " - + "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); - config.getContext().putProperty("FILE_LOG_CHARSET", - resolve(config, "${FILE_LOG_CHARSET:-" + defaultCharset + "}")); + config.getContext() + .putProperty("CONSOLE_LOG_CHARSET", resolve(config, "${CONSOLE_LOG_CHARSET:-" + defaultCharset + "}")); + config.getContext() + .putProperty("FILE_LOG_PATTERN", resolve(config, "${FILE_LOG_PATTERN:-" + + "%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] " + + "%-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}")); + config.getContext() + .putProperty("FILE_LOG_CHARSET", resolve(config, "${FILE_LOG_CHARSET:-" + defaultCharset + "}")); config.logger("org.apache.catalina.startup.DigesterFactory", Level.ERROR); config.logger("org.apache.catalina.util.LifecycleBase", Level.ERROR); config.logger("org.apache.coyote.http11.Http11NioProtocol", Level.WARN); @@ -120,8 +122,8 @@ class DefaultLogbackConfiguration { rollingPolicy.setContext(config.getContext()); rollingPolicy.setFileNamePattern( resolve(config, "${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}")); - rollingPolicy.setCleanHistoryOnStart( - resolveBoolean(config, "${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}")); + rollingPolicy + .setCleanHistoryOnStart(resolveBoolean(config, "${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}")); rollingPolicy.setMaxFileSize(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}")); rollingPolicy.setTotalSizeCap(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}")); rollingPolicy.setMaxHistory(resolveInt(config, "${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}")); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java index 7c47a1b59c..b57e5d80db 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class LogbackConfigurator { Assert.hasLength(conversionWord, "Conversion word must not be empty"); Assert.notNull(converterClass, "Converter class must not be null"); Map registry = (Map) this.context - .getObject(CoreConstants.PATTERN_RULE_REGISTRY); + .getObject(CoreConstants.PATTERN_RULE_REGISTRY); if (registry == null) { registry = new HashMap<>(); this.context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, registry); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java index 06d23ea471..33c0c60d70 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystem.java @@ -421,7 +421,7 @@ public class LogbackLoggingSystem extends AbstractLoggingSystem implements BeanF String key = BeanFactoryInitializationAotContribution.class.getName(); LoggerContext context = getLoggerContext(); BeanFactoryInitializationAotContribution contribution = (BeanFactoryInitializationAotContribution) context - .getObject(key); + .getObject(key); context.removeObject(key); return contribution; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java index 66f63250d7..0fcc1e4c1b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringBootJoranConfigurator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -177,9 +177,10 @@ class SpringBootJoranConfigurator extends JoranConfigurator { generationContext.getRuntimeHints().resources().registerPattern(MODEL_RESOURCE_LOCATION); SerializationHints serializationHints = generationContext.getRuntimeHints().serialization(); serializationTypes(this.model).forEach(serializationHints::registerType); - reflectionTypes(this.model).forEach((type) -> generationContext.getRuntimeHints().reflection().registerType( - TypeReference.of(type), MemberCategory.INTROSPECT_PUBLIC_METHODS, - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)); + reflectionTypes(this.model).forEach((type) -> generationContext.getRuntimeHints() + .reflection() + .registerType(TypeReference.of(type), MemberCategory.INTROSPECT_PUBLIC_METHODS, + MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)); } @SuppressWarnings("unchecked") @@ -235,7 +236,7 @@ class SpringBootJoranConfigurator extends JoranConfigurator { String tag = model.getTag(); if (tag != null) { className = this.modelInterpretationContext.getDefaultNestedComponentRegistry() - .findDefaultComponentTypeByTag(tag); + .findDefaultComponentTypeByTag(tag); if (className != null) { return loadImportType(className); } @@ -286,7 +287,7 @@ class SpringBootJoranConfigurator extends JoranConfigurator { private void processComponent(Class componentType, Set reflectionTypes) { BeanDescription beanDescription = this.modelInterpretationContext.getBeanDescriptionCache() - .getBeanDescription(componentType); + .getBeanDescription(componentType); reflectionTypes.addAll(parameterTypesNames(beanDescription.getPropertyNameToAdder().values())); reflectionTypes.addAll(parameterTypesNames(beanDescription.getPropertyNameToSetter().values())); reflectionTypes.add(componentType.getCanonicalName()); @@ -294,11 +295,14 @@ class SpringBootJoranConfigurator extends JoranConfigurator { private Collection parameterTypesNames(Collection methods) { return methods.stream() - .filter((method) -> !method.getDeclaringClass().equals(ContextAware.class) - && !method.getDeclaringClass().equals(ContextAwareBase.class)) - .map(Method::getParameterTypes).flatMap(Stream::of) - .filter((type) -> !type.isPrimitive() && !type.equals(String.class)) - .map((type) -> type.isArray() ? type.getComponentType() : type).map(Class::getName).toList(); + .filter((method) -> !method.getDeclaringClass().equals(ContextAware.class) + && !method.getDeclaringClass().equals(ContextAwareBase.class)) + .map(Method::getParameterTypes) + .flatMap(Stream::of) + .filter((type) -> !type.isPrimitive() && !type.equals(String.class)) + .map((type) -> type.isArray() ? type.getComponentType() : type) + .map(Class::getName) + .toList(); } } @@ -307,7 +311,7 @@ class SpringBootJoranConfigurator extends JoranConfigurator { private Model read() { try (InputStream modelInput = getClass().getClassLoader() - .getResourceAsStream(ModelWriter.MODEL_RESOURCE_LOCATION)) { + .getResourceAsStream(ModelWriter.MODEL_RESOURCE_LOCATION)) { try (ObjectInputStream input = new ObjectInputStream(modelInput)) { Model model = (Model) input.readObject(); ModelUtil.resetForReuse(model); @@ -353,7 +357,7 @@ class SpringBootJoranConfigurator extends JoranConfigurator { @SuppressWarnings("unchecked") private Map getRegistryMap() { Map patternRuleRegistry = (Map) this.context - .getObject(CoreConstants.PATTERN_RULE_REGISTRY); + .getObject(CoreConstants.PATTERN_RULE_REGISTRY); if (patternRuleRegistry == null) { patternRuleRegistry = new HashMap<>(); this.context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, patternRuleRegistry); @@ -366,8 +370,9 @@ class SpringBootJoranConfigurator extends JoranConfigurator { generationContext.getGeneratedFiles().addResourceFile(RESOURCE_LOCATION, () -> asInputStream(registryMap)); generationContext.getRuntimeHints().resources().registerPattern(RESOURCE_LOCATION); for (String ruleClassName : registryMap.values()) { - generationContext.getRuntimeHints().reflection().registerType(TypeReference.of(ruleClassName), - MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); + generationContext.getRuntimeHints() + .reflection() + .registerType(TypeReference.of(ruleClassName), MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileModelHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileModelHandler.java index e381dab46a..37705a88f1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileModelHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/SpringProfileModelHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,7 +59,7 @@ class SpringProfileModelHandler extends ModelHandlerBase { return false; } String[] profileNames = StringUtils - .trimArrayElements(StringUtils.commaDelimitedListToStringArray(model.getName())); + .trimArrayElements(StringUtils.commaDelimitedListToStringArray(model.getName())); if (profileNames.length == 0) { return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java index 0e232d8ec5..0e0d60b0f1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -236,7 +236,7 @@ public class EntityManagerFactoryBuilder { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); if (EntityManagerFactoryBuilder.this.persistenceUnitManager != null) { entityManagerFactoryBean - .setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager); + .setPersistenceUnitManager(EntityManagerFactoryBuilder.this.persistenceUnitManager); } if (this.persistenceUnit != null) { entityManagerFactoryBean.setPersistenceUnitName(this.persistenceUnit); @@ -268,8 +268,8 @@ public class EntityManagerFactoryBuilder { entityManagerFactoryBean.setBootstrapExecutor(EntityManagerFactoryBuilder.this.bootstrapExecutor); } if (EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors != null) { - entityManagerFactoryBean.setPersistenceUnitPostProcessors( - EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors); + entityManagerFactoryBean + .setPersistenceUnitPostProcessors(EntityManagerFactoryBuilder.this.persistenceUnitPostProcessors); } return entityManagerFactoryBean; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java index aaff7d27e1..13deb8ef0e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/orm/jpa/JpaDatabaseInitializerDetector.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -64,7 +64,7 @@ class JpaDatabaseInitializerDetector extends AbstractBeansOfTypeDatabaseInitiali String initializerName = iterator.next(); BeanDefinition initializerDefinition = beanFactory.getBeanDefinition(initializerName); if (JpaDatabaseInitializerDetector.class.getName() - .equals(initializerDefinition.getAttribute(DatabaseInitializerDetector.class.getName()))) { + .equals(initializerDefinition.getAttribute(DatabaseInitializerDetector.class.getName()))) { iterator.remove(); jpaInitializers.add(initializerName); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java index 34a0d1b2a6..e69eca5d33 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -218,9 +218,11 @@ public final class ConnectionFactoryBuilder { String[] protocols = protocol.split(COLON, 2); String driverDelegate = protocols[0]; String protocolDelegate = (protocols.length != 2) ? "" : protocols[1]; - return ConnectionFactoryOptions.builder().from(options) - .option(ConnectionFactoryOptions.DRIVER, driverDelegate) - .option(ConnectionFactoryOptions.PROTOCOL, protocolDelegate).build(); + return ConnectionFactoryOptions.builder() + .from(options) + .option(ConnectionFactoryOptions.DRIVER, driverDelegate) + .option(ConnectionFactoryOptions.PROTOCOL, protocolDelegate) + .build(); } @SuppressWarnings("unchecked") @@ -229,36 +231,51 @@ public final class ConnectionFactoryBuilder { ConnectionPoolConfiguration.Builder builder = ConnectionPoolConfiguration.builder(connectionFactory); PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); map.from(options.getValue(PoolingConnectionFactoryProvider.BACKGROUND_EVICTION_INTERVAL)) - .as(this::toDuration).to(builder::backgroundEvictionInterval); - map.from(options.getValue(PoolingConnectionFactoryProvider.INITIAL_SIZE)).as(this::toInteger) - .to(builder::initialSize); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_SIZE)).as(this::toInteger) - .to(builder::maxSize); - map.from(options.getValue(PoolingConnectionFactoryProvider.ACQUIRE_RETRY)).as(this::toInteger) - .to(builder::acquireRetry); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_LIFE_TIME)).as(this::toDuration) - .to(builder::maxLifeTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_ACQUIRE_TIME)).as(this::toDuration) - .to(builder::maxAcquireTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_IDLE_TIME)).as(this::toDuration) - .to(builder::maxIdleTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_CREATE_CONNECTION_TIME)).as(this::toDuration) - .to(builder::maxCreateConnectionTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_VALIDATION_TIME)).as(this::toDuration) - .to(builder::maxValidationTime); - map.from(options.getValue(PoolingConnectionFactoryProvider.MIN_IDLE)).as(this::toInteger) - .to(builder::minIdle); + .as(this::toDuration) + .to(builder::backgroundEvictionInterval); + map.from(options.getValue(PoolingConnectionFactoryProvider.INITIAL_SIZE)) + .as(this::toInteger) + .to(builder::initialSize); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_SIZE)) + .as(this::toInteger) + .to(builder::maxSize); + map.from(options.getValue(PoolingConnectionFactoryProvider.ACQUIRE_RETRY)) + .as(this::toInteger) + .to(builder::acquireRetry); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_LIFE_TIME)) + .as(this::toDuration) + .to(builder::maxLifeTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_ACQUIRE_TIME)) + .as(this::toDuration) + .to(builder::maxAcquireTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_IDLE_TIME)) + .as(this::toDuration) + .to(builder::maxIdleTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_CREATE_CONNECTION_TIME)) + .as(this::toDuration) + .to(builder::maxCreateConnectionTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MAX_VALIDATION_TIME)) + .as(this::toDuration) + .to(builder::maxValidationTime); + map.from(options.getValue(PoolingConnectionFactoryProvider.MIN_IDLE)) + .as(this::toInteger) + .to(builder::minIdle); map.from(options.getValue(PoolingConnectionFactoryProvider.POOL_NAME)).as(this::toString).to(builder::name); - map.from(options.getValue(PoolingConnectionFactoryProvider.PRE_RELEASE)).to((function) -> builder + map.from(options.getValue(PoolingConnectionFactoryProvider.PRE_RELEASE)) + .to((function) -> builder .preRelease((Function>) function)); - map.from(options.getValue(PoolingConnectionFactoryProvider.POST_ALLOCATE)).to((function) -> builder + map.from(options.getValue(PoolingConnectionFactoryProvider.POST_ALLOCATE)) + .to((function) -> builder .postAllocate((Function>) function)); - map.from(options.getValue(PoolingConnectionFactoryProvider.REGISTER_JMX)).as(this::toBoolean) - .to(builder::registerJmx); - map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_QUERY)).as(this::toString) - .to(builder::validationQuery); - map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_DEPTH)).as(this::toValidationDepth) - .to(builder::validationDepth); + map.from(options.getValue(PoolingConnectionFactoryProvider.REGISTER_JMX)) + .as(this::toBoolean) + .to(builder::registerJmx); + map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_QUERY)) + .as(this::toString) + .to(builder::validationQuery); + map.from(options.getValue(PoolingConnectionFactoryProvider.VALIDATION_DEPTH)) + .as(this::toValidationDepth) + .to(builder::validationDepth); return builder.build(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java index 6946817cca..0f2d9e3858 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ public abstract class ApplicationContextRequestMatcher implements RequestMatc @Override public final boolean matches(HttpServletRequest request) { WebApplicationContext webApplicationContext = WebApplicationContextUtils - .getRequiredWebApplicationContext(request.getServletContext()); + .getRequiredWebApplicationContext(request.getServletContext()); if (ignoreApplicationContext(webApplicationContext)) { return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializer.java index d35fb21fa7..2955439bf6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -144,7 +144,8 @@ public abstract class AbstractScriptDatabaseInitializer implements ResourceLoade private void runScripts(List resources) { runScripts(new Scripts(resources).continueOnError(this.settings.isContinueOnError()) - .separator(this.settings.getSeparator()).encoding(this.settings.getEncoding())); + .separator(this.settings.getSeparator()) + .encoding(this.settings.getEncoding())); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java index df2bb990d8..8a9344e1d5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,7 @@ public class DatabaseInitializationDependencyConfigurer implements ImportBeanDef String name = DependsOnDatabaseInitializationPostProcessor.class.getName(); if (!registry.containsBeanDefinition(name)) { BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(DependsOnDatabaseInitializationPostProcessor.class); + .rootBeanDefinition(DependsOnDatabaseInitializationPostProcessor.class); registry.registerBeanDefinition(name, builder.getBeanDefinition()); } } @@ -108,7 +108,7 @@ public class DatabaseInitializationDependencyConfigurer implements ImportBeanDef for (String initializerBeanName : initializerBeanNamesBatch) { BeanDefinition beanDefinition = getBeanDefinition(initializerBeanName, beanFactory); beanDefinition - .setDependsOn(merge(beanDefinition.getDependsOn(), previousInitializerBeanNamesBatch)); + .setDependsOn(merge(beanDefinition.getDependsOn(), previousInitializerBeanNamesBatch)); } previousInitializerBeanNamesBatch = initializerBeanNamesBatch; } @@ -156,8 +156,8 @@ public class DatabaseInitializationDependencyConfigurer implements ImportBeanDef private List getDetectors(ConfigurableListableBeanFactory beanFactory, Class type) { ArgumentResolver argumentResolver = ArgumentResolver.of(Environment.class, this.environment); - return SpringFactoriesLoader.forDefaultResourceLocation(beanFactory.getBeanClassLoader()).load(type, - argumentResolver); + return SpringFactoriesLoader.forDefaultResourceLocation(beanFactory.getBeanClassLoader()) + .load(type, argumentResolver); } private static BeanDefinition getBeanDefinition(String beanName, ConfigurableListableBeanFactory beanFactory) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java index 8d7964176f..af23e11115 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,8 @@ import org.springframework.util.ReflectionUtils; public class Instantiator { private static final Comparator> CONSTRUCTOR_COMPARATOR = Comparator - .>comparingInt(Constructor::getParameterCount).reversed(); + .>comparingInt(Constructor::getParameterCount) + .reversed(); private static final FailureHandler throwingFailureHandler = (type, implementationName, failure) -> { throw new IllegalArgumentException("Unable to instantiate " + implementationName + " [" + type.getName() + "]", diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java index 872204b3b2..21ec25238c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -299,8 +299,10 @@ public final class LambdaSafe { public Stream invokeAnd(Function invoker) { Function> mapper = (callbackInstance) -> invoke(callbackInstance, () -> invoker.apply(callbackInstance)); - return this.callbackInstances.stream().map(mapper).filter(InvocationResult::hasResult) - .map(InvocationResult::get); + return this.callbackInstances.stream() + .map(mapper) + .filter(InvocationResult::hasResult) + .map(InvocationResult::get); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactories.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactories.java index 758b27ea8f..232d87b846 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactories.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactories.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -148,9 +148,11 @@ public final class ClientHttpRequestFactories { private static HttpClient createHttpClient(Duration readTimeout) { SocketConfig socketConfig = SocketConfig.custom() - .setSoTimeout((int) readTimeout.toMillis(), TimeUnit.MILLISECONDS).build(); + .setSoTimeout((int) readTimeout.toMillis(), TimeUnit.MILLISECONDS) + .build(); PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create() - .setDefaultSocketConfig(socketConfig).build(); + .setDefaultSocketConfig(socketConfig) + .build(); return HttpClientBuilder.create().setConnectionManager(connectionManager).build(); } @@ -209,7 +211,7 @@ public final class ClientHttpRequestFactories { map.from(settings::connectTimeout).to((connectTimeout) -> setConnectTimeout(unwrapped, connectTimeout)); map.from(settings::readTimeout).to((readTimeout) -> setReadTimeout(unwrapped, readTimeout)); map.from(settings::bufferRequestBody) - .to((bufferRequestBody) -> setBufferRequestBody(unwrapped, bufferRequestBody)); + .to((bufferRequestBody) -> setBufferRequestBody(unwrapped, bufferRequestBody)); } private static ClientHttpRequestFactory unwrapRequestFactoryIfNecessary( @@ -248,10 +250,10 @@ public final class ClientHttpRequestFactories { Class... parameters) { Method method = ReflectionUtils.findMethod(requestFactory.getClass(), methodName, parameters); Assert.state(method != null, () -> "Request factory %s does not have a suitable %s method" - .formatted(requestFactory.getClass().getName(), methodName)); + .formatted(requestFactory.getClass().getName(), methodName)); Assert.state(!method.isAnnotationPresent(Deprecated.class), () -> "Request factory %s has the %s method marked as deprecated" - .formatted(requestFactory.getClass().getName(), methodName)); + .formatted(requestFactory.getClass().getName(), methodName)); return method; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettings.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettings.java index 89b26a276c..9d68f4f709 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettings.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -22,6 +22,7 @@ import org.springframework.http.client.ClientHttpRequestFactory; /** * Settings that can be applied when creating a {@link ClientHttpRequestFactory}. + * * @param connectTimeout the connect timeout * @param readTimeout the read timeout * @param bufferRequestBody if request body buffering is used diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java index 083226a580..9127c5246a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -657,8 +657,9 @@ public class RestTemplateBuilder { if (this.basicAuthentication == null && this.defaultHeaders.isEmpty() && this.requestCustomizers.isEmpty()) { return; } - restTemplate.getClientHttpRequestInitializers().add(new RestTemplateBuilderClientHttpRequestInitializer( - this.basicAuthentication, this.defaultHeaders, this.requestCustomizers)); + restTemplate.getClientHttpRequestInitializers() + .add(new RestTemplateBuilderClientHttpRequestInitializer(this.basicAuthentication, this.defaultHeaders, + this.requestCustomizers)); } @SuppressWarnings("unchecked") diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java index 849f384b6d..596c2fab4b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,7 @@ class RestTemplateBuilderClientHttpRequestInitializer implements ClientHttpReque } this.defaultHeaders.forEach(headers::putIfAbsent); LambdaSafe.callbacks(RestTemplateRequestCustomizer.class, this.requestCustomizers, request) - .invoke((customizer) -> customizer.customize(request)); + .invoke((customizer) -> customizer.customize(request)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java index a3c60ba856..0eeee2f537 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/ForwardHeadersCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class ForwardHeadersCustomizer implements JettyServerCustomizer { for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { ((HttpConfiguration.ConnectionFactory) connectionFactory).getHttpConfiguration() - .addCustomizer(customizer); + .addCustomizer(customizer); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java index 9f7bd76f02..7c6e82fbed 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -278,7 +278,7 @@ public class JettyServletWebServerFactory extends AbstractServletWebServerFactor private void addLocaleMappings(WebAppContext context) { getLocaleCharsetMappings() - .forEach((locale, charset) -> context.addLocaleEncoding(locale.toString(), charset.toString())); + .forEach((locale, charset) -> context.addLocaleEncoding(locale.toString(), charset.toString())); } private File getTempDirectory() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java index 2433ccc959..95ae2e3c2b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -199,8 +199,11 @@ public class JettyWebServer implements WebServer { } private String getContextPath() { - return Arrays.stream(this.server.getHandlers()).map(this::findContextHandler).filter(Objects::nonNull) - .map(ContextHandler::getContextPath).collect(Collectors.joining(" ")); + return Arrays.stream(this.server.getHandlers()) + .map(this::findContextHandler) + .filter(Objects::nonNull) + .map(ContextHandler::getContextPath) + .collect(Collectors.joining(" ")); } private ContextHandler findContextHandler(Handler handler) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java index 16b53d44a0..9ce9b4012b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -121,7 +121,7 @@ class SslServerCustomizer implements JettyServerCustomizer { // Jetty 10 try { return SslConnectionFactory.class.getConstructor(SslContextFactory.Server.class, String.class) - .newInstance(sslContextFactory, protocol); + .newInstance(sslContextFactory, protocol); } catch (Exception ex2) { throw new RuntimeException(ex2); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java index 143f04bfa3..57828601fa 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/CompressionCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -89,7 +89,7 @@ final class CompressionCustomizer implements NettyServerCustomizer { return (request, response) -> { HttpHeaders headers = request.requestHeaders(); return Arrays.stream(excludedUserAgents) - .noneMatch((candidate) -> headers.contains(HttpHeaderNames.USER_AGENT, candidate, true)); + .noneMatch((candidate) -> headers.contains(HttpHeaderNames.USER_AGENT, candidate, true)); }; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java index fad3b4c745..08c220a0bc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/SslServerCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -142,7 +142,7 @@ public class SslServerCustomizer implements NettyServerCustomizer { try { KeyStore store = getTrustStore(ssl, sslStoreProvider); TrustManagerFactory trustManagerFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(store); return trustManagerFactory; } @@ -240,8 +240,11 @@ public class SslServerCustomizer implements NettyServerCustomizer { @Override protected KeyManager[] engineGetKeyManagers() { - return Arrays.stream(this.delegate.getKeyManagers()).filter(X509ExtendedKeyManager.class::isInstance) - .map(X509ExtendedKeyManager.class::cast).map(this::wrap).toArray(KeyManager[]::new); + return Arrays.stream(this.delegate.getKeyManagers()) + .filter(X509ExtendedKeyManager.class::isInstance) + .map(X509ExtendedKeyManager.class::cast) + .map(this::wrap) + .toArray(KeyManager[]::new); } private ConfigurableAliasKeyManager wrap(X509ExtendedKeyManager keyManager) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java index 50aef22550..5f3fcfba64 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -211,8 +211,9 @@ public class TomcatReactiveWebServerFactory extends AbstractReactiveWebServerFac @SuppressWarnings("unchecked") private void invokeProtocolHandlerCustomizers(ProtocolHandler protocolHandler) { - LambdaSafe.callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, - protocolHandler).invoke((customizer) -> customizer.customize(protocolHandler)); + LambdaSafe + .callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, protocolHandler) + .invoke((customizer) -> customizer.customize(protocolHandler)); } private void customizeProtocol(AbstractProtocol protocol) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java index d634a32fa9..746b6bd1bc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -310,8 +310,9 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto private void addJasperInitializer(TomcatEmbeddedContext context) { try { ServletContainerInitializer initializer = (ServletContainerInitializer) ClassUtils - .forName("org.apache.jasper.servlet.JasperInitializer", null).getDeclaredConstructor() - .newInstance(); + .forName("org.apache.jasper.servlet.JasperInitializer", null) + .getDeclaredConstructor() + .newInstance(); context.addServletContainerInitializer(initializer, null); } catch (Exception ex) { @@ -356,8 +357,9 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto @SuppressWarnings("unchecked") private void invokeProtocolHandlerCustomizers(ProtocolHandler protocolHandler) { - LambdaSafe.callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, - protocolHandler).invoke((customizer) -> customizer.customize(protocolHandler)); + LambdaSafe + .callbacks(TomcatProtocolHandlerCustomizer.class, this.tomcatProtocolHandlerCustomizers, protocolHandler) + .invoke((customizer) -> customizer.customize(protocolHandler)); } private void customizeSsl(Connector connector) { @@ -436,7 +438,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto List suppliers = new ArrayList<>(); if (sessionSameSite != null) { suppliers.add(CookieSameSiteSupplier.of(sessionSameSite) - .whenHasName(() -> SessionConfig.getSessionCookieName(context))); + .whenHasName(() -> SessionConfig.getSessionCookieName(context))); } if (!CollectionUtils.isEmpty(getCookieSameSiteSuppliers())) { suppliers.addAll(getCookieSameSiteSuppliers()); @@ -867,9 +869,10 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto @Override public Set listWebAppPaths(String path) { - return this.delegate.listWebAppPaths(path).stream() - .filter((webAppPath) -> !webAppPath.startsWith("/org/springframework/boot")) - .collect(Collectors.toSet()); + return this.delegate.listWebAppPaths(path) + .stream() + .filter((webAppPath) -> !webAppPath.startsWith("/org/springframework/boot")) + .collect(Collectors.toSet()); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java index 6b910671c8..7c05aa77f3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -368,9 +368,11 @@ public class TomcatWebServer implements WebServer { } private String getContextPath() { - return Arrays.stream(this.tomcat.getHost().findChildren()).filter(TomcatEmbeddedContext.class::isInstance) - .map(TomcatEmbeddedContext.class::cast).map(TomcatEmbeddedContext::getPath) - .collect(Collectors.joining(" ")); + return Arrays.stream(this.tomcat.getHost().findChildren()) + .filter(TomcatEmbeddedContext.class::isInstance) + .map(TomcatEmbeddedContext.class::cast) + .map(TomcatEmbeddedContext::getPath) + .collect(Collectors.joining(" ")); } /** diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java index d8615085b4..6060827395 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -112,7 +112,7 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { KeyStore keyStore = getKeyStore(ssl, sslStoreProvider); SslConfigurationValidator.validateKeyAlias(keyStore, ssl.getKeyAlias()); KeyManagerFactory keyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); String keyPassword = (sslStoreProvider != null) ? sslStoreProvider.getKeyPassword() : null; if (keyPassword == null) { keyPassword = (ssl.getKeyPassword() != null) ? ssl.getKeyPassword() : ssl.getKeyStorePassword(); @@ -150,7 +150,7 @@ class SslBuilderCustomizer implements UndertowBuilderCustomizer { try { KeyStore store = getTrustStore(ssl, sslStoreProvider); TrustManagerFactory trustManagerFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(store); return trustManagerFactory.getTrustManagers(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java index 96901fedce..e457f75544 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -358,8 +358,8 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac } private void addLocaleMappings(DeploymentInfo deployment) { - getLocaleCharsetMappings().forEach( - (locale, charset) -> deployment.addLocaleCharsetMapping(locale.toString(), charset.toString())); + getLocaleCharsetMappings() + .forEach((locale, charset) -> deployment.addLocaleCharsetMapping(locale.toString(), charset.toString())); } private void registerServletContainerInitializerToDriveServletContextInitializers(DeploymentInfo deployment, diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java index 5fc9b1d2d7..dd7f887bfb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -411,12 +411,15 @@ public class UndertowWebServer implements WebServer { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - hints.reflection().registerTypeIfPresent(classLoader, "io.undertow.Undertow", - (hint) -> hint.withField("listeners").withField("channels")); - hints.reflection().registerTypeIfPresent(classLoader, "io.undertow.Undertow$ListenerConfig", - (hint) -> hint.withField("type").withField("port")); - hints.reflection().registerTypeIfPresent(classLoader, - "io.undertow.protocols.ssl.UndertowAcceptingSslChannel", (hint) -> hint.withField("ssl")); + hints.reflection() + .registerTypeIfPresent(classLoader, "io.undertow.Undertow", + (hint) -> hint.withField("listeners").withField("channels")); + hints.reflection() + .registerTypeIfPresent(classLoader, "io.undertow.Undertow$ListenerConfig", + (hint) -> hint.withField("type").withField("port")); + hints.reflection() + .registerTypeIfPresent(classLoader, "io.undertow.protocols.ssl.UndertowAcceptingSslChannel", + (hint) -> hint.withField("ssl")); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java index dc7482d486..084dbde662 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerFactoryDelegate.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -164,7 +164,7 @@ class UndertowWebServerFactoryDelegate { } if (ssl != null && ssl.isEnabled()) { new SslBuilderCustomizer(factory.getPort(), address, ssl, factory.getOrCreateSslStoreProvider()) - .customize(builder); + .customize(builder); } else { builder.addHttpListener(port, (address != null) ? address.getHostAddress() : "0.0.0.0"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java index 76c300250e..b8b99552f3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/context/WebServerManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class WebServerManager { this.handler.initializeHandler(); this.webServer.start(); this.applicationContext - .publishEvent(new ReactiveWebServerInitializedEvent(this.webServer, this.applicationContext)); + .publishEvent(new ReactiveWebServerInitializedEvent(this.webServer, this.applicationContext)); } void shutDownGracefully(GracefulShutdownCallback callback) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java index 95cc55a532..d55366b53c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -88,7 +88,8 @@ public class DefaultErrorAttributes implements ErrorAttributes { errorAttributes.put("path", request.path()); Throwable error = getError(request); MergedAnnotation responseStatusAnnotation = MergedAnnotations - .from(error.getClass(), SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class); + .from(error.getClass(), SearchStrategy.TYPE_HIERARCHY) + .get(ResponseStatus.class); HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation); errorAttributes.put("status", errorStatus.value()); errorAttributes.put("error", errorStatus.getReasonPhrase()); @@ -153,7 +154,7 @@ public class DefaultErrorAttributes implements ErrorAttributes { Optional error = request.attribute(ERROR_INTERNAL_ATTRIBUTE); error.ifPresent((value) -> request.attributes().putIfAbsent(ErrorAttributes.ERROR_ATTRIBUTE, value)); return (Throwable) error - .orElseThrow(() -> new IllegalStateException("Missing exception attribute in ServerWebExchange")); + .orElseThrow(() -> new IllegalStateException("Missing exception attribute in ServerWebExchange")); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java index 719cb84140..df8ba5c28f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/result/view/MustacheView.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -80,10 +80,11 @@ public class MustacheView extends AbstractUrlBasedView { Resource resource = resolveResource(); if (resource == null) { return Mono - .error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]")); + .error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]")); } - DataBuffer dataBuffer = exchange.getResponse().bufferFactory() - .allocateBuffer(DefaultDataBufferFactory.DEFAULT_INITIAL_CAPACITY); + DataBuffer dataBuffer = exchange.getResponse() + .bufferFactory() + .allocateBuffer(DefaultDataBufferFactory.DEFAULT_INITIAL_CAPACITY); try (Reader reader = getReader(resource)) { Template template = this.compiler.compile(reader); Charset charset = getCharset(contentType).orElseGet(this::getDefaultCharset); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java index e99968ece0..849989d894 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -326,7 +326,8 @@ public sealed class MimeMappings implements Iterable { try { loaded = new LinkedHashMap<>(); for (Entry entry : PropertiesLoaderUtils - .loadProperties(new ClassPathResource(MIME_MAPPINGS_PROPERTIES, getClass())).entrySet()) { + .loadProperties(new ClassPathResource(MIME_MAPPINGS_PROPERTIES, getClass())) + .entrySet()) { loaded.put((String) entry.getKey(), new Mapping((String) entry.getKey(), (String) entry.getValue())); } @@ -394,8 +395,8 @@ public sealed class MimeMappings implements Iterable { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { - hints.resources().registerPattern( - "org/springframework/boot/web/server/" + DefaultMimeMappings.MIME_MAPPINGS_PROPERTIES); + hints.resources() + .registerPattern("org/springframework/boot/web/server/" + DefaultMimeMappings.MIME_MAPPINGS_PROPERTIES); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java index 088813c12f..17e9c8e78b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,8 +68,8 @@ public class WebServerFactoryCustomizerBeanPostProcessor implements BeanPostProc @SuppressWarnings("unchecked") private void postProcessBeforeInitialization(WebServerFactory webServerFactory) { LambdaSafe.callbacks(WebServerFactoryCustomizer.class, getCustomizers(), webServerFactory) - .withLogger(WebServerFactoryCustomizerBeanPostProcessor.class) - .invoke((customizer) -> customizer.customize(webServerFactory)); + .withLogger(WebServerFactoryCustomizerBeanPostProcessor.class) + .invoke((customizer) -> customizer.customize(webServerFactory)); } private Collection> getCustomizers() { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java index d981571d04..ace35a20c8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentHandler.java @@ -70,7 +70,7 @@ abstract class ServletComponentHandler { void handle(AnnotatedBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { Map attributes = beanDefinition.getMetadata() - .getAnnotationAttributes(this.annotationType.getName()); + .getAnnotationAttributes(this.annotationType.getName()); if (attributes != null) { doHandle(attributes, beanDefinition, registry); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java index 9ab0a59a47..49d548f16b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,7 +54,7 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { private void updatePostProcessor(BeanDefinitionRegistry registry, Set packagesToScan) { ServletComponentRegisteringPostProcessorBeanDefinition definition = (ServletComponentRegisteringPostProcessorBeanDefinition) registry - .getBeanDefinition(BEAN_NAME); + .getBeanDefinition(BEAN_NAME); definition.addPackageNames(packagesToScan); } @@ -66,7 +66,7 @@ class ServletComponentScanRegistrar implements ImportBeanDefinitionRegistrar { private Set getPackagesToScan(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes - .fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); + .fromMap(metadata.getAnnotationAttributes(ServletComponentScan.class.getName())); String[] basePackages = attributes.getStringArray("basePackages"); Class[] basePackageClasses = attributes.getClassArray("basePackageClasses"); Set packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java index 285f76f053..157963fac1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -84,8 +84,10 @@ public class ServletContextInitializerBeans extends AbstractCollection value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE)).toList(); + this.sortedList = this.initializers.values() + .stream() + .flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE)) + .toList(); logMappings(this.initializers); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java index 3f8c2f1275..b001500293 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebListenerHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class WebListenerHandler extends ServletComponentHandler { protected void doHandle(Map attributes, AnnotatedBeanDefinition beanDefinition, BeanDefinitionRegistry registry) { BeanDefinitionBuilder builder = BeanDefinitionBuilder - .rootBeanDefinition(ServletComponentWebListenerRegistrar.class); + .rootBeanDefinition(ServletComponentWebListenerRegistrar.class); builder.addConstructorArgValue(beanDefinition.getBeanClassName()); registry.registerBeanDefinition(beanDefinition.getBeanClassName() + "Registrar", builder.getBeanDefinition()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java index 73b401b2c2..2a27c7961a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/WebServletHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -61,7 +61,7 @@ class WebServletHandler extends ServletComponentHandler { private MultipartConfigElement determineMultipartConfig(AnnotatedBeanDefinition beanDefinition) { Map attributes = beanDefinition.getMetadata() - .getAnnotationAttributes(MultipartConfig.class.getName()); + .getAnnotationAttributes(MultipartConfig.class.getName()); if (attributes == null) { return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java index a8e44ef50e..4823211ba9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/WebServerStartStopLifecycle.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class WebServerStartStopLifecycle implements SmartLifecycle { this.webServer.start(); this.running = true; this.applicationContext - .publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext)); + .publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext)); } @Override diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java index 280363ed0d..88dd4f98ed 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/server/StaticResourceJars.java @@ -47,7 +47,8 @@ class StaticResourceJars { } else { return getUrlsFrom(Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) - .map(this::toUrl).toArray(URL[]::new)); + .map(this::toUrl) + .toArray(URL[]::new)); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java index 6cecaf7b09..9f2c380624 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -487,7 +487,7 @@ public class WebServiceTemplateBuilder { } else if (!CollectionUtils.isEmpty(this.messageSenders.getMessageSenders())) { webServiceTemplate - .setMessageSenders(this.messageSenders.getMessageSenders().toArray(new WebServiceMessageSender[0])); + .setMessageSenders(this.messageSenders.getMessageSenders().toArray(new WebServiceMessageSender[0])); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java index 14bc3dedf4..a338f4a915 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/AbstractApplicationEnvironmentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -39,8 +39,8 @@ public abstract class AbstractApplicationEnvironmentTests { void getActiveProfilesDoesNotResolveProperty() { StandardEnvironment environment = createEnvironment(); new MockPropertySource().withProperty("", ""); - environment.getPropertySources().addFirst( - new MockPropertySource().withProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "test")); + environment.getPropertySources() + .addFirst(new MockPropertySource().withProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "test")); assertThat(environment.getActiveProfiles()).isEmpty(); } @@ -48,8 +48,9 @@ public abstract class AbstractApplicationEnvironmentTests { void getDefaultProfilesDoesNotResolveProperty() { StandardEnvironment environment = createEnvironment(); new MockPropertySource().withProperty("", ""); - environment.getPropertySources().addFirst( - new MockPropertySource().withProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "test")); + environment.getPropertySources() + .addFirst( + new MockPropertySource().withProperty(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, "test")); assertThat(environment.getDefaultProfiles()).containsExactly("default"); } @@ -57,7 +58,7 @@ public abstract class AbstractApplicationEnvironmentTests { void propertyResolverIsOptimizedForConfigurationProperties() { StandardEnvironment environment = createEnvironment(); ConfigurablePropertyResolver expected = ConfigurationPropertySources - .createPropertyResolver(new MutablePropertySources()); + .createPropertyResolver(new MutablePropertySources()); assertThat(environment).extracting("propertyResolver").hasSameClassAs(expected); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java index 4c39c3f8da..8ab5fa2b7e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -98,12 +98,12 @@ class BannerTests { this.context = application.run(); Banner printedBanner = (Banner) this.context.getBean("springBootBanner"); assertThat(printedBanner).hasFieldOrPropertyWithValue("banner", banner); - then(banner).should().printBanner(any(Environment.class), this.sourceClassCaptor.capture(), - any(PrintStream.class)); + then(banner).should() + .printBanner(any(Environment.class), this.sourceClassCaptor.capture(), any(PrintStream.class)); reset(banner); printedBanner.printBanner(this.context.getEnvironment(), null, System.out); - then(banner).should().printBanner(any(Environment.class), eq(this.sourceClassCaptor.getValue()), - any(PrintStream.class)); + then(banner).should() + .printBanner(any(Environment.class), eq(this.sourceClassCaptor.getValue()), any(PrintStream.class)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java index 31b5b892ec..c69e27f9c8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class DefaultApplicationArgumentsTests { @Test void argumentsMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultApplicationArguments((String[]) null)) - .withMessageContaining("Args must not be null"); + .withMessageContaining("Args must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java index 2846083193..8b38549076 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultBootstrapContextTests.java @@ -51,13 +51,13 @@ class DefaultBootstrapContextTests { @Test void registerWhenTypeIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> this.context.register(null, InstanceSupplier.of(1))) - .withMessage("Type must not be null"); + .withMessage("Type must not be null"); } @Test void registerWhenRegistrationIsNullThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.context.register(Integer.class, null)) - .withMessage("InstanceSupplier must not be null"); + .withMessage("InstanceSupplier must not be null"); } @Test @@ -80,8 +80,8 @@ class DefaultBootstrapContextTests { this.context.register(Integer.class, InstanceSupplier.from(this.counter::getAndIncrement)); this.context.get(Integer.class); assertThatIllegalStateException() - .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) - .withMessage("java.lang.Integer has already been created"); + .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) + .withMessage("java.lang.Integer has already been created"); } @Test @@ -98,8 +98,8 @@ class DefaultBootstrapContextTests { this.context.register(Integer.class, InstanceSupplier.from(this.counter::getAndIncrement)); this.context.get(Integer.class); assertThatIllegalStateException() - .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) - .withMessage("java.lang.Integer has already been created"); + .isThrownBy(() -> this.context.register(Integer.class, InstanceSupplier.of(100))) + .withMessage("java.lang.Integer has already been created"); } @Test @@ -155,7 +155,7 @@ class DefaultBootstrapContextTests { void getWhenNoRegistrationThrowsIllegalStateException() { this.context.register(Number.class, InstanceSupplier.of(1)); assertThatIllegalStateException().isThrownBy(() -> this.context.get(Long.class)) - .withMessageContaining("has not been registered"); + .withMessageContaining("has not been registered"); } @Test @@ -247,8 +247,9 @@ class DefaultBootstrapContextTests { this.context.addCloseListener(listener); assertThat(listener).wasNotCalled(); this.context.close(this.applicationContext); - assertThat(listener).wasCalledOnlyOnce().hasBootstrapContextSameAs(this.context) - .hasApplicationContextSameAs(this.applicationContext); + assertThat(listener).wasCalledOnlyOnce() + .hasBootstrapContextSameAs(this.context) + .hasApplicationContextSameAs(this.applicationContext); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java index 0e418995a6..725396f8db 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/EnvironmentConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class EnvironmentConverterTests { AbstractEnvironment originalEnvironment = new MockEnvironment(); originalEnvironment.setActiveProfiles("activeProfile1", "activeProfile2"); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment.getActiveProfiles()).containsExactly("activeProfile1", "activeProfile2"); } @@ -58,7 +58,7 @@ class EnvironmentConverterTests { ConfigurableConversionService conversionService = mock(ConfigurableConversionService.class); originalEnvironment.setConversionService(conversionService); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(originalEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment.getConversionService()).isEqualTo(conversionService); } @@ -66,7 +66,7 @@ class EnvironmentConverterTests { void envClassSameShouldReturnEnvironmentUnconverted() { StandardEnvironment standardEnvironment = new StandardEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isSameAs(standardEnvironment); } @@ -74,7 +74,7 @@ class EnvironmentConverterTests { void standardServletEnvironmentIsConverted() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardServletEnvironment); } @@ -82,7 +82,7 @@ class EnvironmentConverterTests { void servletPropertySourcesAreNotCopiedOverIfNotWebEnvironment() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardServletEnvironment); Set names = new HashSet<>(); for (PropertySource propertySource : convertedEnvironment.getPropertySources()) { @@ -97,7 +97,7 @@ class EnvironmentConverterTests { void envClassSameShouldReturnEnvironmentUnconvertedEvenForWeb() { StandardServletEnvironment standardServletEnvironment = new StandardServletEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardServletEnvironment, StandardServletEnvironment.class); + .convertEnvironmentIfNecessary(standardServletEnvironment, StandardServletEnvironment.class); assertThat(convertedEnvironment).isSameAs(standardServletEnvironment); } @@ -105,7 +105,7 @@ class EnvironmentConverterTests { void servletPropertySourcesArePresentWhenTypeToConvertIsWeb() { StandardEnvironment standardEnvironment = new StandardEnvironment(); ConfigurableEnvironment convertedEnvironment = this.environmentConverter - .convertEnvironmentIfNecessary(standardEnvironment, StandardServletEnvironment.class); + .convertEnvironmentIfNecessary(standardEnvironment, StandardServletEnvironment.class); assertThat(convertedEnvironment).isNotSameAs(standardEnvironment); Set names = new HashSet<>(); for (PropertySource propertySource : convertedEnvironment.getPropertySources()) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index f33da67b10..194194d066 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -47,7 +47,7 @@ class ExitCodeGeneratorsTests { @Test void addWhenGeneratorIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ExitCodeGenerators().add(null)) - .withMessageContaining("Generator must not be null"); + .withMessageContaining("Generator must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationAotProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationAotProcessorTests.java index edfaa0c44f..4894e27584 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationAotProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationAotProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class SpringApplicationAotProcessorTests { SpringApplicationAotProcessor processor = new SpringApplicationAotProcessor(BrokenApplication.class, settings(directory), new String[0]); assertThatIllegalStateException().isThrownBy(processor::process) - .withMessageContaining("Does it run a SpringApplication?"); + .withMessageContaining("Does it run a SpringApplication?"); assertThat(directory).isEmptyDirectory(); } @@ -85,14 +85,18 @@ class SpringApplicationAotProcessorTests { @Test void invokeMainWithMissingArguments() { assertThatIllegalArgumentException() - .isThrownBy(() -> SpringApplicationAotProcessor.main(new String[] { "Test" })) - .withMessageContaining("Usage:"); + .isThrownBy(() -> SpringApplicationAotProcessor.main(new String[] { "Test" })) + .withMessageContaining("Usage:"); } private Settings settings(Path directory) { - return Settings.builder().sourceOutput(directory.resolve("source")) - .resourceOutput(directory.resolve("resource")).classOutput(directory.resolve("class")) - .groupId("com.example").artifactId("example").build(); + return Settings.builder() + .sourceOutput(directory.resolve("source")) + .resourceOutput(directory.resolve("resource")) + .classOutput(directory.resolve("class")) + .groupId("com.example") + .artifactId("example") + .build(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java index aa2d1bff30..5e8a430303 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationNoWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class SpringApplicationNoWebTests { void specificApplicationContextClass() { SpringApplication application = new SpringApplication(ExampleConfig.class); application - .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); + .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); ConfigurableApplicationContext context = application.run(); assertThat(context).isInstanceOf(StaticApplicationContext.class); context.close(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java index 1c3f068ff1..c08862bf7c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -77,7 +77,7 @@ public final class SpringApplicationShutdownHookInstance implements AssertProvid private AbstractBooleanAssert assertThatIsApplicationContextRegistered( ConfigurableApplicationContext context) { return Assertions.assertThat(this.actual.isApplicationContextRegistered(context)) - .as("ApplicationContext registered with shutdown hook"); + .as("ApplicationContext registered with shutdown hook"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java index 42b8eac002..133f5acab8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationShutdownHookTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -128,7 +128,7 @@ class SpringApplicationShutdownHookTests { void addHandlerActionWhenNullThrowsException() { TestSpringApplicationShutdownHook shutdownHook = new TestSpringApplicationShutdownHook(); assertThatIllegalArgumentException().isThrownBy(() -> shutdownHook.getHandlers().add(null)) - .withMessage("Action must not be null"); + .withMessage("Action must not be null"); } @Test @@ -137,14 +137,14 @@ class SpringApplicationShutdownHookTests { shutdownHook.run(); Runnable handlerAction = new TestHandlerAction(new ArrayList<>()); assertThatIllegalStateException().isThrownBy(() -> shutdownHook.getHandlers().add(handlerAction)) - .withMessage("Shutdown in progress"); + .withMessage("Shutdown in progress"); } @Test void removeHandlerActionWhenNullThrowsException() { TestSpringApplicationShutdownHook shutdownHook = new TestSpringApplicationShutdownHook(); assertThatIllegalArgumentException().isThrownBy(() -> shutdownHook.getHandlers().remove(null)) - .withMessage("Action must not be null"); + .withMessage("Action must not be null"); } @Test @@ -154,7 +154,7 @@ class SpringApplicationShutdownHookTests { shutdownHook.getHandlers().add(handlerAction); shutdownHook.run(); assertThatIllegalStateException().isThrownBy(() -> shutdownHook.getHandlers().remove(handlerAction)) - .withMessage("Shutdown in progress"); + .withMessage("Shutdown in progress"); } @Test @@ -164,7 +164,7 @@ class SpringApplicationShutdownHookTests { shutdownHook.registerApplicationContext(context); context.refresh(); assertThatThrownBy(() -> shutdownHook.deregisterFailedApplicationContext(context)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(IllegalStateException.class); assertThat(shutdownHook.isApplicationContextRegistered(context)).isTrue(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index c9502d1889..696f287bcd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -200,20 +200,20 @@ class SpringApplicationTests { @Test void sourcesMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication((Class[]) null).run()) - .withMessageContaining("PrimarySources must not be null"); + .withMessageContaining("PrimarySources must not be null"); } @Test void sourcesMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringApplication().run()) - .withMessageContaining("Sources must not be empty"); + .withMessageContaining("Sources must not be empty"); } @Test void sourcesMustBeAccessible() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringApplication(InaccessibleConfiguration.class).run()) - .withMessageContaining("No visible constructors"); + .isThrownBy(() -> new SpringApplication(InaccessibleConfiguration.class).run()) + .withMessageContaining("No visible constructors"); } @Test @@ -250,7 +250,7 @@ class SpringApplicationTests { application.setEnvironment(environment); this.context = application.run(); assertThat(output) - .contains("No active profile set, falling back to 2 default profiles: \"p0,p1\", \"default\""); + .contains("No active profile set, falling back to 2 default profiles: \"p0,p1\", \"default\""); } @Test @@ -325,7 +325,7 @@ class SpringApplicationTests { void specificApplicationContextFactory() { SpringApplication application = new SpringApplication(ExampleConfig.class); application - .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); + .setApplicationContextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); } @@ -336,7 +336,7 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); final AtomicReference reference = new AtomicReference<>(); application.setInitializers(Collections - .singletonList((ApplicationContextInitializer) reference::set)); + .singletonList((ApplicationContextInitializer) reference::set)); this.context = application.run("--foo=bar"); assertThat(this.context).isSameAs(reference.get()); // Custom initializers do not switch off the defaults @@ -379,10 +379,10 @@ class SpringApplicationTests { then(listener).should(inOrder).onApplicationEvent(isA(ContextRefreshedEvent.class)); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationStartedEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationReadyEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); inOrder.verifyNoMoreInteractions(); } @@ -513,7 +513,7 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); ConfigurableEnvironment environment = new StandardEnvironment(); environment.getPropertySources() - .addFirst(new MapPropertySource("commandLineArgs", Collections.singletonMap("foo", "original"))); + .addFirst(new MapPropertySource("commandLineArgs", Collections.singletonMap("foo", "original"))); application.setEnvironment(environment); this.context = application.run("--foo=bar", "--bar=foo"); assertThat(environment).has(matchingPropertySource(CompositePropertySource.class, "commandLineArgs")); @@ -521,13 +521,13 @@ class SpringApplicationTests { // New command line properties take precedence assertThat(environment.getProperty("foo")).isEqualTo("bar"); CompositePropertySource composite = (CompositePropertySource) environment.getPropertySources() - .get("commandLineArgs"); + .get("commandLineArgs"); assertThat(composite.getPropertySources()).hasSize(2); - assertThat(composite.getPropertySources()).first().matches( - (source) -> source.getName().equals("springApplicationCommandLineArgs"), - "is named springApplicationCommandLineArgs"); + assertThat(composite.getPropertySources()).first() + .matches((source) -> source.getName().equals("springApplicationCommandLineArgs"), + "is named springApplicationCommandLineArgs"); assertThat(composite.getPropertySources()).element(1) - .matches((source) -> source.getName().equals("commandLineArgs"), "is named commandLineArgs"); + .matches((source) -> source.getName().equals("commandLineArgs"), "is named commandLineArgs"); } @Test @@ -601,9 +601,9 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getBeanFactory().getConversionService()) - .isInstanceOf(ApplicationConversionService.class); + .isInstanceOf(ApplicationConversionService.class); assertThat(this.context.getEnvironment().getConversionService()) - .isInstanceOf(ApplicationConversionService.class); + .isInstanceOf(ApplicationConversionService.class); } @Test @@ -614,7 +614,7 @@ class SpringApplicationTests { this.context = application.run(); assertThat(this.context.getBeanFactory().getConversionService()).isNull(); assertThat(this.context.getEnvironment().getConversionService()) - .isNotInstanceOf(ApplicationConversionService.class); + .isNotInstanceOf(ApplicationConversionService.class); } @Test @@ -850,10 +850,13 @@ class SpringApplicationTests { @Test void defaultPropertiesShouldBeMerged() { MockEnvironment environment = new MockEnvironment(); - environment.getPropertySources().addFirst( - new MapPropertySource(DefaultPropertiesPropertySource.NAME, Collections.singletonMap("bar", "foo"))); + environment.getPropertySources() + .addFirst(new MapPropertySource(DefaultPropertiesPropertySource.NAME, + Collections.singletonMap("bar", "foo"))); SpringApplication application = new SpringApplicationBuilder(ExampleConfig.class).environment(environment) - .properties("baz=bing").web(WebApplicationType.NONE).build(); + .properties("baz=bing") + .web(WebApplicationType.NONE) + .build(); this.context = application.run(); assertThat(getEnvironment().getProperty("bar")).isEqualTo("foo"); assertThat(getEnvironment().getProperty("baz")).isEqualTo("bing"); @@ -917,10 +920,10 @@ class SpringApplicationTests { then(listener).should(inOrder).onApplicationEvent(isA(ContextRefreshedEvent.class)); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationStartedEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(LivenessState.CORRECT))); then(listener).should(inOrder).onApplicationEvent(isA(ApplicationReadyEvent.class)); then(listener).should(inOrder) - .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); + .onApplicationEvent(argThat(isAvailabilityChangeEventWithState(ReadinessState.ACCEPTING_TRAFFIC))); inOrder.verifyNoMoreInteractions(); } @@ -1028,13 +1031,13 @@ class SpringApplicationTests { Iterator> iterator = this.context.getEnvironment().getPropertySources().iterator(); assertThat(iterator.next().getName()).isEqualTo("configurationProperties"); assertThat(iterator.next().getName()) - .isEqualTo(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); + .isEqualTo(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME); } @Test void nonWebApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleConfig.class) - .run("--spring.main.web-application-type=none"); + .run("--spring.main.web-application-type=none"); assertThat(context).isNotInstanceOfAny(WebApplicationContext.class, ReactiveWebApplicationContext.class); assertThat(context.getEnvironment()).isNotInstanceOfAny(ConfigurableWebEnvironment.class); } @@ -1042,7 +1045,7 @@ class SpringApplicationTests { @Test void webApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleWebConfig.class) - .run("--spring.main.web-application-type=servlet"); + .run("--spring.main.web-application-type=servlet"); assertThat(context).isInstanceOf(WebApplicationContext.class); assertThat(context.getEnvironment()).isInstanceOf(StandardServletEnvironment.class); assertThat(context.getEnvironment().getClass().getName()).endsWith("ApplicationServletEnvironment"); @@ -1051,7 +1054,7 @@ class SpringApplicationTests { @Test void reactiveApplicationConfiguredViaAPropertyHasTheCorrectTypeOfContextAndEnvironment() { ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) - .run("--spring.main.web-application-type=reactive"); + .run("--spring.main.web-application-type=reactive"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); assertThat(context.getEnvironment()).isInstanceOf(StandardReactiveWebEnvironment.class); assertThat(context.getEnvironment().getClass().getName()).endsWith("ApplicationReactiveWebEnvironment"); @@ -1060,7 +1063,7 @@ class SpringApplicationTests { @Test void environmentIsConvertedIfTypeDoesNotMatch() { ConfigurableApplicationContext context = new SpringApplication(ExampleReactiveWebConfig.class) - .run("--spring.profiles.active=withwebapplicationtype"); + .run("--spring.profiles.active=withwebapplicationtype"); assertThat(context).isInstanceOf(ReactiveWebApplicationContext.class); assertThat(context.getEnvironment()).isInstanceOf(StandardReactiveWebEnvironment.class); assertThat(context.getEnvironment().getClass().getName()).endsWith("ApplicationReactiveWebEnvironment"); @@ -1087,29 +1090,30 @@ class SpringApplicationTests { @Test void beanDefinitionOverridingIsDisabledByDefault() { assertThatExceptionOfType(BeanDefinitionOverrideException.class) - .isThrownBy(() -> new SpringApplication(ExampleConfig.class, OverrideConfig.class).run()); + .isThrownBy(() -> new SpringApplication(ExampleConfig.class, OverrideConfig.class).run()); } @Test void beanDefinitionOverridingCanBeEnabled() { assertThat(new SpringApplication(ExampleConfig.class, OverrideConfig.class) - .run("--spring.main.allow-bean-definition-overriding=true", "--spring.main.web-application-type=none") - .getBean("someBean")).isEqualTo("override"); + .run("--spring.main.allow-bean-definition-overriding=true", "--spring.main.web-application-type=none") + .getBean("someBean")).isEqualTo("override"); } @Test void circularReferencesAreDisabledByDefault() { assertThatExceptionOfType(UnsatisfiedDependencyException.class) - .isThrownBy(() -> new SpringApplication(ExampleProducerConfiguration.class, - ExampleConsumerConfiguration.class).run("--spring.main.web-application-type=none")) - .withRootCauseInstanceOf(BeanCurrentlyInCreationException.class); + .isThrownBy( + () -> new SpringApplication(ExampleProducerConfiguration.class, ExampleConsumerConfiguration.class) + .run("--spring.main.web-application-type=none")) + .withRootCauseInstanceOf(BeanCurrentlyInCreationException.class); } @Test void circularReferencesCanBeEnabled() { assertThatNoException().isThrownBy( - () -> new SpringApplication(ExampleProducerConfiguration.class, ExampleConsumerConfiguration.class).run( - "--spring.main.web-application-type=none", "--spring.main.allow-circular-references=true")); + () -> new SpringApplication(ExampleProducerConfiguration.class, ExampleConsumerConfiguration.class) + .run("--spring.main.web-application-type=none", "--spring.main.allow-circular-references=true")); } @Test @@ -1123,28 +1127,28 @@ class SpringApplicationTests { @Test void lazyInitializationIsDisabledByDefault() { assertThat(new SpringApplication(LazyInitializationConfig.class).run("--spring.main.web-application-type=none") - .getBean(AtomicInteger.class)).hasValue(1); + .getBean(AtomicInteger.class)).hasValue(1); } @Test void lazyInitializationCanBeEnabled() { assertThat(new SpringApplication(LazyInitializationConfig.class) - .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") - .getBean(AtomicInteger.class)).hasValue(0); + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") + .getBean(AtomicInteger.class)).hasValue(0); } @Test void lazyInitializationIgnoresBeansThatAreExplicitlyNotLazy() { assertThat(new SpringApplication(NotLazyInitializationConfig.class) - .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") - .getBean(AtomicInteger.class)).hasValue(1); + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") + .getBean(AtomicInteger.class)).hasValue(1); } @Test void lazyInitializationIgnoresLazyInitializationExcludeFilteredBeans() { assertThat(new SpringApplication(LazyInitializationExcludeFilterConfig.class) - .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") - .getBean(AtomicInteger.class)).hasValue(1); + .run("--spring.main.web-application-type=none", "--spring.main.lazy-initialization=true") + .getBean(AtomicInteger.class)).hasValue(1); } @Test @@ -1165,10 +1169,14 @@ class SpringApplicationTests { then(applicationStartup).should().start("spring.boot.application.context-loaded"); then(applicationStartup).should().start("spring.boot.application.started"); then(applicationStartup).should().start("spring.boot.application.ready"); - long startCount = mockingDetails(applicationStartup).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("start(")).count(); - long endCount = mockingDetails(startupStep).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("end(")).count(); + long startCount = mockingDetails(applicationStartup).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("start(")) + .count(); + long endCount = mockingDetails(startupStep).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("end(")) + .count(); assertThat(startCount).isEqualTo(endCount); } @@ -1186,10 +1194,14 @@ class SpringApplicationTests { then(applicationStartup).should().start("spring.boot.application.starting"); then(applicationStartup).should().start("spring.boot.application.environment-prepared"); then(applicationStartup).should().start("spring.boot.application.failed"); - long startCount = mockingDetails(applicationStartup).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("start(")).count(); - long endCount = mockingDetails(startupStep).getInvocations().stream() - .filter((invocation) -> invocation.getMethod().toString().contains("end(")).count(); + long startCount = mockingDetails(applicationStartup).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("start(")) + .count(); + long endCount = mockingDetails(startupStep).getInvocations() + .stream() + .filter((invocation) -> invocation.getMethod().toString().contains("end(")) + .count(); assertThat(startCount).isEqualTo(endCount); } @@ -1205,7 +1217,7 @@ class SpringApplicationTests { ApplicationStartingEvent startingEvent = listener.getEvent(ApplicationStartingEvent.class); assertThat(startingEvent.getBootstrapContext().get(String.class)).isEqualTo("boot"); ApplicationEnvironmentPreparedEvent environmentPreparedEvent = listener - .getEvent(ApplicationEnvironmentPreparedEvent.class); + .getEvent(ApplicationEnvironmentPreparedEvent.class); assertThat(environmentPreparedEvent.getBootstrapContext().get(String.class)).isEqualTo("boot"); } @@ -1215,8 +1227,9 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); application.addBootstrapRegistryInitializer((bootstrapContext) -> { bootstrapContext.register(String.class, InstanceSupplier.of("boot")); - bootstrapContext.addCloseListener((event) -> event.getApplicationContext().getBeanFactory() - .registerSingleton("test", event.getBootstrapContext().get(String.class))); + bootstrapContext.addCloseListener((event) -> event.getApplicationContext() + .getBeanFactory() + .registerSingleton("test", event.getBootstrapContext().get(String.class))); }); ConfigurableApplicationContext applicationContext = application.run(); assertThat(applicationContext.getBean("test")).isEqualTo("boot"); @@ -1225,7 +1238,7 @@ class SpringApplicationTests { @Test void settingEnvironmentPrefixViaPropertiesThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> new SpringApplication().run("--spring.main.environment-prefix=my")); + .isThrownBy(() -> new SpringApplication().run("--spring.main.environment-prefix=my")); } @Test @@ -1244,7 +1257,7 @@ class SpringApplicationTests { application.setDefaultProperties(Collections.singletonMap("test.name", "test")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("test.name")) - .isEqualTo("spring-application-config-property-source"); + .isEqualTo("spring-application-config-property-source"); } @Test @@ -1255,10 +1268,13 @@ class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); assertThatExceptionOfType(BeanCreationException.class).isThrownBy(application::run); assertThat(events).hasAtLeastOneElementOfType(ApplicationFailedEvent.class); - ApplicationFailedEvent failure = events.stream().filter((event) -> event instanceof ApplicationFailedEvent) - .map(ApplicationFailedEvent.class::cast).findFirst().get(); + ApplicationFailedEvent failure = events.stream() + .filter((event) -> event instanceof ApplicationFailedEvent) + .map(ApplicationFailedEvent.class::cast) + .findFirst() + .get(); assertThat(SpringApplicationShutdownHookInstance.get()) - .didNotRegisterApplicationContext(failure.getApplicationContext()); + .didNotRegisterApplicationContext(failure.getApplicationContext()); } @Test @@ -1304,8 +1320,8 @@ class SpringApplicationTests { }); SpringApplicationHook hook = (springApplication) -> runListener; assertThatExceptionOfType(SpringApplication.AbandonedRunException.class) - .isThrownBy(() -> SpringApplication.withHook(hook, () -> application.run())) - .satisfies((ex) -> assertThat(ex.getApplicationContext().isRunning()).isFalse()); + .isThrownBy(() -> SpringApplication.withHook(hook, () -> application.run())) + .satisfies((ex) -> assertThat(ex.getApplicationContext().isRunning()).isFalse()); then(runListener).should().starting(any()); then(runListener).should().contextPrepared(any()); then(runListener).should(never()).ready(any(), any()); @@ -1323,7 +1339,7 @@ class SpringApplicationTests { new SpringApplicationRuntimeHints().registerHints(hints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onType(SpringApplication.class)).accepts(hints); assertThat(RuntimeHintsPredicates.reflection().onMethod(SpringApplication.class, "setBannerMode")) - .accepts(hints); + .accepts(hints); assertThat(RuntimeHintsPredicates.reflection().onMethod(SpringApplication.class, "getSources")).accepts(hints); assertThat(RuntimeHintsPredicates.reflection().onMethod(SpringApplication.class, "setSources")).accepts(hints); assertThat(RuntimeHintsPredicates.reflection().onMethod(SpringApplication.class, "load")).rejects(hints); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java index a5e10fcd0f..9f7bc8d121 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootConfigurationTests.java @@ -34,14 +34,14 @@ class SpringBootConfigurationTests { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(DefaultSpringBootConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(DefaultSpringBootConfiguration.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", true); } @Test void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils - .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootConfiguration.class, Configuration.class); + .getMergedAnnotationAttributes(NoBeanMethodProxyingSpringBootConfiguration.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", false); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java index 887413c25c..02cfa6cda4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringBootVersionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class SpringBootVersionTests { @Test void getVersionShouldReturnVersionMatchingGradleProperties() throws IOException { String expectedVersion = PropertiesLoaderUtils.loadProperties(new FileSystemResource(findGradleProperties())) - .getProperty("version"); + .getProperty("version"); assertThat(SpringBootVersion.getVersion()).isEqualTo(expectedVersion); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartupInfoLoggerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartupInfoLoggerTests.java index e22f6cf9f0..7c136fb84a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartupInfoLoggerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/StartupInfoLoggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,9 +60,9 @@ class StartupInfoLoggerTests { ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class); then(this.log).should().info(captor.capture()); assertThat(captor.getValue().toString()) - .contains("Starting AOT-processed " + getClass().getSimpleName() + " using Java " - + System.getProperty("java.version") + " with PID " + new ApplicationPid() + " (started by " - + System.getProperty("user.name") + " in " + System.getProperty("user.dir") + ")"); + .contains("Starting AOT-processed " + getClass().getSimpleName() + " using Java " + + System.getProperty("java.version") + " with PID " + new ApplicationPid() + " (started by " + + System.getProperty("user.name") + " in " + System.getProperty("user.dir") + ")"); } finally { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index cc18ba2561..07510abcc2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -122,7 +122,7 @@ class SpringApplicationAdminMXBeanRegistrarTests { assertThat(this.context.isRunning()).isFalse(); // JMX cleanup assertThatExceptionOfType(InstanceNotFoundException.class) - .isThrownBy(() -> this.mBeanServer.getObjectInstance(objectName)); + .isThrownBy(() -> this.mBeanServer.getObjectInstance(objectName)); } private Boolean isApplicationReady(ObjectName objectName) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java index 399dd359f9..675cb8cda8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ansi/Ansi8BitColorTests.java @@ -42,17 +42,17 @@ class Ansi8BitColorTests { @Test void foregroundWhenOutsideBoundsThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.foreground(-1)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.foreground(256)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); } @Test void backgroundWhenOutsideBoundsThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.background(-1)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); assertThatIllegalArgumentException().isThrownBy(() -> Ansi8BitColor.background(256)) - .withMessage("Code must be between 0 and 255"); + .withMessage("Code must be between 0 and 255"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java index fec136367f..4f22ff574c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/ApplicationAvailabilityBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -107,7 +107,7 @@ class ApplicationAvailabilityBeanTests { assertThat(this.log.getLogged()).contains("Application availability state LivenessState changed to CORRECT"); AvailabilityChangeEvent.publish(this.context, LivenessState.BROKEN); assertThat(this.log.getLogged()) - .contains("Application availability state LivenessState changed from CORRECT to BROKEN"); + .contains("Application availability state LivenessState changed from CORRECT to BROKEN"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java index 3bcbe70922..86d8c1c5d5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/availability/AvailabilityChangeEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class AvailabilityChangeEventTests { @Test void createWhenStateIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new AvailabilityChangeEvent<>(this.source, null)) - .withMessage("Payload must not be null"); + .withMessage("Payload must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java index 9fbfbcb1c9..81897b33a2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -74,8 +74,9 @@ class SpringApplicationBuilderTests { @Test void profileAndProperties() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .profiles("foo").properties("foo=bar"); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .profiles("foo") + .properties("foo=bar"); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bucket"); @@ -85,8 +86,8 @@ class SpringApplicationBuilderTests { @Test void propertiesAsMap() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .properties(Collections.singletonMap("bar", "foo")); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .properties(Collections.singletonMap("bar", "foo")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @@ -94,8 +95,8 @@ class SpringApplicationBuilderTests { @Test void propertiesAsProperties() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .properties(StringUtils.splitArrayElementsIntoProperties(new String[] { "bar=foo" }, "=")); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .properties(StringUtils.splitArrayElementsIntoProperties(new String[] { "bar=foo" }, "=")); this.context = application.run(); assertThat(this.context.getEnvironment().getProperty("bar")).isEqualTo("foo"); } @@ -103,8 +104,8 @@ class SpringApplicationBuilderTests { @Test void propertiesWithRepeatSeparator() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) - .properties("one=c:\\logging.file.name", "two=a:b", "three:c:\\logging.file.name", "four:a:b"); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)) + .properties("one=c:\\logging.file.name", "two=a:b", "three:c:\\logging.file.name", "four:a:b"); this.context = application.run(); ConfigurableEnvironment environment = this.context.getEnvironment(); assertThat(environment.getProperty("one")).isEqualTo("c:\\logging.file.name"); @@ -116,7 +117,7 @@ class SpringApplicationBuilderTests { @Test void specificApplicationContextFactory() { SpringApplicationBuilder application = new SpringApplicationBuilder().sources(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(StaticApplicationContext.class)); this.context = application.run(); assertThat(this.context).isInstanceOf(StaticApplicationContext.class); } @@ -124,25 +125,25 @@ class SpringApplicationBuilderTests { @Test void parentContextCreationThatIsRunDirectly() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); application.parent(ExampleConfig.class); this.context = application.run("foo.bar=baz"); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).didNotRegisterApplicationContext(this.context); assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()) - .contains("foo.bar=baz"); + .contains("foo.bar=baz"); assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("foo.bar=baz"); } @Test void parentContextCreationThatIsBuiltThenRun() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); application.parent(ExampleConfig.class); this.context = application.build("a=alpha").run("b=bravo"); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).didNotRegisterApplicationContext(this.context); assertThat(this.context.getParent().getBean(ApplicationArguments.class).getNonOptionArgs()).contains("a=alpha"); assertThat(this.context.getBean(ApplicationArguments.class).getNonOptionArgs()).contains("b=bravo"); @@ -151,19 +152,19 @@ class SpringApplicationBuilderTests { @Test void parentContextCreationWithChildShutdown() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)) - .registerShutdownHook(true); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)) + .registerShutdownHook(true); application.parent(ExampleConfig.class); this.context = application.run(); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).registeredApplicationContext(this.context); } @Test void contextWithClassLoader() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); this.context = application.run(); @@ -173,7 +174,7 @@ class SpringApplicationBuilderTests { @Test void parentContextWithClassLoader() { SpringApplicationBuilder application = new SpringApplicationBuilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); + .contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); ClassLoader classLoader = new URLClassLoader(new URL[0], getClass().getClassLoader()); application.resourceLoader(new DefaultResourceLoader(classLoader)); application.parent(ExampleConfig.class); @@ -184,18 +185,20 @@ class SpringApplicationBuilderTests { @Test void parentFirstCreation() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .child(ChildConfig.class); + .child(ChildConfig.class); application.contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); this.context = application.run(); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); assertThat(SpringApplicationShutdownHookInstance.get()).didNotRegisterApplicationContext(this.context); } @Test void parentFirstCreationWithProfileAndDefaultArgs() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") - .properties("transport=redis").child(ChildConfig.class).web(WebApplicationType.NONE); + .properties("transport=redis") + .child(ChildConfig.class) + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node"))).isTrue(); assertThat(this.context.getEnvironment().getProperty("transport")).isEqualTo("redis"); @@ -208,7 +211,10 @@ class SpringApplicationBuilderTests { @Test void parentFirstWithDifferentProfile() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") - .properties("transport=redis").child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); + .properties("transport=redis") + .child(ChildConfig.class) + .profiles("admin") + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); assertThat(this.context.getParent().getEnvironment().acceptsProfiles(Profiles.of("admin"))).isFalse(); @@ -217,9 +223,10 @@ class SpringApplicationBuilderTests { @Test void parentWithDifferentProfile() { SpringApplicationBuilder shared = new SpringApplicationBuilder(ExampleConfig.class).profiles("node") - .properties("transport=redis"); - SpringApplicationBuilder application = shared.child(ChildConfig.class).profiles("admin") - .web(WebApplicationType.NONE); + .properties("transport=redis"); + SpringApplicationBuilder application = shared.child(ChildConfig.class) + .profiles("admin") + .web(WebApplicationType.NONE); shared.profiles("parent"); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); @@ -230,8 +237,12 @@ class SpringApplicationBuilderTests { @Test void parentFirstWithDifferentProfileAndExplicitEnvironment() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .environment(new StandardEnvironment()).profiles("node").properties("transport=redis") - .child(ChildConfig.class).profiles("admin").web(WebApplicationType.NONE); + .environment(new StandardEnvironment()) + .profiles("node") + .properties("transport=redis") + .child(ChildConfig.class) + .profiles("admin") + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(this.context.getEnvironment().acceptsProfiles(Profiles.of("node", "admin"))).isTrue(); // Now they share an Environment explicitly so there's no way to keep the profiles @@ -246,13 +257,13 @@ class SpringApplicationBuilderTests { application.contextFactory(ApplicationContextFactory.ofContextClass(SpyApplicationContext.class)); this.context = application.run(); then(((SpyApplicationContext) this.context).getApplicationContext()).should() - .setParent(any(ApplicationContext.class)); + .setParent(any(ApplicationContext.class)); } @Test void initializersCreatedOnce() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .web(WebApplicationType.NONE); + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(5); } @@ -260,7 +271,8 @@ class SpringApplicationBuilderTests { @Test void initializersCreatedOnceForChild() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .child(ChildConfig.class).web(WebApplicationType.NONE); + .child(ChildConfig.class) + .web(WebApplicationType.NONE); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(6); } @@ -268,8 +280,9 @@ class SpringApplicationBuilderTests { @Test void initializersIncludeDefaults() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .web(WebApplicationType.NONE).initializers((ConfigurableApplicationContext applicationContext) -> { - }); + .web(WebApplicationType.NONE) + .initializers((ConfigurableApplicationContext applicationContext) -> { + }); this.context = application.run(); assertThat(application.application().getInitializers()).hasSize(6); } @@ -277,7 +290,8 @@ class SpringApplicationBuilderTests { @Test void sourcesWithBoundSources() { SpringApplicationBuilder application = new SpringApplicationBuilder().web(WebApplicationType.NONE) - .sources(ExampleConfig.class).properties("spring.main.sources=" + ChildConfig.class.getName()); + .sources(ExampleConfig.class) + .properties("spring.main.sources=" + ChildConfig.class.getName()); this.context = application.run(); this.context.getBean(ExampleConfig.class); this.context.getBean(ChildConfig.class); @@ -286,8 +300,9 @@ class SpringApplicationBuilderTests { @Test void addBootstrapRegistryInitializer() { SpringApplicationBuilder application = new SpringApplicationBuilder(ExampleConfig.class) - .web(WebApplicationType.NONE).addBootstrapRegistryInitializer((context) -> context.addCloseListener( - (event) -> event.getApplicationContext().getBeanFactory().registerSingleton("test", "spring"))); + .web(WebApplicationType.NONE) + .addBootstrapRegistryInitializer((context) -> context.addCloseListener( + (event) -> event.getApplicationContext().getBeanFactory().registerSingleton("test", "spring"))); this.context = application.run(); assertThat(this.context.getBean("test")).isEqualTo("spring"); } @@ -310,7 +325,7 @@ class SpringApplicationBuilderTests { }; SpringApplication application = applicationBuilder.build(); assertThat(application).asInstanceOf(InstanceOfAssertFactories.type(CustomSpringApplication.class)) - .satisfies((customApp) -> assertThat(customApp.resourceLoader).isEqualTo(resourceLoader)); + .satisfies((customApp) -> assertThat(customApp.resourceLoader).isEqualTo(resourceLoader)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java index 884057e21f..7d330faff5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/cloud/CloudPlatformTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -242,7 +242,7 @@ class CloudPlatformTests { Environment environment = getEnvironmentWithEnvVariables(envVars); ((MockEnvironment) environment).setProperty("spring.main.cloud-platform", "none"); assertThat(Stream.of(CloudPlatform.values()).filter((platform) -> platform.isActive(environment))) - .containsExactly(CloudPlatform.NONE); + .containsExactly(CloudPlatform.NONE); } private Environment getEnvironmentWithEnvVariables(Map environmentVariables) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java index 396e7b1d65..fe6a05cc23 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -144,7 +144,7 @@ class ApplicationPidFileWriterTests { System.setProperty("PID_FAIL_ON_WRITE_ERROR", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); assertThatIllegalStateException().isThrownBy(() -> listener.onApplicationEvent(EVENT)) - .withMessageContaining("Cannot create pid file"); + .withMessageContaining("Cannot create pid file"); }); } @@ -154,7 +154,7 @@ class ApplicationPidFileWriterTests { SpringApplicationEvent event = createPreparedEvent("spring.pid.fail-on-write-error", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); assertThatIllegalStateException().isThrownBy(() -> listener.onApplicationEvent(event)) - .withMessageContaining("Cannot create pid file"); + .withMessageContaining("Cannot create pid file"); }); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java index a5e0036bbe..3c76500b41 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,7 @@ class TypeExcludeFilterTests { this.context.refresh(); assertThat(this.context.getBean(ExampleComponent.class)).isNotNull(); assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> this.context.getBean(ExampleFilteredComponent.class)); + .isThrownBy(() -> this.context.getBean(ExampleFilteredComponent.class)); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java index d4515a8b11..71b36adf9e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class ConfigurationsTests { @Test void createWhenClassesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestConfigurations(null)) - .withMessageContaining("Classes must not be null"); + .withMessageContaining("Classes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java index a7db25a324..23022678f5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorPlaceholdersResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -75,8 +75,8 @@ class ConfigDataEnvironmentContributorPlaceholdersResolverTests { ConfigDataEnvironmentContributorPlaceholdersResolver resolver = new ConfigDataEnvironmentContributorPlaceholdersResolver( contributors, null, null, true); assertThatExceptionOfType(InactiveConfigDataAccessException.class) - .isThrownBy(() -> resolver.resolvePlaceholders("${test}")) - .satisfies(propertyNameAndOriginOf("test", "s3")); + .isThrownBy(() -> resolver.resolvePlaceholders("${test}")) + .satisfies(propertyNameAndOriginOf("test", "s3")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java index 2e80f59944..38be31e1a8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -104,7 +104,8 @@ class ConfigDataEnvironmentContributorTests { ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofUnboundImport(null, null, false, configData, 0); assertThat(contributor.getConfigurationPropertySource() - .getConfigurationProperty(ConfigurationPropertyName.of("spring")).getValue()).isEqualTo("boot"); + .getConfigurationProperty(ConfigurationPropertyName.of("spring")) + .getValue()).isEqualTo("boot"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java index 6492cf335f..3dc02259be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -108,7 +108,7 @@ class ConfigDataEnvironmentContributorsTests { @Test void withProcessedImportsWhenHasNoUnprocessedImportsReturnsSameInstance() { ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor - .ofExisting(new MockPropertySource()); + .ofExisting(new MockPropertySource()); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); ConfigDataEnvironmentContributors withProcessedImports = contributors.withProcessedImports(this.importer, @@ -125,7 +125,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); @@ -148,14 +148,14 @@ class ConfigDataEnvironmentContributorsTests { initialImported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a"), false), new ConfigData(Arrays.asList(initialPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(initialLocations))) - .willReturn(initialImported); + .willReturn(initialImported); List secondLocations = Arrays.asList(LOCATION_2); MockPropertySource secondPropertySource = new MockPropertySource(); Map secondImported = new LinkedHashMap<>(); secondImported.put(new ConfigDataResolutionResult(LOCATION_2, new TestConfigDataResource("b"), false), new ConfigData(Arrays.asList(secondPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(secondLocations))) - .willReturn(secondImported); + .willReturn(secondImported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); @@ -174,7 +174,7 @@ class ConfigDataEnvironmentContributorsTests { MockPropertySource existingPropertySource = new MockPropertySource(); existingPropertySource.setProperty("test", "springboot"); ConfigDataEnvironmentContributor existingContributor = ConfigDataEnvironmentContributor - .ofExisting(existingPropertySource); + .ofExisting(existingPropertySource); this.importer = mock(ConfigDataImporter.class); List locations = Arrays.asList(LOCATION_1); MockPropertySource propertySource = new MockPropertySource(); @@ -182,7 +182,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a'"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(existingContributor, contributor)); @@ -202,20 +202,20 @@ class ConfigDataEnvironmentContributorsTests { initialImported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a"), false), new ConfigData(Arrays.asList(initialPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(initialLocations))) - .willReturn(initialImported); + .willReturn(initialImported); List secondLocations = Arrays.asList(LOCATION_2); MockPropertySource secondPropertySource = new MockPropertySource(); Map secondImported = new LinkedHashMap<>(); secondImported.put(new ConfigDataResolutionResult(LOCATION_2, new TestConfigDataResource("b"), false), new ConfigData(Arrays.asList(secondPropertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(secondLocations))) - .willReturn(secondImported); + .willReturn(secondImported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(contributor)); contributors.withProcessedImports(this.importer, this.activationContext); - then(this.importer).should().resolveAndLoad(any(), this.locationResolverContext.capture(), any(), - eq(secondLocations)); + then(this.importer).should() + .resolveAndLoad(any(), this.locationResolverContext.capture(), any(), eq(secondLocations)); ConfigDataLocationResolverContext context = this.locationResolverContext.getValue(); assertThat(context.getParent()).hasToString("a"); } @@ -225,7 +225,7 @@ class ConfigDataEnvironmentContributorsTests { MockPropertySource existingPropertySource = new MockPropertySource(); existingPropertySource.setProperty("test", "springboot"); ConfigDataEnvironmentContributor existingContributor = ConfigDataEnvironmentContributor - .ofExisting(existingPropertySource); + .ofExisting(existingPropertySource); this.importer = mock(ConfigDataImporter.class); List locations = Arrays.asList(LOCATION_1); MockPropertySource propertySource = new MockPropertySource(); @@ -233,7 +233,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a'"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(existingContributor, contributor)); @@ -248,7 +248,7 @@ class ConfigDataEnvironmentContributorsTests { MockPropertySource existingPropertySource = new MockPropertySource(); existingPropertySource.setProperty("test", "springboot"); ConfigDataEnvironmentContributor existingContributor = ConfigDataEnvironmentContributor - .ofExisting(existingPropertySource); + .ofExisting(existingPropertySource); this.importer = mock(ConfigDataImporter.class); List locations = Arrays.asList(LOCATION_1); MockPropertySource propertySource = new MockPropertySource(); @@ -256,7 +256,7 @@ class ConfigDataEnvironmentContributorsTests { imported.put(new ConfigDataResolutionResult(LOCATION_1, new TestConfigDataResource("a'"), false), new ConfigData(Arrays.asList(propertySource))); given(this.importer.resolveAndLoad(eq(this.activationContext), any(), any(), eq(locations))) - .willReturn(imported); + .willReturn(imported); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofInitialImport(LOCATION_1); ConfigDataEnvironmentContributors contributors = new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, Arrays.asList(existingContributor, contributor)); @@ -351,7 +351,7 @@ class ConfigDataEnvironmentContributorsTests { this.bootstrapContext, Arrays.asList(firstContributor, secondContributor)); Binder binder = contributors.getBinder(this.activationContext, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE); assertThatExceptionOfType(BindException.class).isThrownBy(() -> binder.bind("test", String.class)) - .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); + .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); } @Test @@ -368,7 +368,7 @@ class ConfigDataEnvironmentContributorsTests { this.bootstrapContext, Arrays.asList(firstContributor, secondContributor)); Binder binder = contributors.getBinder(this.activationContext, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE); assertThatExceptionOfType(BindException.class).isThrownBy(() -> binder.bind("test", String.class)) - .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); + .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); } @Test @@ -386,7 +386,7 @@ class ConfigDataEnvironmentContributorsTests { this.bootstrapContext, Arrays.asList(firstContributor, secondContributor)); Binder binder = contributors.getBinder(this.activationContext, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE); assertThatExceptionOfType(BindException.class).isThrownBy(() -> binder.bind("test", String.class)) - .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); + .satisfies((ex) -> assertThat(ex.getCause()).isInstanceOf(InactiveConfigDataAccessException.class)); } private ConfigDataEnvironmentContributor createBoundImportContributor(ConfigData configData, diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java index 78c3eee333..45d8eec771 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,13 +47,13 @@ class ConfigDataEnvironmentPostProcessorBootstrapContextIntegrationTests { @Test void bootstrapsApplicationContext() { try (ConfigurableApplicationContext context = this.application - .run("--spring.config.import=classpath:application-bootstrap-registry-integration-tests.properties")) { + .run("--spring.config.import=classpath:application-bootstrap-registry-integration-tests.properties")) { LoaderHelper bean = context.getBean(TestConfigDataBootstrap.LoaderHelper.class); assertThat(bean).isNotNull(); assertThat(bean.getBound()).isEqualTo("igotbound"); assertThat(bean.getProfileBound()).isEqualTo("igotprofilebound"); assertThat(bean.getLocation().getResolverHelper().getLocation()) - .isEqualTo(ConfigDataLocation.of("testbootstrap:test")); + .isEqualTo(ConfigDataLocation.of("testbootstrap:test")); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java index 1d3dbbeca8..0b9f5e58c6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -61,7 +61,7 @@ class ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegra @Test void testWithoutProfile() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=configimportwithprofilespecific"); + .run("--spring.config.name=configimportwithprofilespecific"); String value = context.getEnvironment().getProperty("prop"); assertThat(value).isEqualTo("fromicwps1"); } @@ -69,7 +69,7 @@ class ConfigDataEnvironmentPostProcessorImportCombinedWithProfileSpecificIntegra @Test void testWithProfile() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=configimportwithprofilespecific", "--spring.profiles.active=prod"); + .run("--spring.config.name=configimportwithprofilespecific", "--spring.profiles.active=prod"); String value = context.getEnvironment().getProperty("prop"); assertThat(value).isEqualTo("fromicwps2"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java index 046bdaa5e6..7b2e834f4a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorIntegrationTests.java @@ -145,7 +145,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenMultipleCustomNamesLoadsEachName() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=moreproperties,testproperties"); + .run("--spring.config.name=moreproperties,testproperties"); String property = context.getEnvironment().getProperty("the.property"); assertThat(property).isEqualTo("frompropertiesfile"); } @@ -177,7 +177,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasCustomSpringConfigLocationLoadsAllFromSpecifiedLocation() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application.properties,classpath:testproperties.properties"); + .run("--spring.config.location=classpath:application.properties,classpath:testproperties.properties"); String property1 = context.getEnvironment().getProperty("the.property"); String property2 = context.getEnvironment().getProperty("my.property"); String property3 = context.getEnvironment().getProperty("foo"); @@ -206,13 +206,13 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenProfileSpecificMandatoryLocationDoesNotExistShouldFailWhenProfileActive() { this.application.setAdditionalProfiles("prod"); assertThatExceptionOfType(ConfigDataResourceNotFoundException.class).isThrownBy(() -> this.application - .run("--spring.config.name=testprofiles", "--spring.config.location=classpath:configdata/profiles/")); + .run("--spring.config.name=testprofiles", "--spring.config.location=classpath:configdata/profiles/")); } @Test void runWhenHasActiveProfilesFromMultipleLocationsActivatesProfileFromOneLocation() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:enableprofile.properties,classpath:enableother.properties"); + .run("--spring.config.location=classpath:enableprofile.properties,classpath:enableother.properties"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.getActiveProfiles()).containsExactly("other"); String property = environment.getProperty("other.property"); @@ -252,7 +252,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenHasCommandLinePropertiesLoadsWithCommandLineTakingPrecedence() { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources() - .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); + .addFirst(new SimpleCommandLinePropertySource("--the.property=fromcommandline")); this.application.setEnvironment(environment); ConfigurableApplicationContext context = this.application.run("--spring.config.name=testproperties"); String property = context.getEnvironment().getProperty("the.property"); @@ -408,9 +408,10 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { String property = context.getEnvironment().getProperty("my.property"); assertThat(context.getEnvironment().getActiveProfiles()).contains("dev"); assertThat(property).isEqualTo("fromdevprofile"); - assertThat(context.getEnvironment().getPropertySources()).extracting("name").contains( - "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #0)", - "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #1)"); + assertThat(context.getEnvironment().getPropertySources()).extracting("name") + .contains( + "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #0)", + "Config resource 'class path resource [configdata/profiles/testsetprofiles.yml]' via location 'classpath:configdata/profiles/' (document #1)"); } @Test @@ -428,7 +429,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void loadWhenHasWhitespaceTrims() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=testsetmultiprofileswhitespace"); + .run("--spring.config.name=testsetmultiprofileswhitespace"); assertThat(context.getEnvironment().getActiveProfiles()).containsExactly("dev", "healthcheck"); } @@ -437,7 +438,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { String location = "file:src/test/resources/specificlocation.properties"; ConfigurableApplicationContext context = this.application.run("--spring.config.location=" + location); assertThat(context.getEnvironment()).has(matchingPropertySource("Config resource 'file [" + Strings - .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + "]' via location '" + location + "'")); } @@ -446,7 +447,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { String location = "src/test/resources/specificlocation.properties"; ConfigurableApplicationContext context = this.application.run("--spring.config.location=" + location); assertThat(context.getEnvironment()).has(matchingPropertySource("Config resource 'file [" + Strings - .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + .join(Arrays.asList("src", "test", "resources", "specificlocation.properties"), File.separatorChar) + "]' via location '" + location + "'")); } @@ -480,7 +481,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasAdditionalLocationLoadsWithAdditionalTakingPrecedenceOverDefaultLocation() { ConfigurableApplicationContext context = this.application - .run("--spring.config.additional-location=classpath:override.properties"); + .run("--spring.config.additional-location=classpath:override.properties"); assertThat(context.getEnvironment().getProperty("foo")).isEqualTo("bar"); assertThat(context.getEnvironment().getProperty("value")).isEqualTo("1234"); } @@ -488,7 +489,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenMultipleAdditionalLocationsLoadsWithLastWinning() { ConfigurableApplicationContext context = this.application - .run("--spring.config.additional-location=classpath:override.properties,classpath:some.properties"); + .run("--spring.config.additional-location=classpath:override.properties,classpath:some.properties"); assertThat(context.getEnvironment().getProperty("foo")).isEqualTo("spam"); assertThat(context.getEnvironment().getProperty("value")).isEqualTo("1234"); } @@ -536,9 +537,10 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenConfigLocationHasUnknownFileExtensionFailsFast() { String location = "classpath:application.unknown"; assertThatIllegalStateException().isThrownBy(() -> this.application.run("--spring.config.location=" + location)) - .withMessageContaining("Unable to load config data").withMessageContaining(location) - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("File extension is not known") - .hasMessageContaining("it must end in '/'")); + .withMessageContaining("Unable to load config data") + .withMessageContaining(location) + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("File extension is not known") + .hasMessageContaining("it must end in '/'")); } @Test @@ -551,14 +553,14 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenConfigLocationHasNonOptionalMissingFileDirectoryThrowsResourceNotFoundException() { File location = new File(this.temp, "application.unknown"); assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy(() -> this.application - .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); + .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); } @Test void runWhenConfigLocationHasNonOptionalMissingClasspathDirectoryThrowsLocationNotFoundException() { String location = "classpath:application.unknown/"; assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) - .isThrownBy(() -> this.application.run("--spring.config.location=" + location)); + .isThrownBy(() -> this.application.run("--spring.config.location=" + location)); } @Test @@ -566,13 +568,13 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { File location = new File(this.temp, "application.empty"); location.mkdirs(); assertThatNoException().isThrownBy(() -> this.application - .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); + .run("--spring.config.location=" + StringUtils.cleanPath(location.getAbsolutePath()) + "/")); } @Test void runWhenConfigLocationHasMandatoryDirectoryThatDoesntExistThrowsException() { - assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy( - () -> this.application.run("--spring.config.location=" + StringUtils.cleanPath("invalid/"))); + assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) + .isThrownBy(() -> this.application.run("--spring.config.location=" + StringUtils.cleanPath("invalid/"))); } @Test @@ -580,8 +582,8 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { File location = new File(this.temp, "application.properties"); FileCopyUtils.copy(new byte[0], location); assertThatNoException() - .isThrownBy(() -> this.application.run("--spring.config.location=classpath:/application.properties," - + StringUtils.cleanPath(location.getAbsolutePath()))); + .isThrownBy(() -> this.application.run("--spring.config.location=classpath:/application.properties," + + StringUtils.cleanPath(location.getAbsolutePath()))); } @Test @@ -592,21 +594,21 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenUsingInvalidPropertyThrowsException() { - assertThatExceptionOfType(InvalidConfigDataPropertyException.class).isThrownBy( - () -> this.application.run("--spring.config.location=classpath:invalidproperty.properties")); + assertThatExceptionOfType(InvalidConfigDataPropertyException.class) + .isThrownBy(() -> this.application.run("--spring.config.location=classpath:invalidproperty.properties")); } @Test void runWhenImportUsesPlaceholder() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); + .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); assertThat(context.getEnvironment().getProperty("my.value")).isEqualTo("iwasimported"); } @Test void runWhenImportFromEarlierDocumentUsesPlaceholder() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-placeholder-in-document.properties"); + .run("--spring.config.location=classpath:application-import-with-placeholder-in-document.properties"); assertThat(context.getEnvironment().getProperty("my.value")).isEqualTo("iwasimported"); } @@ -614,9 +616,9 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { void runWhenImportWithProfileVariantOrdersPropertySourcesCorrectly() { this.application.setAdditionalProfiles("dev"); ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-profile-variant.properties"); + .run("--spring.config.location=classpath:application-import-with-profile-variant.properties"); assertThat(context.getEnvironment().getProperty("my.value")) - .isEqualTo("application-import-with-profile-variant-imported-dev"); + .isEqualTo("application-import-with-profile-variant-imported-dev"); } @Test @@ -625,21 +627,21 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { ConfigurableApplicationContext context = this.application.run( "--spring.config.location=classpath:application-import-with-profile-variant-and-direct-profile-import.properties"); assertThat(context.getEnvironment().getProperty("my.value")) - .isEqualTo("application-import-with-profile-variant-imported-dev"); + .isEqualTo("application-import-with-profile-variant-imported-dev"); } @Test void runWhenHasPropertyInProfileDocumentThrowsException() { assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.application.run( "--spring.config.location=classpath:application-import-with-placeholder-in-profile-document.properties")) - .withCauseInstanceOf(InactiveConfigDataAccessException.class); + .withCauseInstanceOf(InactiveConfigDataAccessException.class); } @Test // gh-29386 void runWhenHasPropertyInEarlierProfileDocumentThrowsException() { assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.application.run( "--spring.config.location=classpath:application-import-with-placeholder-in-earlier-profile-document.properties")) - .withCauseInstanceOf(InactiveConfigDataAccessException.class); + .withCauseInstanceOf(InactiveConfigDataAccessException.class); } @Test // gh-29386 @@ -647,7 +649,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { ConfigurableApplicationContext context = this.application.run( "--spring.config.location=classpath:application-import-with-placeholder-in-earlier-document.properties"); assertThat(context.getEnvironment().getProperty("my.value")) - .isEqualTo("application-import-with-placeholder-in-earlier-document-imported"); + .isEqualTo("application-import-with-placeholder-in-earlier-document-imported"); } @Test @@ -665,7 +667,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasIncludedProfilesActivatesProfiles() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-include-profiles.properties"); + .run("--spring.config.location=classpath:application-include-profiles.properties"); assertThat(context.getEnvironment().getActiveProfiles()).containsExactlyInAnyOrder("p1", "p2", "p3", "p4", "p5"); } @@ -673,7 +675,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasIncludedProfilesWithPlaceholderActivatesProfiles() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-include-profiles-with-placeholder.properties"); + .run("--spring.config.location=classpath:application-include-profiles-with-placeholder.properties"); assertThat(context.getEnvironment().getActiveProfiles()).containsExactlyInAnyOrder("p1", "p2", "p3", "p4", "p5"); } @@ -694,7 +696,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenImportingIncludesParentOrigin() { ConfigurableApplicationContext context = this.application - .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); + .run("--spring.config.location=classpath:application-import-with-placeholder.properties"); Binder binder = Binder.get(context.getEnvironment()); List properties = new ArrayList<>(); BindHandler bindHandler = new BindHandler() { @@ -716,8 +718,8 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenHasWildcardLocationLoadsFromAllMatchingLocations() { - ConfigurableApplicationContext context = this.application.run( - "--spring.config.location=file:src/test/resources/config/*/", "--spring.config.name=testproperties"); + ConfigurableApplicationContext context = this.application + .run("--spring.config.location=file:src/test/resources/config/*/", "--spring.config.name=testproperties"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.getProperty("first.property")).isEqualTo("apple"); assertThat(environment.getProperty("second.property")).isEqualTo("ball"); @@ -725,52 +727,52 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test void runWhenOptionalWildcardLocationDoesNotExistDoesNotThrowException() { - assertThatNoException().isThrownBy(() -> this.application.run( - "--spring.config.location=optional:file:src/test/resources/nonexistent/*/testproperties.properties")); + assertThatNoException().isThrownBy(() -> this.application + .run("--spring.config.location=optional:file:src/test/resources/nonexistent/*/testproperties.properties")); } @Test void runWhenMandatoryWildcardLocationDoesNotExistThrowsException() { assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy(() -> this.application - .run("--spring.config.location=file:src/test/resources/nonexistent/*/testproperties.properties")); + .run("--spring.config.location=file:src/test/resources/nonexistent/*/testproperties.properties")); } @Test void runWhenMandatoryWildcardLocationHasEmptyFileDirectory() { assertThatNoException() - .isThrownBy(() -> this.application.run("--spring.config.location=file:src/test/resources/config/*/")); + .isThrownBy(() -> this.application.run("--spring.config.location=file:src/test/resources/config/*/")); } @Test void runWhenMandatoryWildcardLocationHasNoSubdirectories() { - assertThatExceptionOfType(ConfigDataLocationNotFoundException.class).isThrownBy( - () -> this.application.run("--spring.config.location=file:src/test/resources/config/0-empty/*/")) - .withMessage( - "Config data location 'file:src/test/resources/config/0-empty/*/' contains no subdirectories"); + assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) + .isThrownBy( + () -> this.application.run("--spring.config.location=file:src/test/resources/config/0-empty/*/")) + .withMessage("Config data location 'file:src/test/resources/config/0-empty/*/' contains no subdirectories"); } @Test void runWhenHasMandatoryWildcardLocationThatDoesNotExist() { assertThatExceptionOfType(ConfigDataLocationNotFoundException.class) - .isThrownBy(() -> this.application.run("--spring.config.location=file:invalid/*/")); + .isThrownBy(() -> this.application.run("--spring.config.location=file:invalid/*/")); } @Test void runWhenHasOptionalWildcardLocationThatDoesNotExistDoesNotThrow() { assertThatNoException() - .isThrownBy(() -> this.application.run("--spring.config.location=optional:file:invalid/*/")); + .isThrownBy(() -> this.application.run("--spring.config.location=optional:file:invalid/*/")); } @Test void runWhenOptionalWildcardLocationHasNoSubdirectoriesDoesNotThrow() { assertThatNoException().isThrownBy(() -> this.application - .run("--spring.config.location=optional:file:src/test/resources/config/0-empty/*/")); + .run("--spring.config.location=optional:file:src/test/resources/config/0-empty/*/")); } @Test // gh-24990 void runWhenHasProfileSpecificFileWithActiveOnProfileProperty() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=application-activate-on-profile-in-profile-specific-file"); + .run("--spring.config.name=application-activate-on-profile-in-profile-specific-file"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.getProperty("test1")).isEqualTo("test1"); assertThat(environment.getProperty("test2")).isEqualTo("test2"); @@ -779,7 +781,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test // gh-26960 void runWhenHasProfileSpecificImportWithImportImportsSecondProfileSpecificFile() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=application-profile-specific-import-with-import"); + .run("--spring.config.name=application-profile-specific-import-with-import"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.containsProperty("application-profile-specific-import-with-import")).isTrue(); assertThat(environment.containsProperty("application-profile-specific-import-with-import-p1")).isTrue(); @@ -792,7 +794,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test // gh-26960 void runWhenHasProfileSpecificImportWithCustomImportResolvesProfileSpecific() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=application-profile-specific-import-with-custom-import"); + .run("--spring.config.name=application-profile-specific-import-with-custom-import"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.containsProperty("test:boot")).isTrue(); assertThat(environment.containsProperty("test:boot:ps")).isTrue(); @@ -801,7 +803,7 @@ class ConfigDataEnvironmentPostProcessorIntegrationTests { @Test // gh-26593 void runWhenHasFilesInRootAndConfigWithProfiles() { ConfigurableApplicationContext context = this.application - .run("--spring.config.name=file-in-root-and-config-with-profile", "--spring.profiles.active=p1,p2"); + .run("--spring.config.name=file-in-root-and-config-with-profile", "--spring.profiles.active=p1,p2"); ConfigurableEnvironment environment = context.getEnvironment(); assertThat(environment.containsProperty("file-in-root-and-config-with-profile")).isTrue(); assertThat(environment.containsProperty("file-in-root-and-config-with-profile-p1")).isTrue(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java index 1cf66199b1..f54009a0a1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java @@ -92,8 +92,8 @@ class ConfigDataEnvironmentPostProcessorTests { this.application.setAdditionalProfiles("dev"); willReturn(this.configDataEnvironment).given(this.postProcessor).getConfigDataEnvironment(any(), any(), any()); this.postProcessor.postProcessEnvironment(this.environment, this.application); - then(this.postProcessor).should().getConfigDataEnvironment(any(), any(), - this.additionalProfilesCaptor.capture()); + then(this.postProcessor).should() + .getConfigDataEnvironment(any(), any(), this.additionalProfilesCaptor.capture()); then(this.configDataEnvironment).should().processAndApply(); assertThat(this.additionalProfilesCaptor.getValue()).containsExactly("dev"); } @@ -118,7 +118,7 @@ class ConfigDataEnvironmentPostProcessorTests { assertThat(listener.getAddedPropertySources()).isNotEmpty(); assertThat(listener.getProfiles().getActive()).containsExactly("dev"); assertThat(listener.getAddedPropertySources().stream().anyMatch((added) -> hasDevProfile(added.getResource()))) - .isTrue(); + .isTrue(); } private boolean hasDevProfile(ConfigDataResource resource) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java index f183d0c4c9..60e8993606 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentTests.java @@ -72,7 +72,7 @@ class ConfigDataEnvironmentTests { TestConfigDataEnvironment configDataEnvironment = new TestConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); assertThat(configDataEnvironment.getConfigDataLocationResolversBinder().bind("spring", String.class).get()) - .isEqualTo("boot"); + .isEqualTo("boot"); } @Test @@ -85,10 +85,13 @@ class ConfigDataEnvironmentTests { this.environment.getPropertySources().addLast(propertySource3); ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); - List children = configDataEnvironment.getContributors().getRoot() - .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); - Object[] wrapped = children.stream().filter((child) -> child.getKind() == Kind.EXISTING) - .map(ConfigDataEnvironmentContributor::getPropertySource).toArray(); + List children = configDataEnvironment.getContributors() + .getRoot() + .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); + Object[] wrapped = children.stream() + .filter((child) -> child.getKind() == Kind.EXISTING) + .map(ConfigDataEnvironmentContributor::getPropertySource) + .toArray(); assertThat(wrapped[1]).isEqualTo(propertySource1); assertThat(wrapped[2]).isEqualTo(propertySource2); assertThat(wrapped[3]).isEqualTo(propertySource3); @@ -104,10 +107,13 @@ class ConfigDataEnvironmentTests { this.environment.getPropertySources().addLast(propertySource2); ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); - List children = configDataEnvironment.getContributors().getRoot() - .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); - Object[] wrapped = children.stream().filter((child) -> child.getKind() == Kind.EXISTING) - .map(ConfigDataEnvironmentContributor::getPropertySource).toArray(); + List children = configDataEnvironment.getContributors() + .getRoot() + .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); + Object[] wrapped = children.stream() + .filter((child) -> child.getKind() == Kind.EXISTING) + .map(ConfigDataEnvironmentContributor::getPropertySource) + .toArray(); assertThat(wrapped[1]).isEqualTo(propertySource1); assertThat(wrapped[2]).isEqualTo(propertySource2); assertThat(wrapped[3]).isEqualTo(defaultPropertySource); @@ -120,10 +126,14 @@ class ConfigDataEnvironmentTests { this.environment.setProperty("spring.config.import", "i1,i2"); ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); - List children = configDataEnvironment.getContributors().getRoot() - .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); - Object[] imports = children.stream().filter((child) -> child.getKind() == Kind.INITIAL_IMPORT) - .map(ConfigDataEnvironmentContributor::getImports).map(Object::toString).toArray(); + List children = configDataEnvironment.getContributors() + .getRoot() + .getChildren(ImportPhase.BEFORE_PROFILE_ACTIVATION); + Object[] imports = children.stream() + .filter((child) -> child.getKind() == Kind.INITIAL_IMPORT) + .map(ConfigDataEnvironmentContributor::getImports) + .map(Object::toString) + .toArray(); assertThat(imports).containsExactly("[i2]", "[i1]", "[a2]", "[a1]", "[l2]", "[l1]"); } @@ -230,7 +240,7 @@ class ConfigDataEnvironmentTests { }; assertThatExceptionOfType(InactiveConfigDataAccessException.class) - .isThrownBy(configDataEnvironment::processAndApply); + .isThrownBy(configDataEnvironment::processAndApply); } @ParameterizedTest @@ -288,7 +298,7 @@ class ConfigDataEnvironmentTests { ConfigDataEnvironment configDataEnvironment = new ConfigDataEnvironment(this.logFactory, this.bootstrapContext, this.environment, this.resourceLoader, this.additionalProfiles, null); assertThatExceptionOfType(InvalidConfigDataPropertyException.class) - .isThrownBy(() -> configDataEnvironment.processAndApply()); + .isThrownBy(() -> configDataEnvironment.processAndApply()); } @Test @@ -303,7 +313,7 @@ class ConfigDataEnvironmentTests { assertThat(addedPropertySource.getPropertySource().getProperty("spring")).isEqualTo("boot"); assertThat(addedPropertySource.getLocation()).hasToString(getConfigLocation(info)); assertThat(addedPropertySource.getResource().toString()).contains("class path resource") - .contains(info.getTestMethod().get().getName()); + .contains(info.getTestMethod().get().getName()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java index acb996c96b..3d64b09b7f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataImporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -81,15 +81,17 @@ class ConfigDataImporterTests { ConfigData configData1 = new ConfigData(Collections.singleton(new MockPropertySource())); ConfigData configData2 = new ConfigData(Collections.singleton(new MockPropertySource())); given(this.resolvers.resolve(this.locationResolverContext, location1, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); given(this.resolvers.resolve(this.locationResolverContext, location2, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); given(this.loaders.load(this.loaderContext, resource1)).willReturn(configData1); given(this.loaders.load(this.loaderContext, resource2)).willReturn(configData2); ConfigDataImporter importer = new ConfigDataImporter(this.logFactory, ConfigDataNotFoundAction.FAIL, this.resolvers, this.loaders); - Collection loaded = importer.resolveAndLoad(this.activationContext, this.locationResolverContext, - this.loaderContext, Arrays.asList(location1, location2)).values(); + Collection loaded = importer + .resolveAndLoad(this.activationContext, this.locationResolverContext, this.loaderContext, + Arrays.asList(location1, location2)) + .values(); assertThat(loaded).containsExactly(configData2, configData1); } @@ -107,20 +109,22 @@ class ConfigDataImporterTests { ConfigData configData2 = new ConfigData(Collections.singleton(new MockPropertySource())); ConfigData configData3 = new ConfigData(Collections.singleton(new MockPropertySource())); given(this.resolvers.resolve(this.locationResolverContext, location1, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location1, resource1, false))); given(this.resolvers.resolve(this.locationResolverContext, location2, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location2, resource2, false))); given(this.resolvers.resolve(this.locationResolverContext, location3, this.profiles)) - .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location3, resource3, false))); + .willReturn(Collections.singletonList(new ConfigDataResolutionResult(location3, resource3, false))); given(this.loaders.load(this.loaderContext, resource1)).willReturn(configData1); given(this.loaders.load(this.loaderContext, resource2)).willReturn(configData2); given(this.loaders.load(this.loaderContext, resource3)).willReturn(configData3); ConfigDataImporter importer = new ConfigDataImporter(this.logFactory, ConfigDataNotFoundAction.FAIL, this.resolvers, this.loaders); - Collection loaded1and2 = importer.resolveAndLoad(this.activationContext, - this.locationResolverContext, this.loaderContext, locations1and2).values(); - Collection loaded2and3 = importer.resolveAndLoad(this.activationContext, - this.locationResolverContext, this.loaderContext, locations2and3).values(); + Collection loaded1and2 = importer + .resolveAndLoad(this.activationContext, this.locationResolverContext, this.loaderContext, locations1and2) + .values(); + Collection loaded2and3 = importer + .resolveAndLoad(this.activationContext, this.locationResolverContext, this.loaderContext, locations2and3) + .values(); assertThat(loaded1and2).containsExactly(configData2, configData1); assertThat(loaded2and3).containsExactly(configData3); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java index 850d70b285..50b121fcc0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,8 +64,9 @@ class ConfigDataLoadersTests { springFactoriesLoader.add(ConfigDataLoader.class, DeferredLogFactoryConfigDataLoader.class); ConfigDataLoaders loaders = new ConfigDataLoaders(this.logFactory, this.bootstrapContext, springFactoriesLoader); - assertThat(loaders).extracting("loaders").asList() - .satisfies(this::containsValidDeferredLogFactoryConfigDataLoader); + assertThat(loaders).extracting("loaders") + .asList() + .satisfies(this::containsValidDeferredLogFactoryConfigDataLoader); } private void containsValidDeferredLogFactoryConfigDataLoader(List list) { @@ -79,9 +80,10 @@ class ConfigDataLoadersTests { MockSpringFactoriesLoader springFactoriesLoader = new MockSpringFactoriesLoader(); springFactoriesLoader.add(ConfigDataLoader.class, LogConfigDataLoader.class); assertThatIllegalArgumentException() - .isThrownBy(() -> new ConfigDataLoaders(this.logFactory, this.bootstrapContext, springFactoriesLoader)) - .havingCause().isInstanceOf(IllegalArgumentException.class) - .withMessageContaining("use DeferredLogFactory"); + .isThrownBy(() -> new ConfigDataLoaders(this.logFactory, this.bootstrapContext, springFactoriesLoader)) + .havingCause() + .isInstanceOf(IllegalArgumentException.class) + .withMessageContaining("use DeferredLogFactory"); } @Test @@ -111,7 +113,7 @@ class ConfigDataLoadersTests { springFactoriesLoader); TestConfigDataResource location = new TestConfigDataResource("test"); assertThatIllegalStateException().isThrownBy(() -> loaders.load(this.context, location)) - .withMessageContaining("Multiple loaders found for resource 'test'"); + .withMessageContaining("Multiple loaders found for resource 'test'"); } @Test @@ -122,7 +124,7 @@ class ConfigDataLoadersTests { springFactoriesLoader); TestConfigDataResource location = new TestConfigDataResource("test"); assertThatIllegalStateException().isThrownBy(() -> loaders.load(this.context, location)) - .withMessage("No loader found for resource 'test'"); + .withMessage("No loader found for resource 'test'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java index 254326e610..2cfa963d0e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -126,13 +126,13 @@ class ConfigDataLocationBindHandlerTests { ValueObject bound = binder.bind("test", VALUE_OBJECT, this.handler).get(); assertThat(bound.getLocation(0)).hasToString("a"); assertThat(bound.getLocation(0).getOrigin()) - .hasToString("\"test.locations[0]\" from property source \"source\""); + .hasToString("\"test.locations[0]\" from property source \"source\""); assertThat(bound.getLocation(1)).hasToString("b"); assertThat(bound.getLocation(1).getOrigin()) - .hasToString("\"test.locations[1]\" from property source \"source\""); + .hasToString("\"test.locations[1]\" from property source \"source\""); assertThat(bound.getLocation(2)).hasToString("c"); assertThat(bound.getLocation(2).getOrigin()) - .hasToString("\"test.locations[2]\" from property source \"source\""); + .hasToString("\"test.locations[2]\" from property source \"source\""); } static class ValueObject { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java index 3aab910a1f..f12ef6c22c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationNotFoundExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ class ConfigDataLocationNotFoundExceptionTests { @Test void createWhenLocationIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigDataLocationNotFoundException(null)) - .withMessage("Location must not be null"); + .withMessage("Location must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java index ddef7ae332..517b609b14 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationResolversTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -166,8 +166,8 @@ class ConfigDataLocationResolversTests { this.binder, new DefaultResourceLoader(), springFactoriesLoader); ConfigDataLocation location = ConfigDataLocation.of("Missing:test"); assertThatExceptionOfType(UnsupportedConfigDataLocationException.class) - .isThrownBy(() -> resolvers.resolve(this.context, location, null)) - .satisfies((ex) -> assertThat(ex.getLocation()).isEqualTo(location)); + .isThrownBy(() -> resolvers.resolve(this.context, location, null)) + .satisfies((ex) -> assertThat(ex.getLocation()).isEqualTo(location)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHintsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHintsTests.java index 1805514f42..e4a822bd4d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLocationRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,9 +45,9 @@ class ConfigDataLocationRuntimeHintsTests { RuntimeHints hints = new RuntimeHints(); new TestConfigDataLocationRuntimeHints().registerHints(hints, null); assertThat(hints.resources().resourcePatternHints()).singleElement() - .satisfies(includes("application*.properties", "application*.xml", "application*.yaml", - "application*.yml", "config/application*.properties", "config/application*.xml", - "config/application*.yaml", "config/application*.yml")); + .satisfies(includes("application*.properties", "application*.xml", "application*.yaml", "application*.yml", + "config/application*.properties", "config/application*.xml", "config/application*.yaml", + "config/application*.yml")); } @Test @@ -61,8 +61,8 @@ class ConfigDataLocationRuntimeHintsTests { }.registerHints(hints, null); assertThat(hints.resources().resourcePatternHints()).singleElement() - .satisfies(includes("test*.properties", "test*.xml", "test*.yaml", "test*.yml", - "config/test*.properties", "config/test*.xml", "config/test*.yaml", "config/test*.yml")); + .satisfies(includes("test*.properties", "test*.xml", "test*.yaml", "test*.yml", "config/test*.properties", + "config/test*.xml", "config/test*.yaml", "config/test*.yml")); } @Test @@ -75,8 +75,8 @@ class ConfigDataLocationRuntimeHintsTests { } }.registerHints(hints, null); assertThat(hints.resources().resourcePatternHints()).singleElement() - .satisfies(includes("config/application*.properties", "config/application*.xml", - "config/application*.yaml", "config/application*.yml")); + .satisfies(includes("config/application*.properties", "config/application*.xml", "config/application*.yaml", + "config/application*.yml")); } @Test @@ -89,7 +89,7 @@ class ConfigDataLocationRuntimeHintsTests { } }.registerHints(hints, null); assertThat(hints.resources().resourcePatternHints()).singleElement() - .satisfies(includes("application*.conf", "config/application*.conf")); + .satisfies(includes("application*.conf", "config/application*.conf")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java index 78035672ac..9446c98334 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -40,7 +40,7 @@ class ConfigDataNotFoundFailureAnalyzerTests { FailureAnalysis result = this.analyzer.analyze(exception); assertThat(result.getDescription()).isEqualTo("Config data location 'test' does not exist"); assertThat(result.getAction()) - .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); + .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); } @Test @@ -59,7 +59,7 @@ class ConfigDataNotFoundFailureAnalyzerTests { FailureAnalysis result = this.analyzer.analyze(exception); assertThat(result.getDescription()).isEqualTo("Config data location 'test' does not exist"); assertThat(result.getAction()) - .isEqualTo("Check that the value 'test' at origin is correct, or prefix it with 'optional:'"); + .isEqualTo("Check that the value 'test' at origin is correct, or prefix it with 'optional:'"); } @Test @@ -76,12 +76,12 @@ class ConfigDataNotFoundFailureAnalyzerTests { ConfigDataLocation location = ConfigDataLocation.of("test"); ConfigDataResource resource = new TestConfigDataResource("myresource"); ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(resource) - .withLocation(location); + .withLocation(location); FailureAnalysis result = this.analyzer.analyze(exception); assertThat(result.getDescription()) - .isEqualTo("Config data resource 'myresource' via location 'test' does not exist"); + .isEqualTo("Config data resource 'myresource' via location 'test' does not exist"); assertThat(result.getAction()) - .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); + .isEqualTo("Check that the value 'test' is correct, or prefix it with 'optional:'"); } static class TestOrigin implements Origin { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java index 79af43871f..e4027f513a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -199,7 +199,7 @@ class ConfigDataPropertiesTests { Binder binder = new Binder(source); ConfigDataProperties properties = ConfigDataProperties.get(binder); assertThat(properties.getImports().get(1).getOrigin()) - .hasToString("\"spring.config.import\" from property source \"source\""); + .hasToString("\"spring.config.import\" from property source \"source\""); } @Test @@ -211,7 +211,7 @@ class ConfigDataPropertiesTests { Binder binder = new Binder(source); ConfigDataProperties properties = ConfigDataProperties.get(binder); assertThat(properties.getImports().get(1).getOrigin()) - .hasToString("\"spring.config.import[1]\" from property source \"source\""); + .hasToString("\"spring.config.import[1]\" from property source \"source\""); } private Profiles createTestProfiles() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java index 22a330b068..f0273395f5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataResourceNotFoundExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void createWhenResourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigDataResourceNotFoundException(null)) - .withMessage("Resource must not be null"); + .withMessage("Resource must not be null"); } @Test @@ -95,7 +95,7 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void getLocationWhenHasLocationReturnsLocation() { ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(this.resource) - .withLocation(this.location); + .withLocation(this.location); assertThat(exception.getLocation()).isSameAs(this.location); } @@ -108,15 +108,15 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void getReferenceDescriptionWhenHasLocationReturnsDescription() { ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(this.resource) - .withLocation(this.location); + .withLocation(this.location); assertThat(exception.getReferenceDescription()) - .isEqualTo("resource 'mytestresource' via location 'optional:test'"); + .isEqualTo("resource 'mytestresource' via location 'optional:test'"); } @Test void withLocationReturnsNewInstanceWithLocation() { ConfigDataResourceNotFoundException exception = new ConfigDataResourceNotFoundException(this.resource) - .withLocation(this.location); + .withLocation(this.location); assertThat(exception.getLocation()).isSameAs(this.location); } @@ -140,7 +140,7 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void throwIfDoesNotExistWhenFileDoesNotExistThrowsException() { assertThatExceptionOfType(ConfigDataResourceNotFoundException.class) - .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, this.missing)); + .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, this.missing)); } @Test @@ -151,8 +151,8 @@ class ConfigDataResourceNotFoundExceptionTests { @Test void throwIfDoesNotExistWhenResourceDoesNotExistThrowsException() { assertThatExceptionOfType(ConfigDataResourceNotFoundException.class) - .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, - new FileSystemResource(this.missing))); + .isThrownBy(() -> ConfigDataResourceNotFoundException.throwIfDoesNotExist(this.resource, + new FileSystemResource(this.missing))); } static class TestConfigDataResource extends ConfigDataResource { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java index 93e8c7bfd0..f369614468 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,13 +44,13 @@ class ConfigDataTests { @Test void createWhenPropertySourcesIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigData(null)) - .withMessage("PropertySources must not be null"); + .withMessage("PropertySources must not be null"); } @Test void createWhenOptionsIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigData(Collections.emptyList(), (Option[]) null)) - .withMessage("Options must not be null"); + .withMessage("Options must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java index b670bbbbf3..51e88dc73c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLoaderTests.java @@ -64,7 +64,7 @@ class ConfigTreeConfigDataLoaderTests { File missing = this.directory.resolve("missing").toFile(); ConfigTreeConfigDataResource location = new ConfigTreeConfigDataResource(missing.toString()); assertThatExceptionOfType(ConfigDataResourceNotFoundException.class) - .isThrownBy(() -> this.loader.load(this.loaderContext, location)); + .isThrownBy(() -> this.loader.load(this.loaderContext, location)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java index d82cfef327..fbd56b5352 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataLocationResolverTests.java @@ -61,7 +61,7 @@ class ConfigTreeConfigDataLocationResolverTests { ConfigDataLocation.of("configtree:/etc/config/")); assertThat(locations).hasSize(1); assertThat(locations).extracting(Object::toString) - .containsExactly("config tree [" + new File("/etc/config").getAbsolutePath() + "]"); + .containsExactly("config tree [" + new File("/etc/config").getAbsolutePath() + "]"); } @Test @@ -75,9 +75,9 @@ class ConfigTreeConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, ConfigDataLocation.of("configtree:" + this.temp.getAbsolutePath() + "/*/")); assertThat(locations).hasSize(2); - assertThat(locations).extracting(Object::toString).containsExactly( - "config tree [" + directoryA.getAbsolutePath() + "]", - "config tree [" + directoryB.getAbsolutePath() + "]"); + assertThat(locations).extracting(Object::toString) + .containsExactly("config tree [" + directoryA.getAbsolutePath() + "]", + "config tree [" + directoryB.getAbsolutePath() + "]"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java index e0df78d2a7..50f7811acc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigTreeConfigDataResourceTests.java @@ -35,13 +35,13 @@ class ConfigTreeConfigDataResourceTests { @Test void constructorWhenPathStringIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreeConfigDataResource((String) null)) - .withMessage("Path must not be null"); + .withMessage("Path must not be null"); } @Test void constructorWhenPathIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreeConfigDataResource((Path) null)) - .withMessage("Path must not be null"); + .withMessage("Path must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java index c8f90e81d9..748d1e65ce 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,7 @@ class DelegatingApplicationContextInitializerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=missing.madeup.class"); assertThatExceptionOfType(ApplicationContextException.class) - .isThrownBy(() -> this.initializer.initialize(context)); + .isThrownBy(() -> this.initializer.initialize(context)); } @Test @@ -86,7 +86,7 @@ class DelegatingApplicationContextInitializerTests { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + NotSuitableInit.class.getName()); assertThatIllegalArgumentException().isThrownBy(() -> this.initializer.initialize(context)) - .withMessageContaining("generic parameter"); + .withMessageContaining("generic parameter"); } @Order(Ordered.HIGHEST_PRECEDENCE) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java index 61cf3b45e0..284c9377d4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -81,7 +81,7 @@ class DelegatingApplicationListenerTests { @Override public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event - .getApplicationContext(); + .getApplicationContext(); applicationContext.getBeanFactory().registerSingleton("a", "a"); } @@ -93,7 +93,7 @@ class DelegatingApplicationListenerTests { @Override public void onApplicationEvent(ContextRefreshedEvent event) { ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event - .getApplicationContext(); + .getApplicationContext(); assertThat(applicationContext.getBeanFactory().getSingleton("a")).isEqualTo("a"); applicationContext.getBeanFactory().registerSingleton("b", "b"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java index 031411fcc3..7071e437c7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InactiveConfigDataAccessExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -123,10 +123,10 @@ class InactiveConfigDataAccessExceptionTests { given(contributor.getPropertySource()).willReturn((PropertySource) this.propertySource); given(contributor.getResource()).willReturn(this.resource); assertThatExceptionOfType(InactiveConfigDataAccessException.class) - .isThrownBy(() -> InactiveConfigDataAccessException.throwIfPropertyFound(contributor, - ConfigurationPropertyName.of("spring"))) - .withMessage("Inactive property source 'mockProperties' imported from location 'test' " - + "cannot contain property 'spring' [origin: \"spring\" from property source \"mockProperties\"]"); + .isThrownBy(() -> InactiveConfigDataAccessException.throwIfPropertyFound(contributor, + ConfigurationPropertyName.of("spring"))) + .withMessage("Inactive property source 'mockProperties' imported from location 'test' " + + "cannot contain property 'spring' [origin: \"spring\" from property source \"mockProperties\"]"); } private static class TestConfigDataResource extends ConfigDataResource { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java index 0a86faca1e..d9961b02b8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/InvalidConfigDataPropertyExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,20 +49,20 @@ class InvalidConfigDataPropertyExceptionTests { @Test void createHasCorrectMessage() { assertThat(new InvalidConfigDataPropertyException(this.property, false, this.replacement, this.resource)) - .hasMessage( - "Property 'invalid' imported from location 'test' is invalid and should be replaced with 'replacement' [origin: origin]"); + .hasMessage( + "Property 'invalid' imported from location 'test' is invalid and should be replaced with 'replacement' [origin: origin]"); } @Test void createWhenNoLocationHasCorrectMessage() { assertThat(new InvalidConfigDataPropertyException(this.property, false, this.replacement, null)) - .hasMessage("Property 'invalid' is invalid and should be replaced with 'replacement' [origin: origin]"); + .hasMessage("Property 'invalid' is invalid and should be replaced with 'replacement' [origin: origin]"); } @Test void createWhenNoReplacementHasCorrectMessage() { assertThat(new InvalidConfigDataPropertyException(this.property, false, null, this.resource)) - .hasMessage("Property 'invalid' imported from location 'test' is invalid [origin: origin]"); + .hasMessage("Property 'invalid' imported from location 'test' is invalid [origin: origin]"); } @Test @@ -75,8 +75,8 @@ class InvalidConfigDataPropertyExceptionTests { @Test void createWhenProfileSpecificHasCorrectMessage() { ConfigurationProperty property = new ConfigurationProperty(this.invalid, "bad", null); - assertThat(new InvalidConfigDataPropertyException(property, true, null, this.resource)).hasMessage( - "Property 'invalid' imported from location 'test' is invalid in a profile specific resource"); + assertThat(new InvalidConfigDataPropertyException(property, true, null, this.resource)) + .hasMessage("Property 'invalid' imported from location 'test' is invalid in a profile specific resource"); } @Test @@ -106,9 +106,9 @@ class InvalidConfigDataPropertyExceptionTests { propertySource.setProperty("spring.profiles", "a"); ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor.ofExisting(propertySource); assertThatExceptionOfType(InvalidConfigDataPropertyException.class) - .isThrownBy(() -> InvalidConfigDataPropertyException.throwIfPropertyFound(contributor)) - .withMessageStartingWith("Property 'spring.profiles' is invalid and should be replaced with " - + "'spring.config.activate.on-profile'"); + .isThrownBy(() -> InvalidConfigDataPropertyException.throwIfPropertyFound(contributor)) + .withMessageStartingWith("Property 'spring.profiles' is invalid and should be replaced with " + + "'spring.config.activate.on-profile'"); } @Test @@ -128,8 +128,8 @@ class InvalidConfigDataPropertyExceptionTests { private void throwOrWarnWhenWhenHasInvalidProfileSpecificPropertyThrowsException(String name) { ConfigDataEnvironmentContributor contributor = createInvalidProfileSpecificPropertyContributor(name); assertThatExceptionOfType(InvalidConfigDataPropertyException.class) - .isThrownBy(() -> InvalidConfigDataPropertyException.throwIfPropertyFound(contributor)) - .withMessageStartingWith("Property '" + name + "' is invalid in a profile specific resource"); + .isThrownBy(() -> InvalidConfigDataPropertyException.throwIfPropertyFound(contributor)) + .withMessageStartingWith("Property '" + name + "' is invalid in a profile specific resource"); } private ConfigDataEnvironmentContributor createInvalidProfileSpecificPropertyContributor(String name, @@ -145,7 +145,7 @@ class InvalidConfigDataPropertyExceptionTests { @Test void throwOrWarnWhenHasNoInvalidPropertyDoesNothing() { ConfigDataEnvironmentContributor contributor = ConfigDataEnvironmentContributor - .ofExisting(new MockPropertySource()); + .ofExisting(new MockPropertySource()); InvalidConfigDataPropertyException.throwIfPropertyFound(contributor); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java index fa489e3739..c7f2ac4afa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/LocationResourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ class LocationResourceLoaderTests { @Test void getResourceWhenPatternThrowsException() { assertThatIllegalStateException().isThrownBy(() -> this.loader.getResource("spring/boot/*")) - .withMessage("Location 'spring/boot/*' must not be a pattern"); + .withMessage("Location 'spring/boot/*' must not be a pattern"); } @Test @@ -85,27 +85,27 @@ class LocationResourceLoaderTests { @Test void getResourcesWhenNotPatternThrowsException() { assertThatIllegalStateException().isThrownBy(() -> this.loader.getResources("spring/boot", ResourceType.FILE)) - .withMessage("Location 'spring/boot' must be a pattern"); + .withMessage("Location 'spring/boot' must be a pattern"); } @Test void getResourcesWhenLocationStartsWithClasspathWildcardThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> this.loader.getResources("classpath*:spring/boot/*/", ResourceType.FILE)) - .withMessage("Location 'classpath*:spring/boot/*/' cannot use classpath wildcards"); + .isThrownBy(() -> this.loader.getResources("classpath*:spring/boot/*/", ResourceType.FILE)) + .withMessage("Location 'classpath*:spring/boot/*/' cannot use classpath wildcards"); } @Test void getResourcesWhenLocationContainsMultipleWildcardsThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> this.loader.getResources("spring/*/boot/*/", ResourceType.FILE)) - .withMessage("Location 'spring/*/boot/*/' cannot contain multiple wildcards"); + .isThrownBy(() -> this.loader.getResources("spring/*/boot/*/", ResourceType.FILE)) + .withMessage("Location 'spring/*/boot/*/' cannot contain multiple wildcards"); } @Test void getResourcesWhenPatternDoesNotEndWithAsteriskSlashThrowsException() { assertThatIllegalStateException().isThrownBy(() -> this.loader.getResources("spring/boot/*", ResourceType.FILE)) - .withMessage("Location 'spring/boot/*' must end with '*/'"); + .withMessage("Location 'spring/boot/*' must end with '*/'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java index d8623bc9b6..908c4a29c0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLoaderTests.java @@ -52,12 +52,12 @@ class StandardConfigDataLoaderTests { PropertySource source1 = configData.getPropertySources().get(0); PropertySource source2 = configData.getPropertySources().get(1); assertThat(source1.getName()) - .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " - + "via location 'classpath:configdata/yaml/application.yml' (document #0)"); + .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " + + "via location 'classpath:configdata/yaml/application.yml' (document #0)"); assertThat(source1.getProperty("foo")).isEqualTo("bar"); assertThat(source2.getName()) - .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " - + "via location 'classpath:configdata/yaml/application.yml' (document #1)"); + .isEqualTo("Config resource 'class path resource [configdata/yaml/application.yml]' " + + "via location 'classpath:configdata/yaml/application.yml' (document #1)"); assertThat(source2.getProperty("hello")).isEqualTo("world"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java index c94098d4c4..d7430085b0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataLocationResolverTests.java @@ -75,56 +75,60 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations).hasSize(1); assertThat(locations).extracting(Object::toString) - .containsExactly("class path resource [configdata/properties/application.properties]"); + .containsExactly("class path resource [configdata/properties/application.properties]"); } @Test void resolveWhenLocationIsFileResolvesFile() { ConfigDataLocation location = ConfigDataLocation - .of("file:src/test/resources/configdata/properties/application.properties"); + .of("file:src/test/resources/configdata/properties/application.properties"); List locations = this.resolver.resolve(this.context, location); assertThat(locations).hasSize(1); - assertThat(locations).extracting(Object::toString).containsExactly( - filePath("src", "test", "resources", "configdata", "properties", "application.properties")); + assertThat(locations).extracting(Object::toString) + .containsExactly( + filePath("src", "test", "resources", "configdata", "properties", "application.properties")); } @Test void resolveWhenLocationIsFileAndNoMatchingLoaderThrowsException() { ConfigDataLocation location = ConfigDataLocation - .of("file:src/test/resources/configdata/properties/application.unknown"); + .of("file:src/test/resources/configdata/properties/application.unknown"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Unable to load config data from") - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); + .withMessageStartingWith("Unable to load config data from") + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); } @Test void resolveWhenLocationWildcardIsSpecifiedForClasspathLocationThrowsException() { ConfigDataLocation location = ConfigDataLocation.of("classpath*:application.properties"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageContaining("Location 'classpath*:application.properties' cannot use classpath wildcards"); + .withMessageContaining("Location 'classpath*:application.properties' cannot use classpath wildcards"); } @Test void resolveWhenLocationWildcardIsNotBeforeLastSlashThrowsException() { ConfigDataLocation location = ConfigDataLocation.of("file:src/test/resources/*/config/"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Location '").withMessageEndingWith("' must end with '*/'"); + .withMessageStartingWith("Location '") + .withMessageEndingWith("' must end with '*/'"); } @Test void createWhenConfigNameHasWildcardThrowsException() { this.environment.setProperty("spring.config.name", "*/application"); assertThatIllegalStateException() - .isThrownBy(() -> new StandardConfigDataLocationResolver(new DeferredLogs(), this.environmentBinder, - this.resourceLoader)) - .withMessageStartingWith("Config name '").withMessageEndingWith("' cannot contain '*'"); + .isThrownBy(() -> new StandardConfigDataLocationResolver(new DeferredLogs(), this.environmentBinder, + this.resourceLoader)) + .withMessageStartingWith("Config name '") + .withMessageEndingWith("' cannot contain '*'"); } @Test void resolveWhenLocationHasMultipleWildcardsThrowsException() { ConfigDataLocation location = ConfigDataLocation.of("file:src/test/resources/config/**/"); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Location '").withMessageEndingWith("' cannot contain multiple wildcards"); + .withMessageStartingWith("Location '") + .withMessageEndingWith("' cannot contain multiple wildcards"); } @Test @@ -136,9 +140,9 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations).hasSize(3); assertThat(locations).extracting(Object::toString) - .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) - .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) - .doesNotContain(filePath("src", "test", "resources", "config", "3-third", "testproperties.properties")); + .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) + .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) + .doesNotContain(filePath("src", "test", "resources", "config", "3-third", "testproperties.properties")); } @Test @@ -148,10 +152,10 @@ class StandardConfigDataLocationResolverTests { this.resolver = new StandardConfigDataLocationResolver(new DeferredLogs(), this.environmentBinder, this.resourceLoader); List locations = this.resolver.resolve(this.context, location); - assertThat(locations).extracting(Object::toString).containsExactly( - filePath("src", "test", "resources", "config", "0-empty", "testproperties.properties"), - filePath("src", "test", "resources", "config", "1-first", "testproperties.properties"), - filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")); + assertThat(locations).extracting(Object::toString) + .containsExactly(filePath("src", "test", "resources", "config", "0-empty", "testproperties.properties"), + filePath("src", "test", "resources", "config", "1-first", "testproperties.properties"), + filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")); } @Test @@ -163,14 +167,14 @@ class StandardConfigDataLocationResolverTests { @Test void resolveWhenLocationIsWildcardFilesLoadsAllFilesThatMatch() { ConfigDataLocation location = ConfigDataLocation - .of("file:src/test/resources/config/*/testproperties.properties"); + .of("file:src/test/resources/config/*/testproperties.properties"); List locations = this.resolver.resolve(this.context, location); assertThat(locations).hasSize(3); assertThat(locations).extracting(Object::toString) - .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) - .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) - .doesNotContain(filePath("src", "test", "resources", "config", "nested", "3-third", - "testproperties.properties")); + .contains(filePath("src", "test", "resources", "config", "1-first", "testproperties.properties")) + .contains(filePath("src", "test", "resources", "config", "2-second", "testproperties.properties")) + .doesNotContain( + filePath("src", "test", "resources", "config", "nested", "3-third", "testproperties.properties")); } @Test @@ -189,7 +193,7 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations).hasSize(1); assertThat(locations).extracting(Object::toString) - .contains("class path resource [configdata/properties/other.properties]"); + .contains("class path resource [configdata/properties/other.properties]"); } @Test @@ -207,7 +211,7 @@ class StandardConfigDataLocationResolverTests { List locations = this.resolver.resolve(this.context, location); assertThat(locations).hasSize(1); assertThat(locations).extracting(Object::toString) - .contains("class path resource [config/nested/3-third/testproperties.properties]"); + .contains("class path resource [config/nested/3-third/testproperties.properties]"); } @Test @@ -220,8 +224,8 @@ class StandardConfigDataLocationResolverTests { StandardConfigDataResource parent = new StandardConfigDataResource(parentReference, parentResource); given(this.context.getParent()).willReturn(parent); assertThatIllegalStateException().isThrownBy(() -> this.resolver.resolve(this.context, location)) - .withMessageStartingWith("Unable to load config data from 'application.other'") - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); + .withMessageStartingWith("Unable to load config data from 'application.other'") + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageStartingWith("File extension is not known")); } @Test @@ -245,7 +249,7 @@ class StandardConfigDataLocationResolverTests { profiles); assertThat(locations).hasSize(1); assertThat(locations).extracting(Object::toString) - .containsExactly("class path resource [configdata/properties/application-dev.properties]"); + .containsExactly("class path resource [configdata/properties/application-dev.properties]"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java index 8c1734ee2a..56bc44058c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/StandardConfigDataResourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -40,13 +40,13 @@ class StandardConfigDataResourceTests { @Test void createWhenReferenceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new StandardConfigDataResource(null, this.resource)) - .withMessage("Reference must not be null"); + .withMessage("Reference must not be null"); } @Test void createWhenResourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new StandardConfigDataResource(this.reference, null)) - .withMessage("Resource must not be null"); + .withMessage("Resource must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java index 4820905fd7..1f3a673d28 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/TestConfigDataBootstrap.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,8 +47,8 @@ class TestConfigDataBootstrap { @Override public List resolve(ConfigDataLocationResolverContext context, ConfigDataLocation location) { - context.getBootstrapContext().registerIfAbsent(ResolverHelper.class, - InstanceSupplier.from(() -> new ResolverHelper(location))); + context.getBootstrapContext() + .registerIfAbsent(ResolverHelper.class, InstanceSupplier.from(() -> new ResolverHelper(location))); ResolverHelper helper = context.getBootstrapContext().get(ResolverHelper.class); return Collections.singletonList(new Resource(helper)); } @@ -59,8 +59,9 @@ class TestConfigDataBootstrap { @Override public ConfigData load(ConfigDataLoaderContext context, Resource location) throws IOException { - context.getBootstrapContext().registerIfAbsent(LoaderHelper.class, - (bootstrapContext) -> new LoaderHelper(location, () -> bootstrapContext.get(Binder.class))); + context.getBootstrapContext() + .registerIfAbsent(LoaderHelper.class, + (bootstrapContext) -> new LoaderHelper(location, () -> bootstrapContext.get(Binder.class))); LoaderHelper helper = context.getBootstrapContext().get(LoaderHelper.class); context.getBootstrapContext().addCloseListener(helper); return new ConfigData( diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/event/EventPublishingRunListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/event/EventPublishingRunListenerTests.java index 99e2cad3df..3380481104 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/event/EventPublishingRunListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/event/EventPublishingRunListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -76,7 +76,7 @@ class EventPublishingRunListenerTests { ConfigurableEnvironment environment = new StandardEnvironment(); TestApplicationListener lateAddedApplicationListener = new TestApplicationListener(); ApplicationListener listener = (event) -> event.getSpringApplication() - .addListeners(lateAddedApplicationListener); + .addListeners(lateAddedApplicationListener); application.addListeners(listener); EventPublishingRunListener runListener = new EventPublishingRunListener(application, null); runListener.starting(bootstrapContext); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java index de7097e83b..398bc82982 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java @@ -50,7 +50,8 @@ class LoggingApplicationListenerIntegrationTests { @Test void loggingSystemRegisteredInTheContext() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) - .web(WebApplicationType.NONE).run()) { + .web(WebApplicationType.NONE) + .run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.loggingSystem).isNotNull(); } @@ -60,7 +61,9 @@ class LoggingApplicationListenerIntegrationTests { void logFileRegisteredInTheContextWhenApplicable(@TempDir File tempDir) { String logFile = new File(tempDir, "test.log").getAbsolutePath(); try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) - .web(WebApplicationType.NONE).properties("logging.file.name=" + logFile).run()) { + .web(WebApplicationType.NONE) + .properties("logging.file.name=" + logFile) + .run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.logFile).isNotNull(); assertThat(service.logFile).hasToString(logFile); @@ -72,17 +75,20 @@ class LoggingApplicationListenerIntegrationTests { @Test void loggingPerformedDuringChildApplicationStartIsNotLost(CapturedOutput output) { - new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).child(Config.class) - .web(WebApplicationType.NONE).listeners(new ApplicationListener() { + new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE) + .child(Config.class) + .web(WebApplicationType.NONE) + .listeners(new ApplicationListener() { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Override - public void onApplicationEvent(ApplicationStartingEvent event) { - this.logger.info("Child application starting"); - } + @Override + public void onApplicationEvent(ApplicationStartingEvent event) { + this.logger.info("Child application starting"); + } - }).run(); + }) + .run(); assertThat(output).contains("Child application starting"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java index fdc6edaa72..d083114281 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java @@ -177,11 +177,11 @@ class LoggingApplicationListenerTests { @Test void overrideConfigDoesNotExist() { addPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); - assertThatIllegalStateException().isThrownBy( - () -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); + assertThatIllegalStateException() + .isThrownBy(() -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); assertThat(this.output) - .contains("Logging system failed to initialize using configuration from 'doesnotexist.xml'") - .doesNotContain("JoranException"); + .contains("Logging system failed to initialize using configuration from 'doesnotexist.xml'") + .doesNotContain("JoranException"); } @Test @@ -343,8 +343,8 @@ class LoggingApplicationListenerTests { void parseLevelsFails() { this.logger.setLevel(Level.INFO); addPropertiesToEnvironment(this.context, "logging.level.org.springframework.boot=GARBAGE"); - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader())); } @Test @@ -485,7 +485,7 @@ class LoggingApplicationListenerTests { addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${doesnotexist}"); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo("console ${doesnotexist}"); + .isEqualTo("console ${doesnotexist}"); } @Test @@ -493,7 +493,7 @@ class LoggingApplicationListenerTests { addPropertiesToEnvironment(this.context, "logging.pattern.console=console ${pid}"); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)) - .isEqualTo(this.context.getEnvironment().getProperty("logging.pattern.console")); + .isEqualTo(this.context.getEnvironment().getProperty("logging.pattern.console")); } @Test @@ -501,7 +501,7 @@ class LoggingApplicationListenerTests { addPropertiesToEnvironment(this.context, "logging.file.name=" + this.tempDir + "${PID}.log"); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); assertThat(System.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo(this.tempDir + new ApplicationPid().toString() + ".log"); + .isEqualTo(this.tempDir + new ApplicationPid().toString() + ".log"); } @Test @@ -521,8 +521,11 @@ class LoggingApplicationListenerTests { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); this.springApplication.setWebApplicationType(WebApplicationType.NONE); ConfigurableApplicationContext context = this.springApplication.run(); - ApplicationListener listener = this.springApplication.getListeners().stream() - .filter(LoggingApplicationListener.class::isInstance).findFirst().get(); + ApplicationListener listener = this.springApplication.getListeners() + .stream() + .filter(LoggingApplicationListener.class::isInstance) + .findFirst() + .get(); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils.getField(listener, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); @@ -543,7 +546,7 @@ class LoggingApplicationListenerTests { void lowPriorityPropertySourceShouldNotOverrideRootLoggerConfig() { MutablePropertySources propertySources = this.context.getEnvironment().getPropertySources(); propertySources - .addFirst(new MapPropertySource("test1", Collections.singletonMap("logging.level.ROOT", "DEBUG"))); + .addFirst(new MapPropertySource("test1", Collections.singletonMap("logging.level.ROOT", "DEBUG"))); propertySources.addLast(new MapPropertySource("test2", Collections.singletonMap("logging.level.root", "WARN"))); this.listener.initialize(this.context.getEnvironment(), this.context.getClassLoader()); this.logger.debug("testatdebug"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java index 77ee044251..ace6a59c85 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/metrics/buffering/BufferingApplicationStartupTests.java @@ -87,7 +87,7 @@ class BufferingApplicationStartupTests { BufferingApplicationStartup applicationStartup = new BufferingApplicationStartup(2); applicationStartup.start("first").end(); assertThatThrownBy(applicationStartup::startRecording).isInstanceOf(IllegalStateException.class) - .hasMessage("Cannot restart recording once steps have been buffered."); + .hasMessage("Cannot restart recording once steps have been buffered."); } @Test @@ -96,7 +96,7 @@ class BufferingApplicationStartupTests { StartupStep step = applicationStartup.start("first"); step.end(); assertThatThrownBy(() -> step.tag("name", "value")).isInstanceOf(IllegalStateException.class) - .hasMessage("StartupStep has already ended."); + .hasMessage("StartupStep has already ended."); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests.java index 9029dc4959..6ef68b8bd6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,7 +63,7 @@ class ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests { @Test void configurationPropertiesBeanFactoryInitializationAotProcessorIsRegistered() { assertThat(AotServices.factories().load(BeanFactoryInitializationAotProcessor.class)) - .anyMatch(ConfigurationPropertiesBeanFactoryInitializationAotProcessor.class::isInstance); + .anyMatch(ConfigurationPropertiesBeanFactoryInitializationAotProcessor.class::isInstance); } @Test @@ -79,22 +79,22 @@ class ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests { beanFactory.registerSingleton("test", new SampleProperties()); RuntimeHints runtimeHints = process(beanFactory); assertThat(runtimeHints.reflection().getTypeHint(SampleProperties.class)) - .satisfies(javaBeanBinding(SampleProperties.class)); + .satisfies(javaBeanBinding(SampleProperties.class)); } @Test void processJavaBeanConfigurationProperties() { RuntimeHints runtimeHints = process(SampleProperties.class); assertThat(runtimeHints.reflection().getTypeHint(SampleProperties.class)) - .satisfies(javaBeanBinding(SampleProperties.class)); + .satisfies(javaBeanBinding(SampleProperties.class)); } @Test void processJavaBeanConfigurationPropertiesWithSeveralConstructors() throws NoSuchMethodException { RuntimeHints runtimeHints = process(SamplePropertiesWithSeveralConstructors.class); assertThat(runtimeHints.reflection().getTypeHint(SamplePropertiesWithSeveralConstructors.class)) - .satisfies(javaBeanBinding(SamplePropertiesWithSeveralConstructors.class, - SamplePropertiesWithSeveralConstructors.class.getDeclaredConstructor())); + .satisfies(javaBeanBinding(SamplePropertiesWithSeveralConstructors.class, + SamplePropertiesWithSeveralConstructors.class.getDeclaredConstructor())); } @Test @@ -165,58 +165,62 @@ class ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests { void processConfigurationPropertiesWithNestedTypeNotUsedIsIgnored() { RuntimeHints runtimeHints = process(SamplePropertiesWithNested.class); assertThat(runtimeHints.reflection().getTypeHint(SamplePropertiesWithNested.class)) - .satisfies(javaBeanBinding(SamplePropertiesWithNested.class)); + .satisfies(javaBeanBinding(SamplePropertiesWithNested.class)); } @Test void processConfigurationPropertiesWithNestedExternalType() { RuntimeHints runtimeHints = process(SamplePropertiesWithExternalNested.class); assertThat(runtimeHints.reflection().typeHints()) - .anySatisfy(javaBeanBinding(SamplePropertiesWithExternalNested.class)) - .anySatisfy(javaBeanBinding(SampleType.class)).anySatisfy(javaBeanBinding(SampleType.Nested.class)) - .hasSize(3); + .anySatisfy(javaBeanBinding(SamplePropertiesWithExternalNested.class)) + .anySatisfy(javaBeanBinding(SampleType.class)) + .anySatisfy(javaBeanBinding(SampleType.Nested.class)) + .hasSize(3); } @Test void processConfigurationPropertiesWithRecursiveType() { RuntimeHints runtimeHints = process(SamplePropertiesWithRecursive.class); assertThat(runtimeHints.reflection().typeHints()) - .anySatisfy(javaBeanBinding(SamplePropertiesWithRecursive.class)) - .anySatisfy(javaBeanBinding(Recursive.class)).hasSize(2); + .anySatisfy(javaBeanBinding(SamplePropertiesWithRecursive.class)) + .anySatisfy(javaBeanBinding(Recursive.class)) + .hasSize(2); } @Test void processValueObjectConfigurationPropertiesWithRecursiveType() { RuntimeHints runtimeHints = process(SampleImmutablePropertiesWithRecursive.class); assertThat(runtimeHints.reflection().typeHints()) - .anySatisfy(valueObjectBinding(SampleImmutablePropertiesWithRecursive.class, - SampleImmutablePropertiesWithRecursive.class.getDeclaredConstructors()[0])) - .anySatisfy(valueObjectBinding(ImmutableRecursive.class, - ImmutableRecursive.class.getDeclaredConstructors()[0])) - .hasSize(2); + .anySatisfy(valueObjectBinding(SampleImmutablePropertiesWithRecursive.class, + SampleImmutablePropertiesWithRecursive.class.getDeclaredConstructors()[0])) + .anySatisfy( + valueObjectBinding(ImmutableRecursive.class, ImmutableRecursive.class.getDeclaredConstructors()[0])) + .hasSize(2); } @Test void processConfigurationPropertiesWithWellKnownTypes() { RuntimeHints runtimeHints = process(SamplePropertiesWithWellKnownTypes.class); assertThat(runtimeHints.reflection().typeHints()) - .anySatisfy(javaBeanBinding(SamplePropertiesWithWellKnownTypes.class)).hasSize(1); + .anySatisfy(javaBeanBinding(SamplePropertiesWithWellKnownTypes.class)) + .hasSize(1); } @Test void processConfigurationPropertiesWithCrossReference() { RuntimeHints runtimeHints = process(SamplePropertiesWithCrossReference.class); assertThat(runtimeHints.reflection().typeHints()) - .anySatisfy(javaBeanBinding(SamplePropertiesWithCrossReference.class)) - .anySatisfy(javaBeanBinding(CrossReferenceA.class)).anySatisfy(javaBeanBinding(CrossReferenceB.class)) - .hasSize(3); + .anySatisfy(javaBeanBinding(SamplePropertiesWithCrossReference.class)) + .anySatisfy(javaBeanBinding(CrossReferenceA.class)) + .anySatisfy(javaBeanBinding(CrossReferenceB.class)) + .hasSize(3); } @Test void processConfigurationPropertiesWithUnresolvedGeneric() { RuntimeHints runtimeHints = process(SamplePropertiesWithGeneric.class); assertThat(runtimeHints.reflection().typeHints()).anySatisfy(javaBeanBinding(SamplePropertiesWithGeneric.class)) - .anySatisfy(javaBeanBinding(GenericObject.class)); + .anySatisfy(javaBeanBinding(GenericObject.class)); } @Test @@ -232,7 +236,7 @@ class ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests { assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.class)).accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.DoubleNested.class)).accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.DoubleNested.Nested.class)) - .accepts(runtimeHints); + .accepts(runtimeHints); } private Consumer javaBeanBinding(Class type) { @@ -262,7 +266,7 @@ class ConfigurationPropertiesBeanFactoryInitializationAotProcessorTests { return (executableHint) -> { assertThat(executableHint.getName()).isEqualTo(""); assertThat(Arrays.stream(constructor.getParameterTypes()).map(TypeReference::of).toList()) - .isEqualTo(executableHint.getParameterTypes()); + .isEqualTo(executableHint.getParameterTypes()); }; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java index 631727fae5..e0bf3eb7f6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,8 +66,8 @@ class ConfigurationPropertiesBeanRegistrarTests { @Test void registerWhenNoAnnotationThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> this.registrar.register(NoAnnotationConfigurationProperties.class)) - .withMessageContaining("No ConfigurationProperties annotation found"); + .isThrownBy(() -> this.registrar.register(NoAnnotationConfigurationProperties.class)) + .withMessageContaining("No ConfigurationProperties annotation found"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessorTests.java index 263c90d02c..cb1d826c1f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrationAotProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,7 @@ class ConfigurationPropertiesBeanRegistrationAotProcessorTests { @Test void configurationPropertiesBeanRegistrationAotProcessorIsRegistered() { assertThat(AotServices.factories().load(BeanRegistrationAotProcessor.class)) - .anyMatch(ConfigurationPropertiesBeanRegistrationAotProcessor.class::isInstance); + .anyMatch(ConfigurationPropertiesBeanRegistrationAotProcessor.class::isInstance); } @Test @@ -65,7 +65,7 @@ class ConfigurationPropertiesBeanRegistrationAotProcessorTests { RootBeanDefinition beanDefinition = new RootBeanDefinition(String.class); this.beanFactory.registerBeanDefinition("test", beanDefinition); BeanRegistrationAotContribution contribution = this.processor - .processAheadOfTime(RegisteredBean.of(this.beanFactory, "test")); + .processAheadOfTime(RegisteredBean.of(this.beanFactory, "test")); assertThat(contribution).isNull(); } @@ -148,7 +148,7 @@ class ConfigurationPropertiesBeanRegistrationAotProcessorTests { TestCompiler.forSystem().with(generationContext).compile((compiled) -> { GenericApplicationContext freshApplicationContext = new GenericApplicationContext(); ApplicationContextInitializer initializer = compiled - .getInstance(ApplicationContextInitializer.class, className.toString()); + .getInstance(ApplicationContextInitializer.class, className.toString()); initializer.initialize(freshApplicationContext); freshContext.accept(freshApplicationContext); }); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java index 152d01d3a3..9eaffa3d6a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -220,7 +220,7 @@ class ConfigurationPropertiesBeanTests { @Test void forValueObjectWithConstructorBindingAnnotatedClassReturnsBean() { ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean - .forValueObject(ConstructorBindingOnConstructor.class, "valueObjectBean"); + .forValueObject(ConstructorBindingOnConstructor.class, "valueObjectBean"); assertThat(propertiesBean.getName()).isEqualTo("valueObjectBean"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(ConstructorBindingOnConstructor.class); @@ -230,14 +230,14 @@ class ConfigurationPropertiesBeanTests { assertThat(target.getType()).isEqualTo(ResolvableType.forClass(ConstructorBindingOnConstructor.class)); assertThat(target.getValue()).isNull(); assertThat(BindConstructorProvider.DEFAULT.getBindConstructor(ConstructorBindingOnConstructor.class, false)) - .isNotNull(); + .isNotNull(); } @Test @Deprecated(since = "3.0.0", forRemoval = true) void forValueObjectWithDeprecatedConstructorBindingAnnotatedClassReturnsBean() { ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean - .forValueObject(DeprecatedConstructorBindingOnConstructor.class, "valueObjectBean"); + .forValueObject(DeprecatedConstructorBindingOnConstructor.class, "valueObjectBean"); assertThat(propertiesBean.getName()).isEqualTo("valueObjectBean"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(DeprecatedConstructorBindingOnConstructor.class); @@ -245,22 +245,27 @@ class ConfigurationPropertiesBeanTests { assertThat(propertiesBean.getAnnotation()).isNotNull(); Bindable target = propertiesBean.asBindTarget(); assertThat(target.getType()) - .isEqualTo(ResolvableType.forClass(DeprecatedConstructorBindingOnConstructor.class)); + .isEqualTo(ResolvableType.forClass(DeprecatedConstructorBindingOnConstructor.class)); assertThat(target.getValue()).isNull(); assertThat(BindConstructorProvider.DEFAULT.getBindConstructor(DeprecatedConstructorBindingOnConstructor.class, - false)).isNotNull(); + false)) + .isNotNull(); } @Test void forValueObjectWithRecordReturnsBean() { Class implicitConstructorBinding = new ByteBuddy(ClassFileVersion.JAVA_V16).makeRecord() - .name("org.springframework.boot.context.properties.ImplicitConstructorBinding") - .annotateType(AnnotationDescription.Builder.ofType(ConfigurationProperties.class) - .define("prefix", "implicit").build()) - .defineRecordComponent("someString", String.class).defineRecordComponent("someInteger", Integer.class) - .make().load(getClass().getClassLoader()).getLoaded(); + .name("org.springframework.boot.context.properties.ImplicitConstructorBinding") + .annotateType(AnnotationDescription.Builder.ofType(ConfigurationProperties.class) + .define("prefix", "implicit") + .build()) + .defineRecordComponent("someString", String.class) + .defineRecordComponent("someInteger", Integer.class) + .make() + .load(getClass().getClassLoader()) + .getLoaded(); ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean - .forValueObject(implicitConstructorBinding, "implicitBindingRecord"); + .forValueObject(implicitConstructorBinding, "implicitBindingRecord"); assertThat(propertiesBean.getName()).isEqualTo("implicitBindingRecord"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(implicitConstructorBinding); @@ -278,12 +283,11 @@ class ConfigurationPropertiesBeanTests { @Test void forValueObjectWhenJavaBeanBindTypeThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(AnnotatedBean.class, "annotatedBean")) - .withMessage("Bean 'annotatedBean' is not a @ConfigurationProperties value object"); + .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(AnnotatedBean.class, "annotatedBean")) + .withMessage("Bean 'annotatedBean' is not a @ConfigurationProperties value object"); assertThatIllegalStateException() - .isThrownBy( - () -> ConfigurationPropertiesBean.forValueObject(NonAnnotatedBean.class, "nonAnnotatedBean")) - .withMessage("Bean 'nonAnnotatedBean' is not a @ConfigurationProperties value object"); + .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(NonAnnotatedBean.class, "nonAnnotatedBean")) + .withMessage("Bean 'nonAnnotatedBean' is not a @ConfigurationProperties value object"); } @@ -308,9 +312,9 @@ class ConfigurationPropertiesBeanTests { @Test void bindMethodGetWhenConstructorBindingOnMultipleConstructorsThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> BindMethod.get(ConstructorBindingOnMultipleConstructors.class)) - .withMessage(ConstructorBindingOnMultipleConstructors.class.getName() - + " has more than one @ConstructorBinding constructor"); + .isThrownBy(() -> BindMethod.get(ConstructorBindingOnMultipleConstructors.class)) + .withMessage(ConstructorBindingOnMultipleConstructors.class.getName() + + " has more than one @ConstructorBinding constructor"); } @Test @@ -334,7 +338,7 @@ class ConfigurationPropertiesBeanTests { @Test void constructorBindingAndAutowiredConstructorsShouldThrowException() { assertThatIllegalStateException() - .isThrownBy(() -> BindMethod.get(ConstructorBindingAndAutowiredConstructors.class)); + .isThrownBy(() -> BindMethod.get(ConstructorBindingAndAutowiredConstructors.class)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java index f4dc5004cb..c35deaacb0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanRegistrarTests.java @@ -81,7 +81,7 @@ class ConfigurationPropertiesScanRegistrarTests { beanFactory); assertThat(beanFactory.containsBeanDefinition( "foo-org.springframework.boot.context.properties.scan.valid.ConfigurationPropertiesScanConfiguration$FooProperties")) - .isFalse(); + .isFalse(); BeanDefinition aDefinition = beanFactory.getBeanDefinition( "a-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$AProperties"); BeanDefinition bFirstDefinition = beanFactory.getBeanDefinition( diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java index 5609874e90..012e00fac0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesScanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "profile-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyProfileProperties")) - .isTrue(); + .isTrue(); } @Test @@ -78,7 +78,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "profile-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyProfileProperties")) - .isFalse(); + .isFalse(); } @Test @@ -90,7 +90,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "resource-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyResourceProperties")) - .isTrue(); + .isTrue(); } @Test @@ -98,7 +98,7 @@ class ConfigurationPropertiesScanTests { load(TestConfiguration.class); assertThat(this.context.containsBean( "resource-org.springframework.boot.context.properties.scan.valid.a.AScanConfiguration$MyResourceProperties")) - .isFalse(); + .isFalse(); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java index de44144c60..a0c40b65ac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java @@ -182,8 +182,8 @@ class ConfigurationPropertiesTests { void loadWhenHasIgnoreUnknownFieldsFalseAndUnknownFieldsShouldFail() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) + .withCauseInstanceOf(BindException.class); } @Test @@ -191,7 +191,7 @@ class ConfigurationPropertiesTests { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class).isThrownBy( () -> load(IgnoreUnknownFieldsFalseIgnoreInvalidFieldsTrueConfiguration.class, "name=foo", "bar=baz")) - .withCauseInstanceOf(BindException.class); + .withCauseInstanceOf(BindException.class); } @Test @@ -244,7 +244,7 @@ class ConfigurationPropertiesTests { @Test void loadWhenBindingWithoutAndAnnotationShouldFail() { assertThatIllegalStateException().isThrownBy(() -> load(WithoutAndAnnotationConfiguration.class, "name:foo")) - .withMessageContaining("No ConfigurationProperties annotation found"); + .withMessageContaining("No ConfigurationProperties annotation found"); } @Test @@ -356,7 +356,7 @@ class ConfigurationPropertiesTests { void loadWithPropertyPlaceholderValueShouldBind() { load(WithPropertyPlaceholderValueConfiguration.class, "default.value=foo"); WithPropertyPlaceholderValueProperties bean = this.context - .getBean(WithPropertyPlaceholderValueProperties.class); + .getBean(WithPropertyPlaceholderValueProperties.class); assertThat(bean.getValue()).isEqualTo("foo"); } @@ -459,9 +459,10 @@ class ConfigurationPropertiesTests { @Test void loadWhenUsingSystemPropertiesShouldBindToMap() { - this.context.getEnvironment().getPropertySources().addLast( - new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - Collections.singletonMap("TEST_MAP_FOO_BAR", "baz"))); + this.context.getEnvironment() + .getPropertySources() + .addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + Collections.singletonMap("TEST_MAP_FOO_BAR", "baz"))); load(WithComplexMapProperties.class); WithComplexMapProperties bean = this.context.getBean(WithComplexMapProperties.class); assertThat(bean.getMap()).containsOnlyKeys("foo"); @@ -470,9 +471,10 @@ class ConfigurationPropertiesTests { @Test void loadWhenDotsInSystemEnvironmentPropertiesShouldBind() { - this.context.getEnvironment().getPropertySources().addLast( - new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - Collections.singletonMap("com.example.bar", "baz"))); + this.context.getEnvironment() + .getPropertySources() + .addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + Collections.singletonMap("com.example.bar", "baz"))); load(SimplePrefixedProperties.class); SimplePrefixedProperties bean = this.context.getBean(SimplePrefixedProperties.class); assertThat(bean.getBar()).isEqualTo("baz"); @@ -507,29 +509,29 @@ class ConfigurationPropertiesTests { @Test void loadWhenJsr303ConstraintDoesNotMatchShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedJsr303Configuration.class, "description=")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedJsr303Configuration.class, "description=")) + .withCauseInstanceOf(BindException.class); } @Test void loadValidatedOnBeanMethodAndJsr303ConstraintDoesNotMatchShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) + .withCauseInstanceOf(BindException.class); } @Test void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, "properties.description=")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, "properties.description=")) + .withCauseInstanceOf(BindException.class); } @Test void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedButIsValidShouldFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(ValidatedValidNestedJsr303Properties.class)) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(ValidatedValidNestedJsr303Properties.class)) + .withCauseInstanceOf(BindException.class); } @Test @@ -555,8 +557,8 @@ class ConfigurationPropertiesTests { @Test void loadWhenOverridingPropertiesWithPlaceholderResolutionInEnvironmentShouldBindWithOverride() { MutablePropertySources sources = this.context.getEnvironment().getPropertySources(); - sources.addFirst( - new SystemEnvironmentPropertySource("system", Collections.singletonMap("COM_EXAMPLE_BAR", "10"))); + sources + .addFirst(new SystemEnvironmentPropertySource("system", Collections.singletonMap("COM_EXAMPLE_BAR", "10"))); Map source = new HashMap<>(); source.put("com.example.bar", 5); source.put("com.example.foo", "${com.example.bar}"); @@ -665,9 +667,8 @@ class ConfigurationPropertiesTests { @Test void loadWhenConfigurationConverterIsNotQualifiedShouldNotConvert() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy( - () -> prepareConverterContext(NonQualifiedConverterConfiguration.class, PersonProperties.class)) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> prepareConverterContext(NonQualifiedConverterConfiguration.class, PersonProperties.class)) + .withCauseInstanceOf(BindException.class); } @Test @@ -690,7 +691,7 @@ class ConfigurationPropertiesTests { void loadWhenGenericConfigurationConverterIsNotQualifiedShouldNotConvert() { assertThatExceptionOfType(BeanCreationException.class).isThrownBy( () -> prepareConverterContext(NonQualifiedGenericConverterConfiguration.class, PersonProperties.class)) - .withCauseInstanceOf(BindException.class); + .withCauseInstanceOf(BindException.class); } @Test @@ -708,17 +709,17 @@ class ConfigurationPropertiesTests { @Test void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() { assertThatExceptionOfType(Exception.class).isThrownBy(() -> load(WithCustomValidatorConfiguration.class)) - .satisfies((ex) -> { - assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); - }); + .satisfies((ex) -> { + assertThat(ex).hasCauseInstanceOf(BindException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); + }); } @Test void loadWhenHasUnsupportedConfigurationPropertiesValidatorShouldBind() { load(WithUnsupportedCustomValidatorConfiguration.class, "test.foo=bar"); WithSetterThatThrowsValidationExceptionProperties bean = this.context - .getBean(WithSetterThatThrowsValidationExceptionProperties.class); + .getBean(WithSetterThatThrowsValidationExceptionProperties.class); assertThat(bean.getFoo()).isEqualTo("bar"); } @@ -740,18 +741,18 @@ class ConfigurationPropertiesTests { @Test void loadWhenSetterThrowsValidationExceptionShouldFail() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> load(WithSetterThatThrowsValidationExceptionProperties.class, "test.foo=spam")) - .withCauseInstanceOf(BindException.class); + .isThrownBy(() -> load(WithSetterThatThrowsValidationExceptionProperties.class, "test.foo=spam")) + .withCauseInstanceOf(BindException.class); } @Test void loadWhenFailsShouldIncludeAnnotationDetails() { removeSystemProperties(); assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) - .withMessageContaining("Could not bind properties to " - + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " - + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false"); + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz")) + .withMessageContaining("Could not bind properties to " + + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " + + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false"); } @Test @@ -812,9 +813,11 @@ class ConfigurationPropertiesTests { @Test void loadWhenConfigurationPropertiesInjectsAnotherBeanShouldNotFail() { assertThatExceptionOfType(ConfigurationPropertiesBindException.class) - .isThrownBy(() -> load(OtherInjectPropertiesConfiguration.class)).havingCause() - .isInstanceOf(BindException.class).withMessageContaining(OtherInjectedProperties.class.getName()) - .withMessageContaining("Failed to bind properties under 'test'"); + .isThrownBy(() -> load(OtherInjectPropertiesConfiguration.class)) + .havingCause() + .isInstanceOf(BindException.class) + .withMessageContaining(OtherInjectedProperties.class.getName()) + .withMessageContaining("Failed to bind properties under 'test'"); } @Test @@ -840,7 +843,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context - .getBean(ConstructorParameterWithUnitProperties.class); + .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(13)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(14)); @@ -858,7 +861,7 @@ class ConfigurationPropertiesTests { void loadWhenBindingToConstructorParametersWithEmptyDefaultValueShouldBind() { load(ConstructorParameterEmptyDefaultValueConfiguration.class); ConstructorParameterEmptyDefaultValueProperties bean = this.context - .getBean(ConstructorParameterEmptyDefaultValueProperties.class); + .getBean(ConstructorParameterEmptyDefaultValueProperties.class); assertThat(bean.getSet()).isEmpty(); assertThat(bean.getMap()).isEmpty(); assertThat(bean.getArray()).isEmpty(); @@ -869,7 +872,7 @@ class ConfigurationPropertiesTests { void loadWhenBindingToConstructorParametersWithDefaultDataUnitShouldBind() { load(ConstructorParameterWithUnitConfiguration.class); ConstructorParameterWithUnitProperties bean = this.context - .getBean(ConstructorParameterWithUnitProperties.class); + .getBean(ConstructorParameterWithUnitProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(2)); assertThat(bean.getSize()).isEqualTo(DataSize.ofMegabytes(3)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(4)); @@ -884,7 +887,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(ConstructorParameterWithFormatConfiguration.class); ConstructorParameterWithFormatProperties bean = this.context - .getBean(ConstructorParameterWithFormatProperties.class); + .getBean(ConstructorParameterWithFormatProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(12)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(13)); } @@ -896,8 +899,9 @@ class ConfigurationPropertiesTests { source.put("test.duration", "P12D"); sources.addLast(new MapPropertySource("test", source)); assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)).havingCause() - .isInstanceOf(BindException.class); + .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)) + .havingCause() + .isInstanceOf(BindException.class); } @Test @@ -907,15 +911,16 @@ class ConfigurationPropertiesTests { source.put("test.period", "P12D"); sources.addLast(new MapPropertySource("test", source)); assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)).havingCause() - .isInstanceOf(BindException.class); + .isThrownBy(() -> load(ConstructorParameterWithFormatConfiguration.class)) + .havingCause() + .isInstanceOf(BindException.class); } @Test void loadWhenBindingToConstructorParametersWithDefaultDataFormatShouldBind() { load(ConstructorParameterWithFormatConfiguration.class); ConstructorParameterWithFormatProperties bean = this.context - .getBean(ConstructorParameterWithFormatProperties.class); + .getBean(ConstructorParameterWithFormatProperties.class); assertThat(bean.getDuration()).isEqualTo(Duration.ofDays(2)); assertThat(bean.getPeriod()).isEqualTo(Period.ofYears(3)); } @@ -923,10 +928,11 @@ class ConfigurationPropertiesTests { @Test void loadWhenBindingToConstructorParametersShouldValidate() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> load(ConstructorParameterValidationConfiguration.class)).satisfies((ex) -> { - assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); - }); + .isThrownBy(() -> load(ConstructorParameterValidationConfiguration.class)) + .satisfies((ex) -> { + assertThat(ex).hasCauseInstanceOf(BindException.class); + assertThat(ex.getCause()).hasCauseExactlyInstanceOf(BindValidationException.class); + }); } @Test @@ -935,8 +941,8 @@ class ConfigurationPropertiesTests { BasicProperties bean = this.context.getBean(BasicProperties.class); assertThat(bean.name).isEqualTo("test"); bean.name = "override"; - this.context.getBean(ConfigurationPropertiesBindingPostProcessor.class).postProcessBeforeInitialization(bean, - "does-not-exist"); + this.context.getBean(ConfigurationPropertiesBindingPostProcessor.class) + .postProcessBeforeInitialization(bean, "does-not-exist"); assertThat(bean.name).isEqualTo("test"); } @@ -962,7 +968,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(MultiConstructorConfigurationPropertiesConfiguration.class); MultiConstructorConfigurationListProperties bean = this.context - .getBean(MultiConstructorConfigurationListProperties.class); + .getBean(MultiConstructorConfigurationListProperties.class); MultiConstructorConfigurationProperties nested = bean.getNested().get(0); assertThat(nested.getName()).isEqualTo("spring"); assertThat(nested.getAge()).isEqualTo(5); @@ -976,7 +982,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(MultiConstructorConfigurationPropertiesConfiguration.class); MultiConstructorConfigurationListProperties bean = this.context - .getBean(MultiConstructorConfigurationListProperties.class); + .getBean(MultiConstructorConfigurationListProperties.class); MultiConstructorConfigurationProperties nested = bean.getNested().get(0); assertThat(nested.getName()).isEqualTo("spring"); assertThat(nested.getAge()).isZero(); @@ -1014,7 +1020,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(JavaBeanNestedConstructorBindingPropertiesConfiguration.class); JavaBeanNestedConstructorBindingProperties bean = this.context - .getBean(JavaBeanNestedConstructorBindingProperties.class); + .getBean(JavaBeanNestedConstructorBindingProperties.class); assertThat(bean.getNested().getAge()).isEqualTo(5); } @@ -1037,7 +1043,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(JavaBeanNonDefaultConstructorPropertiesConfiguration.class); JavaBeanNonDefaultConstructorProperties bean = this.context - .getBean(JavaBeanNonDefaultConstructorProperties.class); + .getBean(JavaBeanNonDefaultConstructorProperties.class); assertThat(bean.getNested().getAge()).isEqualTo(10); } @@ -1058,7 +1064,7 @@ class ConfigurationPropertiesTests { sources.addLast(new MapPropertySource("test", source)); load(ConstructorBindingWithOuterClassConstructorBoundConfiguration.class); ConstructorBindingWithOuterClassConstructorBoundProperties bean = this.context - .getBean(ConstructorBindingWithOuterClassConstructorBoundProperties.class); + .getBean(ConstructorBindingWithOuterClassConstructorBoundProperties.class); assertThat(bean.getNested().getOuter().getAge()).isEqualTo(5); } @@ -1109,7 +1115,7 @@ class ConfigurationPropertiesTests { this.context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance()); load(WithCustomConverterAndObjectToObjectMethodConfiguration.class, "test.item=foo"); WithCustomConverterAndObjectToObjectMethodProperties bean = this.context - .getBean(WithCustomConverterAndObjectToObjectMethodProperties.class); + .getBean(WithCustomConverterAndObjectToObjectMethodProperties.class); assertThat(bean.getItem().getValue()).isEqualTo("foo"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java index aa51fd0e8e..ed45f33d3d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/EnableConfigurationPropertiesRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,7 +56,7 @@ class EnableConfigurationPropertiesRegistrarTests { void typeWithDefaultConstructorShouldRegisterRootBeanDefinition() { register(TestConfiguration.class); BeanDefinition definition = this.beanFactory - .getBeanDefinition("foo-" + getClass().getName() + "$FooProperties"); + .getBeanDefinition("foo-" + getClass().getName() + "$FooProperties"); assertThat(definition).satisfies(configurationPropertiesBeanDefinition(BindMethod.JAVA_BEAN)); } @@ -64,7 +64,7 @@ class EnableConfigurationPropertiesRegistrarTests { void constructorBoundPropertiesShouldRegisterConfigurationPropertiesBeanDefinition() { register(TestConfiguration.class); BeanDefinition definition = this.beanFactory - .getBeanDefinition("bar-" + getClass().getName() + "$BarProperties"); + .getBeanDefinition("bar-" + getClass().getName() + "$BarProperties"); assertThat(definition).satisfies(configurationPropertiesBeanDefinition(BindMethod.VALUE_OBJECT)); } @@ -72,15 +72,15 @@ class EnableConfigurationPropertiesRegistrarTests { void typeWithMultipleConstructorsShouldRegisterGenericBeanDefinition() { register(TestConfiguration.class); BeanDefinition definition = this.beanFactory - .getBeanDefinition("bing-" + getClass().getName() + "$BingProperties"); + .getBeanDefinition("bing-" + getClass().getName() + "$BingProperties"); assertThat(definition).satisfies(configurationPropertiesBeanDefinition(BindMethod.JAVA_BEAN)); } @Test void typeWithNoAnnotationShouldFail() { assertThatIllegalStateException().isThrownBy(() -> register(InvalidConfiguration.class)) - .withMessageContaining("No ConfigurationProperties annotation found") - .withMessageContaining(EnableConfigurationPropertiesRegistrar.class.getName()); + .withMessageContaining("No ConfigurationProperties annotation found") + .withMessageContaining(EnableConfigurationPropertiesRegistrar.class.getName()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java index 344a3df993..72cb48f621 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/IncompatibleConfigurationFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class IncompatibleConfigurationFailureAnalyzerTests { assertThat(failureAnalysis.getDescription()).contains( "The following configuration properties have incompatible values: [spring.first.key, spring.second.key]"); assertThat(failureAnalysis.getAction()) - .contains("Review the docs for spring.first.key, spring.second.key and change the configured values."); + .contains("Review the docs for spring.first.key, spring.second.key and change the configured values."); } private FailureAnalysis performAnalysis(String... keys) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java index b09d304a36..156d7f6678 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/NotConstructorBoundInjectionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,9 +46,9 @@ class NotConstructorBoundInjectionFailureAnalyzerTests { + " is annotated with @" + ConstructorBinding.class.getSimpleName() + " but it is defined as a regular bean which caused dependency injection to fail."); assertThat(analysis.getAction()) - .isEqualTo("Update your configuration so that " + ConstructorBoundProperties.class.getSimpleName() - + " is defined via @" + ConfigurationPropertiesScan.class.getSimpleName() + " or @" - + EnableConfigurationProperties.class.getSimpleName() + "."); + .isEqualTo("Update your configuration so that " + ConstructorBoundProperties.class.getSimpleName() + + " is defined via @" + ConfigurationPropertiesScan.class.getSimpleName() + " or @" + + EnableConfigurationProperties.class.getSimpleName() + "."); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java index 852bbe8483..a67dd344b7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,13 +63,13 @@ class PropertyMapperTests { @Test void fromWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from((Supplier) null)) - .withMessageContaining("Supplier must not be null"); + .withMessageContaining("Supplier must not be null"); } @Test void toWhenConsumerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").to(null)) - .withMessageContaining("Consumer must not be null"); + .withMessageContaining("Consumer must not be null"); } @Test @@ -89,7 +89,7 @@ class PropertyMapperTests { @Test void asWhenAdapterIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.map.from(() -> "").as(null)) - .withMessageContaining("Adapter must not be null"); + .withMessageContaining("Adapter must not be null"); } @Test @@ -186,8 +186,12 @@ class PropertyMapperTests { @Test void whenWhenCombinedWithAsUsesSourceValue() { Count source = new Count<>(() -> "123"); - Long result = this.map.from(source).when("123"::equals).as(Integer::valueOf).when((v) -> v == 123) - .as(Integer::longValue).toInstance(Long::valueOf); + Long result = this.map.from(source) + .when("123"::equals) + .as(Integer::valueOf) + .when((v) -> v == 123) + .as(Integer::longValue) + .toInstance(Long::valueOf); assertThat(result).isEqualTo(123); assertThat(source.getCount()).isOne(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java index bae6e8963d..6cb182a36f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertySourcesDeducerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -79,8 +79,8 @@ class PropertySourcesDeducerTests { Environment environment = mock(Environment.class); given(applicationContext.getEnvironment()).willReturn(environment); PropertySourcesDeducer deducer = new PropertySourcesDeducer(applicationContext); - assertThatIllegalStateException().isThrownBy(() -> deducer.getPropertySources()).withMessage( - "Unable to obtain PropertySources from PropertySourcesPlaceholderConfigurer or Environment"); + assertThatIllegalStateException().isThrownBy(() -> deducer.getPropertySources()) + .withMessage("Unable to obtain PropertySources from PropertySourcesPlaceholderConfigurer or Environment"); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java index fa076bd8e5..5db7aa1714 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java @@ -73,10 +73,10 @@ class ArrayBinderTests { BindHandler handler = mockBindHandler(); this.binder.bind("foo", INTEGER_LIST, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), - any(), eq(1)); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(INTEGER_LIST), any(), - isA(List.class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), any(), eq(1)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(INTEGER_LIST), any(), isA(List.class)); } @Test @@ -141,14 +141,14 @@ class ArrayBinderTests { source.put("foo[3]", "3"); this.sources.add(source); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", INTEGER_ARRAY)) - .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) - .getUnboundProperties(); - assertThat(unbound).hasSize(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName()).hasToString("foo[3]"); - assertThat(property.getValue()).isEqualTo("3"); - }); + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); + assertThat(unbound).hasSize(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName()).hasToString("foo[3]"); + assertThat(property.getValue()).isEqualTo("3"); + }); } @Test @@ -204,10 +204,10 @@ class ArrayBinderTests { Bindable target = INTEGER_ARRAY; this.binder.bind("foo", target, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), - any(), eq(1)); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), - isA(Integer[].class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo[0]")), eq(Bindable.of(Integer.class)), any(), eq(1)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Integer[].class)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java index 7c010d2ead..93b75241dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BackCompatibilityBinderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -42,8 +42,9 @@ class BackCompatibilityBinderIntegrationTests { StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.singletonMap("FOO_ZK_NODES", "foo")); environment.getPropertySources().addFirst(propertySource); - ExampleCamelCaseBean result = Binder.get(environment).bind("foo", Bindable.of(ExampleCamelCaseBean.class)) - .get(); + ExampleCamelCaseBean result = Binder.get(environment) + .bind("foo", Bindable.of(ExampleCamelCaseBean.class)) + .get(); assertThat(result.getZkNodes()).isEqualTo("foo"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java index 7ee4fb899a..6768f00cff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -70,7 +70,7 @@ class BindConverterTests { void canConvertWhenHasDefaultEditorShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(null); assertThat(bindConverter.canConvert("java.lang.RuntimeException", ResolvableType.forClass(Class.class))) - .isTrue(); + .isTrue(); } @Test @@ -89,7 +89,7 @@ class BindConverterTests { void canConvertWhenHasEditorForCollectionElementShouldReturnTrue() { BindConverter bindConverter = getPropertyEditorOnlyBindConverter(this::registerSampleTypeEditor); assertThat(bindConverter.canConvert("test", ResolvableType.forClassWithGenerics(List.class, SampleType.class))) - .isTrue(); + .isTrue(); } @Test @@ -159,7 +159,7 @@ class BindConverterTests { void convertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldThrowException() { BindConverter bindConverter = BindConverter.get(null, null); assertThatExceptionOfType(ConverterNotFoundException.class) - .isThrownBy(() -> bindConverter.convert("test", ResolvableType.forClass(SampleType.class))); + .isThrownBy(() -> bindConverter.convert("test", ResolvableType.forClass(SampleType.class))); } @Test @@ -185,8 +185,8 @@ class BindConverterTests { BindConverter bindConverter = BindConverter.get(Collections.singletonList(new GenericConversionService()), null); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> bindConverter.convert("com.example.Missing", ResolvableType.forClass(Class.class))) - .withRootCauseInstanceOf(ClassNotFoundException.class); + .isThrownBy(() -> bindConverter.convert("com.example.Missing", ResolvableType.forClass(Class.class))) + .withRootCauseInstanceOf(ClassNotFoundException.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java index 4f54502a48..3612e3c8e9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java @@ -62,7 +62,7 @@ class BindResultTests { void getWhenHasNoValueShouldThrowException() { BindResult result = BindResult.of(null); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(result::get) - .withMessageContaining("No value bound"); + .withMessageContaining("No value bound"); } @Test @@ -81,7 +81,7 @@ class BindResultTests { void ifBoundWhenConsumerIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); assertThatIllegalArgumentException().isThrownBy(() -> result.ifBound(null)) - .withMessageContaining("Consumer must not be null"); + .withMessageContaining("Consumer must not be null"); } @Test @@ -102,7 +102,7 @@ class BindResultTests { void mapWhenMapperIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); assertThatIllegalArgumentException().isThrownBy(() -> result.map(null)) - .withMessageContaining("Mapper must not be null"); + .withMessageContaining("Mapper must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrarTests.java index 11115bf7f4..a36c651f22 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -78,7 +78,7 @@ class BindableRuntimeHintsRegistrarTests { BindableRuntimeHintsRegistrar registrar = new BindableRuntimeHintsRegistrar(); registrar.registerHints(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(BoundConfigurationProperties.class)) - .rejects(runtimeHints); + .rejects(runtimeHints); } @Test @@ -145,7 +145,7 @@ class BindableRuntimeHintsRegistrarTests { RuntimeHints runtimeHints = registerHints(Immutable.class); List typeHints = runtimeHints.reflection().typeHints().toList(); assertThat(typeHints) - .anySatisfy(valueObjectBinding(Immutable.class, Immutable.class.getDeclaredConstructors()[0])); + .anySatisfy(valueObjectBinding(Immutable.class, Immutable.class.getDeclaredConstructors()[0])); assertThat(typeHints).hasSize(1); } @@ -173,55 +173,58 @@ class BindableRuntimeHintsRegistrarTests { void registerHintsWhenHasNestedTypeNotUsedIsIgnored() { RuntimeHints runtimeHints = registerHints(WithNested.class); assertThat(runtimeHints.reflection().getTypeHint(WithNested.class)) - .satisfies(javaBeanBinding(WithNested.class)); + .satisfies(javaBeanBinding(WithNested.class)); } @Test void registerHintsWhenWhenHasNestedExternalType() { RuntimeHints runtimeHints = registerHints(WithExternalNested.class); assertThat(runtimeHints.reflection().typeHints()).anySatisfy(javaBeanBinding(WithExternalNested.class)) - .anySatisfy(javaBeanBinding(SampleType.class)).anySatisfy(javaBeanBinding(SampleType.Nested.class)) - .hasSize(3); + .anySatisfy(javaBeanBinding(SampleType.class)) + .anySatisfy(javaBeanBinding(SampleType.Nested.class)) + .hasSize(3); } @Test void registerHintsWhenWhenHasRecursiveType() { RuntimeHints runtimeHints = registerHints(WithRecursive.class); assertThat(runtimeHints.reflection().typeHints()).anySatisfy(javaBeanBinding(WithRecursive.class)) - .anySatisfy(javaBeanBinding(Recursive.class)).hasSize(2); + .anySatisfy(javaBeanBinding(Recursive.class)) + .hasSize(2); } @Test void registerHintsWhenValueObjectWithRecursiveType() { RuntimeHints runtimeHints = registerHints(ImmutableWithRecursive.class); assertThat(runtimeHints.reflection().typeHints()) - .anySatisfy(valueObjectBinding(ImmutableWithRecursive.class, - ImmutableWithRecursive.class.getDeclaredConstructors()[0])) - .anySatisfy(valueObjectBinding(ImmutableRecursive.class, - ImmutableRecursive.class.getDeclaredConstructors()[0])) - .hasSize(2); + .anySatisfy(valueObjectBinding(ImmutableWithRecursive.class, + ImmutableWithRecursive.class.getDeclaredConstructors()[0])) + .anySatisfy( + valueObjectBinding(ImmutableRecursive.class, ImmutableRecursive.class.getDeclaredConstructors()[0])) + .hasSize(2); } @Test void registerHintsWhenHasWellKnownTypes() { RuntimeHints runtimeHints = registerHints(WithWellKnownTypes.class); assertThat(runtimeHints.reflection().typeHints()).anySatisfy(javaBeanBinding(WithWellKnownTypes.class)) - .hasSize(1); + .hasSize(1); } @Test void registerHintsWhenHasCrossReference() { RuntimeHints runtimeHints = registerHints(WithCrossReference.class); assertThat(runtimeHints.reflection().typeHints()).anySatisfy(javaBeanBinding(WithCrossReference.class)) - .anySatisfy(javaBeanBinding(CrossReferenceA.class)).anySatisfy(javaBeanBinding(CrossReferenceB.class)) - .hasSize(3); + .anySatisfy(javaBeanBinding(CrossReferenceA.class)) + .anySatisfy(javaBeanBinding(CrossReferenceB.class)) + .hasSize(3); } @Test void pregisterHintsWhenHasUnresolvedGeneric() { RuntimeHints runtimeHints = registerHints(WithGeneric.class); assertThat(runtimeHints.reflection().typeHints()).anySatisfy(javaBeanBinding(WithGeneric.class)) - .anySatisfy(javaBeanBinding(GenericObject.class)); + .anySatisfy(javaBeanBinding(GenericObject.class)); } @Test @@ -237,7 +240,7 @@ class BindableRuntimeHintsRegistrarTests { assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.class)).accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.DoubleNested.class)).accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.DoubleNested.Nested.class)) - .accepts(runtimeHints); + .accepts(runtimeHints); } private Consumer javaBeanBinding(Class type) { @@ -267,7 +270,7 @@ class BindableRuntimeHintsRegistrarTests { return (executableHint) -> { assertThat(executableHint.getName()).isEqualTo(""); assertThat(Arrays.stream(constructor.getParameterTypes()).map(TypeReference::of).toList()) - .isEqualTo(executableHint.getParameterTypes()); + .isEqualTo(executableHint.getParameterTypes()); }; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java index f998902d42..5409a2cbf3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java @@ -42,13 +42,13 @@ class BindableTests { @Test void ofClassWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((Class) null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test void ofTypeWhenTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> Bindable.of((ResolvableType) null)) - .withMessageContaining("Type must not be null"); + .withMessageContaining("Type must not be null"); } @Test @@ -78,14 +78,14 @@ class BindableTests { @Test void ofTypeWithExistingValueShouldSetTypeAndExistingValue() { assertThat(Bindable.of(ResolvableType.forClass(String.class)).withExistingValue("foo").getValue().get()) - .isEqualTo("foo"); + .isEqualTo("foo"); } @Test void ofTypeWhenExistingValueIsNotInstanceOfTypeShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123)) - .withMessageContaining("ExistingValue must be an instance of " + String.class.getName()); + .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123)) + .withMessageContaining("ExistingValue must be an instance of " + String.class.getName()); } @Test @@ -131,7 +131,7 @@ class BindableTests { void getAnnotationWhenMatchShouldReturnAnnotation() { Test annotation = AnnotationUtils.synthesizeAnnotation(Test.class); assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotation(Test.class)) - .isSameAs(annotation); + .isSameAs(annotation); } @Test @@ -145,8 +145,8 @@ class BindableTests { Annotation annotation = AnnotationUtils.synthesizeAnnotation(TestAnnotation.class); Bindable bindable = Bindable.of(String.class).withExistingValue("foo").withAnnotations(annotation); assertThat(bindable.toString()) - .contains("type = java.lang.String, value = 'provided', annotations = array[" - + "@org.springframework.boot.context.properties.bind.BindableTests.TestAnnotation()]"); + .contains("type = java.lang.String, value = 'provided', annotations = array[" + + "@org.springframework.boot.context.properties.bind.BindableTests.TestAnnotation()]"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java index 3660c62faf..e527e2792e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java @@ -73,38 +73,40 @@ class BinderTests { @Test void createWhenSourcesIsNullArrayShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder((ConfigurationPropertySource[]) null)) - .withMessageContaining("Sources must not be null"); + .withMessageContaining("Sources must not be null"); } @Test void createWhenSourcesIsNullIterableShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder((Iterable) null)) - .withMessageContaining("Sources must not be null"); + .withMessageContaining("Sources must not be null"); } @Test void createWhenArraySourcesContainsNullElementShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder(new ConfigurationPropertySource[] { null })) - .withMessageContaining("Sources must not contain null elements"); + .withMessageContaining("Sources must not contain null elements"); } @Test void createWhenIterableSourcesContainsNullElementShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new Binder(Collections.singletonList(null))) - .withMessageContaining("Sources must not contain null elements"); + .withMessageContaining("Sources must not contain null elements"); } @Test void bindWhenNameIsNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, - Bindable.of(String.class), BindHandler.DEFAULT)).withMessageContaining("Name must not be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, Bindable.of(String.class), + BindHandler.DEFAULT)) + .withMessageContaining("Name must not be null"); } @Test void bindWhenTargetIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), null, BindHandler.DEFAULT)) - .withMessageContaining("Target must not be null"); + .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), null, BindHandler.DEFAULT)) + .withMessageContaining("Target must not be null"); } @Test @@ -224,10 +226,10 @@ class BinderTests { Bindable target = Bindable.of(JavaBean.class); this.binder.bind("foo", target, handler); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), - any(), eq("bar")); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), - isA(JavaBean.class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), any(), eq("bar")); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(JavaBean.class)); } @Test @@ -238,18 +240,18 @@ class BinderTests { Bindable target = Bindable.of(JavaBean.class); binder.bind("foo", target); InOrder inOrder = inOrder(handler); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), - any(), eq("bar")); - inOrder.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), - isA(JavaBean.class)); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.value")), eq(Bindable.of(String.class)), any(), eq("bar")); + inOrder.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(JavaBean.class)); } @Test void bindWhenHasMalformedDateShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo", "2014-04-01T01:30:00.000-05:00")); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class))) - .withCauseInstanceOf(ConversionFailedException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class))) + .withCauseInstanceOf(ConversionFailedException.class); } @Test @@ -300,7 +302,7 @@ class BinderTests { source.put("value", "hello"); source.put("", "bar"); Iterable propertySources = ConfigurationPropertySources - .from(new MapPropertySource("test", source)); + .from(new MapPropertySource("test", source)); propertySources.forEach(this.sources::add); Bindable target = Bindable.of(JavaBean.class); JavaBean result = this.binder.bind("", target).get(); @@ -346,7 +348,7 @@ class BinderTests { @Test void bindToJavaBeanWithPublicConstructorWhenHasBindRestriction() { Bindable bindable = Bindable.of(JavaBeanWithPublicConstructor.class) - .withBindRestrictions(BindRestriction.NO_DIRECT_PROPERTY); + .withBindRestrictions(BindRestriction.NO_DIRECT_PROPERTY); JavaBeanWithPublicConstructor result = bindToJavaBeanWithPublicConstructor(bindable); assertThat(result.getValue()).isEqualTo("setter"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java index 08bfc4f13e..8d3ca49f12 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java @@ -87,7 +87,7 @@ class CollectionBinderTests { source.put("foo[1][1]", "4"); this.sources.add(source); Bindable>> target = Bindable - .of(ResolvableType.forClassWithGenerics(List.class, INTEGER_LIST.getType())); + .of(ResolvableType.forClassWithGenerics(List.class, INTEGER_LIST.getType())); List> result = this.binder.bind("foo", target).get(); assertThat(result).hasSize(2); assertThat(result.get(0)).containsExactly(1, 2); @@ -113,14 +113,14 @@ class CollectionBinderTests { source.put("foo[3]", "3"); this.sources.add(source); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", INTEGER_LIST)) - .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) - .getUnboundProperties(); - assertThat(unbound).hasSize(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName()).hasToString("foo[3]"); - assertThat(property.getValue()).isEqualTo("3"); - }); + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); + assertThat(unbound).hasSize(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName()).hasToString("foo[3]"); + assertThat(property.getValue()).isEqualTo("3"); + }); } @Test @@ -132,14 +132,14 @@ class CollectionBinderTests { this.sources.add(source); Bindable> target = Bindable.listOf(JavaBean.class); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", target)) - .satisfies((ex) -> { - Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) - .getUnboundProperties(); - assertThat(unbound).hasSize(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName()).hasToString("foo[4].value"); - assertThat(property.getValue()).isEqualTo("4"); - }); + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex.getCause()) + .getUnboundProperties(); + assertThat(unbound).hasSize(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName()).hasToString("foo[4].value"); + assertThat(property.getValue()).isEqualTo("4"); + }); } @Test @@ -307,7 +307,8 @@ class CollectionBinderTests { source.put("foo.items", "a,b,c,c"); this.sources.add(source); ExampleCustomNoDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomNoDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomNoDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).hasSize(4); assertThat(result.getItems()).containsExactly("a", "b", "c", "c"); } @@ -319,7 +320,8 @@ class CollectionBinderTests { source.put("foo.items", "a,b,c,c"); this.sources.add(source); ExampleCustomWithDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomWithDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomWithDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).hasSize(4); assertThat(result.getItems()).containsExactly("a", "b", "c", "c"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProviderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProviderTests.java index 6d09fe98a5..75042fd921 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProviderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/DefaultBindConstructorProviderTests.java @@ -73,9 +73,9 @@ class DefaultBindConstructorProviderTests { @Test void getBindConstructorWhenHasTwoConstructorsWithOneAutowiredAndOneConstructorBindingThrowsException() { assertThatIllegalStateException() - .isThrownBy(() -> this.provider - .getBindConstructor(TwoConstructorsWithOneAutowiredAndOneConstructorBinding.class, false)) - .withMessageContaining("declares @ConstructorBinding and @Autowired"); + .isThrownBy(() -> this.provider + .getBindConstructor(TwoConstructorsWithOneAutowiredAndOneConstructorBinding.class, false)) + .withMessageContaining("declares @ConstructorBinding and @Autowired"); } @Test @@ -88,9 +88,8 @@ class DefaultBindConstructorProviderTests { @Test void getBindConstructorWhenHasTwoConstructorsWithBothConstructorBindingThrowsException() { assertThatIllegalStateException() - .isThrownBy( - () -> this.provider.getBindConstructor(TwoConstructorsWithBothConstructorBinding.class, false)) - .withMessageContaining("has more than one @ConstructorBinding"); + .isThrownBy(() -> this.provider.getBindConstructor(TwoConstructorsWithBothConstructorBinding.class, false)) + .withMessageContaining("has more than one @ConstructorBinding"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java index 3dfad6341a..1778d6e80e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java @@ -83,7 +83,7 @@ class JavaBeanBinderTests { source.put("enum-value", "foo-bar"); this.sources.add(source); ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), Bindable.of(ExampleValueBean.class)) - .get(); + .get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.getStringValue()).isEqualTo("foo"); @@ -100,7 +100,8 @@ class JavaBeanBinderTests { this.sources.add(source); ExampleValueBean bean = new ExampleValueBean(); ExampleValueBean boundBean = this.binder - .bind("foo", Bindable.of(ExampleValueBean.class).withExistingValue(bean)).get(); + .bind("foo", Bindable.of(ExampleValueBean.class).withExistingValue(bean)) + .get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); @@ -138,7 +139,8 @@ class JavaBeanBinderTests { ExampleDefaultsBean bean = new ExampleDefaultsBean(); bean.setFoo(888); ExampleDefaultsBean boundBean = this.binder - .bind("foo", Bindable.of(ExampleDefaultsBean.class).withExistingValue(bean)).get(); + .bind("foo", Bindable.of(ExampleDefaultsBean.class).withExistingValue(bean)) + .get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getFoo()).isEqualTo(888); assertThat(bean.getBar()).isEqualTo(999); @@ -171,8 +173,8 @@ class JavaBeanBinderTests { source.put("foo.list[2]", "bar-baz"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleListBean.class))) - .withCauseInstanceOf(UnboundConfigurationPropertiesException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleListBean.class))) + .withCauseInstanceOf(UnboundConfigurationPropertiesException.class); } @Test @@ -201,7 +203,8 @@ class JavaBeanBinderTests { source.put("foo.collection", "foo-bar|bar-baz"); this.sources.add(source); ExampleCollectionBeanWithDelimiter bean = this.binder - .bind("foo", Bindable.of(ExampleCollectionBeanWithDelimiter.class)).get(); + .bind("foo", Bindable.of(ExampleCollectionBeanWithDelimiter.class)) + .get(); assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -212,7 +215,7 @@ class JavaBeanBinderTests { source.put("foo.map.bar-baz", "2"); this.sources.add(source); ExampleMapBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleMapBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getMap()).containsExactly(entry(ExampleEnum.FOO_BAR, 1), entry(ExampleEnum.BAR_BAZ, 2)); } @@ -223,7 +226,7 @@ class JavaBeanBinderTests { source.put("foo.list[1]", "bar-baz"); this.sources.add(source); ExampleListBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleListBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getList()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -234,7 +237,7 @@ class JavaBeanBinderTests { source.put("foo.set[1]", "bar-baz"); this.sources.add(source); ExampleSetBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleSetBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getSet()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -245,7 +248,8 @@ class JavaBeanBinderTests { source.put("foo.collection[1]", "bar-baz"); this.sources.add(source); ExampleCollectionBeanWithoutSetter bean = this.binder - .bind("foo", Bindable.of(ExampleCollectionBeanWithoutSetter.class)).get(); + .bind("foo", Bindable.of(ExampleCollectionBeanWithoutSetter.class)) + .get(); assertThat(bean.getCollection()).containsExactly(ExampleEnum.FOO_BAR, ExampleEnum.BAR_BAZ); } @@ -267,7 +271,8 @@ class JavaBeanBinderTests { source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); ExampleNestedBeanWithoutSetterOrType bean = this.binder - .bind("foo", Bindable.of(ExampleNestedBeanWithoutSetterOrType.class)).get(); + .bind("foo", Bindable.of(ExampleNestedBeanWithoutSetterOrType.class)) + .get(); ExampleValueBean valueBean = (ExampleValueBean) bean.getValueBean(); assertThat(valueBean.getIntValue()).isEqualTo(123); assertThat(valueBean.getStringValue()).isEqualTo("foo"); @@ -293,7 +298,7 @@ class JavaBeanBinderTests { source.put("foo.value-bean.string-value", "foo"); this.sources.add(source); ExampleNestedBeanWithoutSetter bean = this.binder.bind("foo", Bindable.of(ExampleNestedBeanWithoutSetter.class)) - .get(); + .get(); assertThat(bean.getValueBean().getIntValue()).isEqualTo(123); assertThat(bean.getValueBean().getStringValue()).isEqualTo("foo"); } @@ -304,7 +309,7 @@ class JavaBeanBinderTests { source.put("foo.nested.foo", "bar"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class))); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class))); } @Test @@ -361,7 +366,8 @@ class JavaBeanBinderTests { this.sources.add(source); ExampleWithNonDefaultConstructor bean = new ExampleWithNonDefaultConstructor("faf"); ExampleWithNonDefaultConstructor boundBean = binder - .bind("foo", Bindable.of(ExampleWithNonDefaultConstructor.class).withExistingValue(bean)).get(); + .bind("foo", Bindable.of(ExampleWithNonDefaultConstructor.class).withExistingValue(bean)) + .get(); assertThat(boundBean).isSameAs(bean); assertThat(bean.getValue()).isEqualTo("bar"); } @@ -381,7 +387,7 @@ class JavaBeanBinderTests { void bindToClassWhenPropertyCannotBeConvertedShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo.int-value", "foo")); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); } @Test @@ -444,7 +450,7 @@ class JavaBeanBinderTests { source.put("foo.date", "2014-04-01"); this.sources.add(source); ConverterAnnotatedExampleBean bean = this.binder.bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)) - .get(); + .get(); assertThat(bean.getDate()).hasToString("2014-04-01"); } @@ -455,7 +461,7 @@ class JavaBeanBinderTests { source.put("foo.value", "java.lang.RuntimeException"); this.sources.add(source); ExampleWithPropertyEditorType bean = this.binder.bind("foo", Bindable.of(ExampleWithPropertyEditorType.class)) - .get(); + .get(); assertThat(bean.getValue()).isEqualTo(RuntimeException.class); } @@ -465,7 +471,7 @@ class JavaBeanBinderTests { source.put("foo.name", "something"); this.sources.add(source); ExampleWithInvalidAccessors bean = this.binder.bind("foo", Bindable.of(ExampleWithInvalidAccessors.class)) - .get(); + .get(); assertThat(bean.getName()).isEqualTo("something"); } @@ -499,7 +505,7 @@ class JavaBeanBinderTests { source.put("foo.property", "some string"); this.sources.add(source); PropertyWithOverloadedSetter bean = this.binder.bind("foo", Bindable.of(PropertyWithOverloadedSetter.class)) - .get(); + .get(); assertThat(bean.getProperty()).isEqualTo("some string"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java index 79323629bf..7b86c96920 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java @@ -131,7 +131,8 @@ class MapBinderTests { source.put("faf.far.bin", "x"); this.sources.add(source); Map> result = this.binder - .bind("foo", Bindable.>>of(type)).get(); + .bind("foo", Bindable.>>of(type)) + .get(); assertThat(result).hasSize(2); assertThat(result.get("bar")).containsEntry("baz", 1).containsEntry("bin", 2); assertThat(result.get("far")).containsEntry("baz", 3).containsEntry("bin", 4); @@ -301,7 +302,7 @@ class MapBinderTests { source.put("foo.ccc.ddd.eee", "bazboo"); this.sources.add(source); Map result = this.binder.bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)) - .get(); + .get(); assertThat(result).hasSize(3); assertThat(result).containsEntry("aaa.bbb.ccc", ExampleEnum.FOO_BAR); assertThat(result).containsEntry("bbb.ccc.ddd", ExampleEnum.BAR_BAZ); @@ -316,7 +317,7 @@ class MapBinderTests { this.sources.add(source); this.binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(environment)); Map result = this.binder.bind("foo", Bindable.mapOf(String.class, ExampleEnum.class)) - .get(); + .get(); assertThat(result).containsEntry("aaa.bbb.ccc", ExampleEnum.BAZ_BOO); } @@ -335,8 +336,8 @@ class MapBinderTests { Bindable> target = STRING_INTEGER_MAP; this.binder.bind("foo", target, handler); InOrder ordered = inOrder(handler); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(Integer.class)), - any(), eq(1)); + ordered.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(Integer.class)), any(), eq(1)); ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Map.class)); } @@ -348,8 +349,9 @@ class MapBinderTests { this.binder.bind("foo", target, handler); InOrder ordered = inOrder(handler); ArgumentCaptor array = ArgumentCaptor.forClass(String[].class); - ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(String[].class)), - any(), array.capture()); + ordered.verify(handler) + .onSuccess(eq(ConfigurationPropertyName.of("foo.bar")), eq(Bindable.of(String[].class)), any(), + array.capture()); assertThat(array.getValue()).containsExactly("a", "b", "c"); ordered.verify(handler).onSuccess(eq(ConfigurationPropertyName.of("foo")), eq(target), any(), isA(Map.class)); } @@ -559,7 +561,8 @@ class MapBinderTests { source.put("foo.items.a", "b"); this.sources.add(source); ExampleCustomNoDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomNoDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomNoDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).containsOnly(entry("foo", "bar"), entry("a", "b")); } @@ -570,7 +573,8 @@ class MapBinderTests { source.put("foo.items.a", "b"); this.sources.add(source); ExampleCustomWithDefaultConstructorBean result = this.binder - .bind("foo", ExampleCustomWithDefaultConstructorBean.class).get(); + .bind("foo", ExampleCustomWithDefaultConstructorBean.class) + .get(); assertThat(result.getItems()).containsExactly(entry("a", "b")); } @@ -581,7 +585,8 @@ class MapBinderTests { source.put("foo.values.e", "f"); this.sources.add(source); Map result = this.binder - .bind("foo.values", STRING_STRING_MAP.withExistingValue(Collections.singletonMap("a", "b"))).get(); + .bind("foo.values", STRING_STRING_MAP.withExistingValue(Collections.singletonMap("a", "b"))) + .get(); assertThat(result).hasSize(3); assertThat(result).containsExactly(entry("a", "b"), entry("c", "d"), entry("e", "f")); } @@ -604,7 +609,7 @@ class MapBinderTests { this.sources.add(source); MapWithWildcardProperties result = this.binder.bind("foo", Bindable.of(MapWithWildcardProperties.class)).get(); assertThat(result.getAddresses().get("localhost").stream().map(InetAddress::getHostAddress)) - .containsExactly("127.0.0.1", "127.0.0.2"); + .containsExactly("127.0.0.1", "127.0.0.2"); } private Bindable> getMapBindable(Class keyGeneric, ResolvableType valueType) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java index 7ef7214b52..3b4e283bbc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -43,8 +43,8 @@ class PropertySourcesPlaceholdersResolverTests { @Test void placeholderResolverIfEnvironmentNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PropertySourcesPlaceholdersResolver((Environment) null)) - .withMessageContaining("Environment must not be null"); + .isThrownBy(() -> new PropertySourcesPlaceholdersResolver((Environment) null)) + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java index 6ceae00942..e991d0b740 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java @@ -82,7 +82,7 @@ class ValueObjectBinderTests { source.put("enum-value", "foo-bar"); this.sources.add(source); ExampleValueBean bean = this.binder.bind(ConfigurationPropertyName.of(""), Bindable.of(ExampleValueBean.class)) - .get(); + .get(); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getLongValue()).isEqualTo(34); assertThat(bean.isBooleanValue()).isTrue(); @@ -136,7 +136,8 @@ class ValueObjectBinderTests { source.put("foo.int-value", "12"); this.sources.add(source); MultipleConstructorsOnlyOneNotPrivateBean bean = this.binder - .bind("foo", Bindable.of(MultipleConstructorsOnlyOneNotPrivateBean.class)).get(); + .bind("foo", Bindable.of(MultipleConstructorsOnlyOneNotPrivateBean.class)) + .get(); bean = bean.withString("test"); assertThat(bean.getIntValue()).isEqualTo(12); assertThat(bean.getStringValue()).isEqualTo("test"); @@ -192,7 +193,7 @@ class ValueObjectBinderTests { source.put("foo.date", "2014-04-01"); this.sources.add(source); ConverterAnnotatedExampleBean bean = this.binder.bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)) - .get(); + .get(); assertThat(bean.getDate()).hasToString("2014-04-01"); } @@ -202,7 +203,7 @@ class ValueObjectBinderTests { source.put("foo.bar", "hello"); this.sources.add(source); ConverterAnnotatedExampleBean bean = this.binder.bind("foo", Bindable.of(ConverterAnnotatedExampleBean.class)) - .get(); + .get(); assertThat(bean.getDate()).hasToString("2019-05-10"); } @@ -212,7 +213,8 @@ class ValueObjectBinderTests { source.put("foo.property", "test"); this.sources.add(source); ExamplePackagePrivateConstructorBean bound = this.binder - .bind("foo", Bindable.of(ExamplePackagePrivateConstructorBean.class)).get(); + .bind("foo", Bindable.of(ExamplePackagePrivateConstructorBean.class)) + .get(); assertThat(bound.getProperty()).isEqualTo("test"); } @@ -254,7 +256,7 @@ class ValueObjectBinderTests { this.sources.add(source); Bindable target = Bindable.of(ValidatingConstructorBean.class); assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder.bind("foo", target)) - .satisfies(this::noConfigurationProperty); + .satisfies(this::noConfigurationProperty); } @Test @@ -264,9 +266,10 @@ class ValueObjectBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.value.bar", "baz"); this.sources.add(source); - GenericValue> bean = this.binder.bind("foo", Bindable + GenericValue> bean = this.binder + .bind("foo", Bindable .>>of(ResolvableType.forClassWithGenerics(GenericValue.class, type))) - .get(); + .get(); assertThat(bean.getValue()).containsEntry("bar", "baz"); } @@ -281,9 +284,9 @@ class ValueObjectBinderTests { @Test void bindWhenJavaLangParameterWithEmptyDefaultValueShouldThrowException() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bindOrCreate("foo", - Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForJavaLangTypes.class))) - .withStackTraceContaining("Parameter of type java.lang.String must have a non-empty default value."); + .isThrownBy(() -> this.binder.bindOrCreate("foo", + Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForJavaLangTypes.class))) + .withStackTraceContaining("Parameter of type java.lang.String must have a non-empty default value."); } @Test @@ -317,18 +320,18 @@ class ValueObjectBinderTests { @Test void bindWhenEnumParameterWithEmptyDefaultValueShouldThrowException() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bindOrCreate("foo", - Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForEnumTypes.class))) - .withStackTraceContaining( - "Parameter of type org.springframework.boot.context.properties.bind.ValueObjectBinderTests$NestedConstructorBeanWithEmptyDefaultValueForEnumTypes$Foo must have a non-empty default value."); + .isThrownBy(() -> this.binder.bindOrCreate("foo", + Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForEnumTypes.class))) + .withStackTraceContaining( + "Parameter of type org.springframework.boot.context.properties.bind.ValueObjectBinderTests$NestedConstructorBeanWithEmptyDefaultValueForEnumTypes$Foo must have a non-empty default value."); } @Test void bindWhenPrimitiveParameterWithEmptyDefaultValueShouldThrowException() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bindOrCreate("foo", - Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForPrimitiveTypes.class))) - .withStackTraceContaining("Parameter of type int must have a non-empty default value."); + .isThrownBy(() -> this.binder.bindOrCreate("foo", + Bindable.of(NestedConstructorBeanWithEmptyDefaultValueForPrimitiveTypes.class))) + .withStackTraceContaining("Parameter of type int must have a non-empty default value."); } @Test @@ -380,7 +383,7 @@ class ValueObjectBinderTests { ClassLoader cl = compiled.getClassLoader(); Object bean = this.binder.bind("test.record", Class.forName("RecordProperties", true, cl)).get(); assertThat(bean).hasFieldOrPropertyWithValue("property1", "value-from-config-1") - .hasFieldOrPropertyWithValue("property2", "default-value-2"); + .hasFieldOrPropertyWithValue("property2", "default-value-2"); } catch (ClassNotFoundException ex) { fail("Expected generated class 'RecordProperties' not found", ex); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java index 942c5a4a12..6eebdf58fd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java @@ -54,7 +54,7 @@ class IgnoreErrorsBindHandlerTests { @Test void bindWhenNotIgnoringErrorsShouldFail() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java index 40a92d4f00..748d8aeb7a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,8 +54,8 @@ class IgnoreTopLevelConverterNotFoundBindHandlerTests { @Test void bindWhenHandlerNotPresentShouldFail() { assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))) - .withCauseInstanceOf(ConverterNotFoundException.class); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))) + .withCauseInstanceOf(ConverterNotFoundException.class); } @Test @@ -69,9 +69,9 @@ class IgnoreTopLevelConverterNotFoundBindHandlerTests { source.put("example.foo", "1"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler())) - .withCauseInstanceOf(IllegalStateException.class); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), + new IgnoreTopLevelConverterNotFoundBindHandler())) + .withCauseInstanceOf(IllegalStateException.class); } @Test @@ -80,9 +80,9 @@ class IgnoreTopLevelConverterNotFoundBindHandlerTests { source.put("example.map", "hello"); this.sources.add(source); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler())) - .withCauseInstanceOf(ConverterNotFoundException.class); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), + new IgnoreTopLevelConverterNotFoundBindHandler())) + .withCauseInstanceOf(ConverterNotFoundException.class); } static class Example { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java index 7fc7b5f104..4cf19ff833 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,7 +62,7 @@ class NoUnboundElementsBindHandlerTests { this.sources.add(source); this.binder = new Binder(this.sources); Example bound = this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler()) - .get(); + .get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -73,10 +73,11 @@ class NoUnboundElementsBindHandlerTests { source.put("example.baz", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()) - .contains("The elements [example.baz] were left unbound")); + assertThatExceptionOfType(BindException.class) + .isThrownBy( + () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .contains("The elements [example.baz] were left unbound")); } @Test @@ -87,7 +88,7 @@ class NoUnboundElementsBindHandlerTests { this.sources.add(source); this.binder = new Binder(this.sources); Example bound = this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler()) - .get(); + .get(); assertThat(bound.getFoo()).isEqualTo("bar"); } @@ -125,10 +126,11 @@ class NoUnboundElementsBindHandlerTests { source.put("example.foo[0]", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - assertThatExceptionOfType(BindException.class).isThrownBy( - () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()) - .contains("The elements [example.foo[0]] were left unbound")); + assertThatExceptionOfType(BindException.class) + .isThrownBy( + () -> this.binder.bind("example", Bindable.of(Example.class), new NoUnboundElementsBindHandler())) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .contains("The elements [example.foo[0]] were left unbound")); } @Test @@ -145,7 +147,7 @@ class NoUnboundElementsBindHandlerTests { this.binder = new Binder(this.sources); NoUnboundElementsBindHandler handler = new NoUnboundElementsBindHandler(); ExampleWithNestedList bound = this.binder.bind("example", Bindable.of(ExampleWithNestedList.class), handler) - .get(); + .get(); assertThat(bound.getNested().get(0).getStringValue()).isEqualTo("bar"); } @@ -161,10 +163,10 @@ class NoUnboundElementsBindHandlerTests { this.sources.add(source2); this.binder = new Binder(this.sources); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("example", Bindable.of(ExampleWithNestedList.class), - new NoUnboundElementsBindHandler())) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()) - .contains("The elements [example.nested[1].invalid] were left unbound")); + .isThrownBy(() -> this.binder.bind("example", Bindable.of(ExampleWithNestedList.class), + new NoUnboundElementsBindHandler())) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .contains("The elements [example.nested[1].invalid] were left unbound")); } static class Example { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java index 78ffaead5e..6e7252c64e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ class PackagePrivateBeanBindingTests { source.put("foo.bar", "999"); this.sources.add(source); ExamplePackagePrivateBean bean = this.binder.bind(this.name, Bindable.of(ExamplePackagePrivateBean.class)) - .get(); + .get(); assertThat(bean.getBar()).isEqualTo(999); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java index 29cd41ed8b..b3d1f734dd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -33,7 +33,7 @@ class BindValidationExceptionTests { @Test void createWhenValidationErrorsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new BindValidationException(null)) - .withMessageContaining("ValidationErrors must not be null"); + .withMessageContaining("ValidationErrors must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java index 17f072326f..27fe9697fd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/OriginTrackedFieldErrorTests.java @@ -57,8 +57,8 @@ class OriginTrackedFieldErrorTests { @Test void toStringShouldAddOrigin() { assertThat(OriginTrackedFieldError.of(FIELD_ERROR, ORIGIN)) - .hasToString("Field error in object 'foo' on field 'bar': rejected value [null]" - + "; codes []; arguments []; default message [faf]; origin afile"); + .hasToString("Field error in object 'foo' on field 'bar': rejected value [null]" + + "; codes []; arguments []; default message [faf]; origin afile"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java index c2dd33293f..9ffee98c76 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java @@ -87,24 +87,23 @@ class ValidationBindHandlerTests { void bindShouldFailWithHandler() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4)); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class), this.handler)) - .withCauseInstanceOf(BindValidationException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class), this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test void bindShouldValidateNestedProperties() { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", 4)); assertThatExceptionOfType(BindException.class) - .isThrownBy( - () -> this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)) - .withCauseInstanceOf(BindValidationException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test void bindShouldFailWithAccessToOrigin() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4, "file")); BindValidationException cause = bindAndExpectValidationError(() -> this.binder - .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedBean.class), this.handler)); + .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedBean.class), this.handler)); ObjectError objectError = cause.getValidationErrors().getAllErrors().get(0); assertThat(Origin.from(objectError)).hasToString("file"); } @@ -119,8 +118,8 @@ class ValidationBindHandlerTests { BindValidationException cause = bindAndExpectValidationError(() -> this.binder.bind( ConfigurationPropertyName.of("foo"), Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)); Set boundProperties = cause.getValidationErrors().getBoundProperties(); - assertThat(boundProperties).extracting((p) -> p.getName().toString()).contains("foo.nested.age", - "foo.nested.name"); + assertThat(boundProperties).extracting((p) -> p.getName().toString()) + .contains("foo.nested.age", "foo.nested.name"); } @Test @@ -167,9 +166,9 @@ class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo", "hello")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) - .withCauseInstanceOf(ConverterNotFoundException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), + this.handler)) + .withCauseInstanceOf(ConverterNotFoundException.class); } @Test @@ -179,9 +178,9 @@ class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo", "hello")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) - .withCauseInstanceOf(BindValidationException.class); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), + this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test @@ -193,17 +192,17 @@ class ValidationBindHandlerTests { this.sources.add(new MockConfigurationPropertySource("foo.years", "99")); ExampleValidatedBean bean = new ExampleValidatedBean(); assertThatExceptionOfType(BindException.class) - .isThrownBy(() -> this.binder.bind("foo", - Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), this.handler)) - .withCauseInstanceOf(BindValidationException.class) - .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("years")); + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class).withExistingValue(bean), + this.handler)) + .withCauseInstanceOf(BindValidationException.class) + .satisfies((ex) -> assertThat(ex.getCause()).hasMessageContaining("years")); } @Test void validationErrorsForCamelCaseFieldsShouldContainRejectedValue() { this.sources.add(new MockConfigurationPropertySource("foo.inner.person-age", 2)); BindValidationException cause = bindAndExpectValidationError(() -> this.binder - .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); + .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); assertThat(cause.getMessage()).contains("rejected value [2]"); } @@ -211,7 +210,7 @@ class ValidationBindHandlerTests { void validationShouldBeSkippedIfPreviousValidationErrorPresent() { this.sources.add(new MockConfigurationPropertySource("foo.inner.person-age", 2)); BindValidationException cause = bindAndExpectValidationError(() -> this.binder - .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); + .bind(ConfigurationPropertyName.of("foo"), Bindable.of(ExampleCamelCase.class), this.handler)); FieldError fieldError = (FieldError) cause.getValidationErrors().getAllErrors().get(0); assertThat(fieldError.getField()).isEqualTo("personAge"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java index a3657e6065..4a5ca36eb0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -47,20 +47,20 @@ class ValidationErrorsTests { @Test void createWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), Collections.emptyList())) - .withMessageContaining("Name must not be null"); + .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), Collections.emptyList())) + .withMessageContaining("Name must not be null"); } @Test void createWhenBoundPropertiesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, null, Collections.emptyList())) - .withMessageContaining("BoundProperties must not be null"); + .withMessageContaining("BoundProperties must not be null"); } @Test void createWhenErrorsIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ValidationErrors(NAME, Collections.emptySet(), null)) - .withMessageContaining("Errors must not be null"); + .withMessageContaining("Errors must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java index 8556562334..77dc3ff0a0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class AliasedConfigurationPropertySourceTests { source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); ConfigurationPropertySource aliased = source.nonIterable() - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(getValue(aliased, "foo.bar")).isEqualTo("bing"); assertThat(getValue(aliased, "foo.bar1")).isEqualTo("bing"); } @@ -47,7 +47,7 @@ class AliasedConfigurationPropertySourceTests { source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); ConfigurationPropertySource aliased = source.nonIterable() - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(getValue(aliased, "foo.baz")).isEqualTo("biff"); } @@ -56,7 +56,7 @@ class AliasedConfigurationPropertySourceTests { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().unknown(name); ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.UNKNOWN); } @@ -64,9 +64,9 @@ class AliasedConfigurationPropertySourceTests { void containsDescendantOfWhenSourceReturnsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().present(name) - .unknown(ConfigurationPropertyName.of("bar")); + .unknown(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); } @@ -74,7 +74,7 @@ class AliasedConfigurationPropertySourceTests { void containsDescendantOfWhenAllAreAbsentShouldReturnAbsent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().absent(name) - .absent(ConfigurationPropertyName.of("bar")); + .absent(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource aliased = source.withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); } @@ -83,7 +83,7 @@ class AliasedConfigurationPropertySourceTests { void containsDescendantOfWhenAnyIsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().absent(name) - .present(ConfigurationPropertyName.of("bar")); + .present(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource aliased = source.withAliases(new ConfigurationPropertyNameAliases("foo", "bar")); assertThat(aliased.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); } @@ -93,9 +93,9 @@ class AliasedConfigurationPropertySourceTests { ConfigurationPropertySource source = new MapConfigurationPropertySource( Collections.singletonMap("foo.bar", "foobar")); ConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "baz.foo")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "baz.foo")); assertThat(aliased.containsDescendantOf(ConfigurationPropertyName.of("baz"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); } private Object getValue(ConfigurationPropertySource source, String name) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java index 95599959a3..fdd2769208 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/AliasedIterableConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -34,7 +34,7 @@ class AliasedIterableConfigurationPropertySourceTests extends AliasedConfigurati source.put("foo.bar", "bing"); source.put("foo.baz", "biff"); IterableConfigurationPropertySource aliased = source - .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); + .withAliases(new ConfigurationPropertyNameAliases("foo.bar", "foo.bar1")); assertThat(aliased.stream()).containsExactly(ConfigurationPropertyName.of("foo.bar"), ConfigurationPropertyName.of("foo.bar1"), ConfigurationPropertyName.of("foo.baz")); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java index 13edbc49ed..aa84049991 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyCachingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -63,8 +63,8 @@ class ConfigurationPropertyCachingTests { @Test void getFromSourcesWhenSourcesIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyCaching.get((Iterable) null)) - .withMessage("Sources must not be null"); + .isThrownBy(() -> ConfigurationPropertyCaching.get((Iterable) null)) + .withMessage("Sources must not be null"); } @Test @@ -89,8 +89,8 @@ class ConfigurationPropertyCachingTests { sources.add(SpringConfigurationPropertySource.from(this.propertySource)); MapPropertySource anotherPropertySource = new MapPropertySource("test2", Collections.emptyMap()); assertThatIllegalStateException() - .isThrownBy(() -> ConfigurationPropertyCaching.get(sources, anotherPropertySource)) - .withMessage("Unable to find cache from configuration property sources"); + .isThrownBy(() -> ConfigurationPropertyCaching.get(sources, anotherPropertySource)) + .withMessage("Unable to find cache from configuration property sources"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java index 3ae273f1b5..7a91afa5e3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -32,14 +32,14 @@ class ConfigurationPropertyNameAliasesTests { @Test void createWithStringWhenNullNameShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationPropertyNameAliases((String) null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void createWithStringShouldAddMapping() { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -48,7 +48,7 @@ class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -56,7 +56,7 @@ class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -65,7 +65,7 @@ class ConfigurationPropertyNameAliasesTests { aliases.addAliases(ConfigurationPropertyName.of("foo"), ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -74,7 +74,7 @@ class ConfigurationPropertyNameAliasesTests { aliases.addAliases("foo", "bar"); aliases.addAliases("foo", "baz"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); + .containsExactly(ConfigurationPropertyName.of("bar"), ConfigurationPropertyName.of("baz")); } @Test @@ -88,7 +88,7 @@ class ConfigurationPropertyNameAliasesTests { ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases(); aliases.addAliases("foo", "bar"); assertThat(aliases.getAliases(ConfigurationPropertyName.of("foo"))) - .containsExactly(ConfigurationPropertyName.of("bar")); + .containsExactly(ConfigurationPropertyName.of("bar")); } @Test @@ -97,9 +97,9 @@ class ConfigurationPropertyNameAliasesTests { aliases.addAliases("foo", "bar"); aliases.addAliases("foo", "baz"); assertThat((Object) aliases.getNameForAlias(ConfigurationPropertyName.of("bar"))) - .isEqualTo(ConfigurationPropertyName.of("foo")); + .isEqualTo(ConfigurationPropertyName.of("foo")); assertThat((Object) aliases.getNameForAlias(ConfigurationPropertyName.of("baz"))) - .isEqualTo(ConfigurationPropertyName.of("foo")); + .isEqualTo(ConfigurationPropertyName.of("foo")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java index 8fcea89dd8..53871db64b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java @@ -41,31 +41,35 @@ class ConfigurationPropertyNameTests { @Test void ofNameShouldNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.of(null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void ofNameShouldNotStartWithDash() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("-foo")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("-foo")) + .withMessageContaining("is not valid"); } @Test void ofNameShouldNotStartWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of(".foo")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of(".foo")) + .withMessageContaining("is not valid"); } @Test void ofNameShouldNotEndWithDot() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo.")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo.")) + .withMessageContaining("is not valid"); } @Test void ofNameShouldNotContainUppercase() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("fOo")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("fOo")) + .withMessageContaining("is not valid"); } @Test @@ -73,8 +77,8 @@ class ConfigurationPropertyNameTests { String invalid = "_@$%*+=':;"; for (char c : invalid.toCharArray()) { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)) - .satisfies((ex) -> assertThat(ex.getMessage()).contains("is not valid")); + .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)) + .satisfies((ex) -> assertThat(ex.getMessage()).contains("is not valid")); } } @@ -153,19 +157,22 @@ class ConfigurationPropertyNameTests { @Test void ofNameWhenMissingCloseBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("[bar")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("[bar")) + .withMessageContaining("is not valid"); } @Test void ofNameWhenMissingOpenBracket() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("bar]")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("bar]")) + .withMessageContaining("is not valid"); } @Test void ofNameWhenMultipleMismatchedBrackets() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")) + .withMessageContaining("is not valid"); } @Test @@ -179,7 +186,8 @@ class ConfigurationPropertyNameTests { @Test void ofNameWithWhitespaceInName() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")).withMessageContaining("is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")) + .withMessageContaining("is not valid"); } @Test @@ -224,7 +232,7 @@ class ConfigurationPropertyNameTests { @Test void adaptWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyName.adapt(null, '.')) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test @@ -408,8 +416,8 @@ class ConfigurationPropertyNameTests { @Test void appendWhenElementNameIsNotValidShouldThrowException() { assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) - .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("-bar")) - .withMessageContaining("Configuration property name '-bar' is not valid"); + .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("-bar")) + .withMessageContaining("Configuration property name '-bar' is not valid"); } @Test @@ -588,7 +596,7 @@ class ConfigurationPropertyNameTests { void compareDifferentLengthsShouldSortNames() { ConfigurationPropertyName name = ConfigurationPropertyName.of("spring.web.resources.chain.strategy.content"); ConfigurationPropertyName other = ConfigurationPropertyName - .of("spring.web.resources.chain.strategy.content.enabled"); + .of("spring.web.resources.chain.strategy.content.enabled"); assertThat(name).isLessThan(other); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java index dda5128a53..6c8ae09ca8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class ConfigurationPropertySourceTests { source.setProperty("spring", "boot"); ConfigurationPropertySource adapted = ConfigurationPropertySource.from(source); assertThat(adapted.getConfigurationProperty(ConfigurationPropertyName.of("spring")).getValue()) - .isEqualTo("boot"); + .isEqualTo("boot"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java index af0490ea98..552bbbc2ef 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,7 +66,7 @@ class ConfigurationPropertySourcesTests { ConfigurableEnvironment child = new StandardEnvironment(); child.merge(parent); child.getPropertySources() - .addLast(new MapPropertySource("config", Collections.singletonMap("my.example_property", "1234"))); + .addLast(new MapPropertySource("config", Collections.singletonMap("my.example_property", "1234"))); ConfigurationPropertySources.attach(child); assertThat(child.getProperty("my.example-property")).isEqualTo("1234"); } @@ -115,8 +115,9 @@ class ConfigurationPropertySourcesTests { @Test void fromPropertySourceShouldReturnSpringConfigurationPropertySource() { PropertySource source = new MapPropertySource("foo", Collections.singletonMap("foo", "bar")); - ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySources.from(source).iterator() - .next(); + ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySources.from(source) + .iterator() + .next(); assertThat(configurationPropertySource).isInstanceOf(SpringConfigurationPropertySource.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java index 6663cb26ce..61be906666 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,14 +35,14 @@ class ConfigurationPropertyStateTests { @Test void searchWhenIterableIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> ConfigurationPropertyState.search(null, (e) -> true)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test void searchWhenPredicateIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConfigurationPropertyState.search(Collections.emptyList(), null)) - .withMessageContaining("Predicate must not be null"); + .isThrownBy(() -> ConfigurationPropertyState.search(Collections.emptyList(), null)) + .withMessageContaining("Predicate must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java index 1e5d2d79c1..e1da09f8a3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java @@ -41,13 +41,13 @@ class ConfigurationPropertyTests { @Test void createWhenNameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(null, "bar", null)) - .withMessageContaining("Name must not be null"); + .withMessageContaining("Name must not be null"); } @Test void createWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigurationProperty(NAME, null, null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java index 5bce71fcd9..685a6e63cb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -34,16 +34,15 @@ class FilteredConfigurationPropertiesSourceTests { @Test void createWhenSourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) - .withMessageContaining("Source must not be null"); + .isThrownBy(() -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) + .withMessageContaining("Source must not be null"); } @Test void createWhenFilterIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), null)) - .withMessageContaining("Filter must not be null"); + .isThrownBy(() -> new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), null)) + .withMessageContaining("Filter must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java index 816c5d83bd..0b36cbbfd4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredIterableConfigurationPropertiesSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -32,8 +32,9 @@ class FilteredIterableConfigurationPropertiesSourceTests extends FilteredConfigu void iteratorShouldFilterNames() { MockConfigurationPropertySource source = (MockConfigurationPropertySource) createTestSource(); IterableConfigurationPropertySource filtered = source.filter(this::noBrackets); - assertThat(filtered.iterator()).toIterable().extracting(ConfigurationPropertyName::toString) - .containsExactly("a", "b", "c"); + assertThat(filtered.iterator()).toIterable() + .extracting(ConfigurationPropertyName::toString) + .containsExactly("a", "b", "c"); } @Override @@ -49,9 +50,9 @@ class FilteredIterableConfigurationPropertiesSourceTests extends FilteredConfigu source.put("faf.bar[0]", "1"); IterableConfigurationPropertySource filtered = source.filter(this::noBrackets); assertThat(filtered.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(filtered.containsDescendantOf(ConfigurationPropertyName.of("faf"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } private boolean noBrackets(ConfigurationPropertyName name) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java index c7b4b2798e..dc2e63d655 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class MapConfigurationPropertySourceTests { @Test void createWhenMapIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new MapConfigurationPropertySource(null)) - .withMessageContaining("Map must not be null"); + .withMessageContaining("Map must not be null"); } @Test @@ -52,7 +52,7 @@ class MapConfigurationPropertySourceTests { void putAllWhenMapIsNullShouldThrowException() { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); assertThatIllegalArgumentException().isThrownBy(() -> source.putAll(null)) - .withMessageContaining("Map must not be null"); + .withMessageContaining("Map must not be null"); } @Test @@ -87,8 +87,8 @@ class MapConfigurationPropertySourceTests { MapConfigurationPropertySource source = new MapConfigurationPropertySource(); source.put("foo.BAR", "spring"); source.put("foo.baz", "boot"); - assertThat(source.iterator()).toIterable().containsExactly(ConfigurationPropertyName.of("foo.bar"), - ConfigurationPropertyName.of("foo.baz")); + assertThat(source.iterator()).toIterable() + .containsExactly(ConfigurationPropertyName.of("foo.bar"), ConfigurationPropertyName.of("foo.baz")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java index 6a0676de19..51a03d3a6d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -37,39 +37,39 @@ class MutuallyExclusiveConfigurationPropertiesExceptionTests { @Test void createWhenConfiguredNamesIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(null, Arrays.asList("a", "b"))) - .withMessage("ConfiguredNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(null, Arrays.asList("a", "b"))) + .withMessage("ConfiguredNames must contain 2 or more names"); } @Test void createWhenConfiguredNamesContainsOneElementThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Collections.singleton("a"), - Arrays.asList("a", "b"))) - .withMessage("ConfiguredNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Collections.singleton("a"), + Arrays.asList("a", "b"))) + .withMessage("ConfiguredNames must contain 2 or more names"); } @Test void createWhenMutuallyExclusiveNamesIsNullThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), null)) - .withMessage("MutuallyExclusiveNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), null)) + .withMessage("MutuallyExclusiveNames must contain 2 or more names"); } @Test void createWhenMutuallyExclusiveNamesContainsOneElementThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), - Collections.singleton("a"))) - .withMessage("MutuallyExclusiveNames must contain 2 or more names"); + .isThrownBy(() -> new MutuallyExclusiveConfigurationPropertiesException(Arrays.asList("a", "b"), + Collections.singleton("a"))) + .withMessage("MutuallyExclusiveNames must contain 2 or more names"); } @Test void createBuildsSensibleMessage() { List names = Arrays.asList("a", "b"); assertThat(new MutuallyExclusiveConfigurationPropertiesException(names, names)) - .hasMessage("The configuration properties 'a, b' are mutually exclusive " - + "and 'a, b' have been configured together"); + .hasMessage("The configuration properties 'a, b' are mutually exclusive " + + "and 'a, b' have been configured together"); } @Test @@ -117,10 +117,11 @@ class MutuallyExclusiveConfigurationPropertiesExceptionTests { entries.put("a", "a"); entries.put("b", "B"); entries.put("c", null); - })).satisfies((ex) -> { - assertThat(ex.getConfiguredNames()).containsExactly("a", "b"); - assertThat(ex.getMutuallyExclusiveNames()).containsExactly("a", "b", "c"); - }); + })) + .satisfies((ex) -> { + assertThat(ex.getConfiguredNames()).containsExactly("a", "b"); + assertThat(ex.getMutuallyExclusiveNames()).containsExactly("a", "b", "c"); + }); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java index 380f13641a..209425ded8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/PrefixedConfigurationPropertySourceTests.java @@ -45,27 +45,27 @@ class PrefixedConfigurationPropertySourceTests { ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().unknown(name); ConfigurationPropertySource prefixed = source.withPrefix("my"); assertThat(prefixed.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.UNKNOWN); + .isEqualTo(ConfigurationPropertyState.UNKNOWN); } @Test void containsDescendantOfWhenSourceReturnsPresentShouldReturnPresent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("my.foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().present(name) - .unknown(ConfigurationPropertyName.of("bar")); + .unknown(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource prefixed = source.withPrefix("my"); assertThat(prefixed.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); } @Test void containsDescendantOfWhenSourceReturnsAbsentShouldReturnAbsent() { ConfigurationPropertyName name = ConfigurationPropertyName.of("my.foo"); ConfigurationPropertySource source = new KnownAncestorsConfigurationPropertySource().absent(name) - .absent(ConfigurationPropertyName.of("bar")); + .absent(ConfigurationPropertyName.of("bar")); ConfigurationPropertySource prefixed = source.withPrefix("my"); assertThat(prefixed.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java index 7676d13dab..ec870d734b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java @@ -42,8 +42,8 @@ class SpringConfigurationPropertySourceTests { @Test void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringConfigurationPropertySource(null, mock(PropertyMapper.class))) - .withMessageContaining("PropertySource must not be null"); + .isThrownBy(() -> new SpringConfigurationPropertySource(null, mock(PropertyMapper.class))) + .withMessageContaining("PropertySource must not be null"); } @Test @@ -94,13 +94,13 @@ class SpringConfigurationPropertySourceTests { SpringConfigurationPropertySource adapter = new SpringConfigurationPropertySource(propertySource, DefaultPropertyMapper.INSTANCE); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.UNKNOWN); + .isEqualTo(ConfigurationPropertyState.UNKNOWN); } @Test void fromWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> SpringConfigurationPropertySource.from(null)) - .withMessageContaining("Source must not be null"); + .withMessageContaining("Source must not be null"); } @Test @@ -114,7 +114,7 @@ class SpringConfigurationPropertySourceTests { }; assertThat(SpringConfigurationPropertySource.from(propertySource)) - .isNotInstanceOf(IterableConfigurationPropertySource.class); + .isNotInstanceOf(IterableConfigurationPropertySource.class); } @@ -130,7 +130,7 @@ class SpringConfigurationPropertySourceTests { }; PropertySource propertySource = new MapPropertySource("test", source); assertThat(SpringConfigurationPropertySource.from(propertySource)) - .isNotInstanceOf(IterableConfigurationPropertySource.class); + .isNotInstanceOf(IterableConfigurationPropertySource.class); } @Test @@ -140,13 +140,13 @@ class SpringConfigurationPropertySourceTests { source.put("barBaz", "Boot"); PropertySource propertySource = new MapPropertySource("test", source); assertThat(SpringConfigurationPropertySource.from(propertySource)) - .isInstanceOf(IterableConfigurationPropertySource.class); + .isInstanceOf(IterableConfigurationPropertySource.class); } @Test void containsDescendantOfWhenRandomSourceAndRandomPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource()); + .from(new RandomValuePropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("random"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -155,7 +155,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenRandomSourceAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource()); + .from(new RandomValuePropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("random.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(source.getConfigurationProperty(name)).isNotNull(); @@ -164,7 +164,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenRandomSourceWithDifferentNameAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource("different")); + .from(new RandomValuePropertySource("different")); ConfigurationPropertyName name = ConfigurationPropertyName.of("random.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(source.getConfigurationProperty(name)).isNotNull(); @@ -173,7 +173,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenRandomSourceAndNonRandomPropertyReturnsAbsent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomValuePropertySource()); + .from(new RandomValuePropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("abandon.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -182,7 +182,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndRandomPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("cachedrandom"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -191,7 +191,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("cachedrandom.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -200,7 +200,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceWithMatchingNameAndRandomPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource("cachedrandom")); + .from(new RandomWrapperPropertySource("cachedrandom")); ConfigurationPropertyName name = ConfigurationPropertyName.of("cachedrandom.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(source.getConfigurationProperty(name)).isNotNull(); @@ -209,7 +209,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndRandomDashPrefixedPropertyReturnsPresent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("cached-random.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); @@ -218,7 +218,7 @@ class SpringConfigurationPropertySourceTests { @Test void containsDescendantOfWhenWrappedRandomSourceAndNonRandomPropertyReturnsAbsent() { SpringConfigurationPropertySource source = SpringConfigurationPropertySource - .from(new RandomWrapperPropertySource()); + .from(new RandomWrapperPropertySource()); ConfigurationPropertyName name = ConfigurationPropertyName.of("abandon.something.int"); assertThat(source.containsDescendantOf(name)).isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(source.getConfigurationProperty(name)).isNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java index b8072e4e4a..b8a2c3b940 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java @@ -43,7 +43,7 @@ class SpringConfigurationPropertySourcesTests { @Test void createWhenPropertySourcesIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringConfigurationPropertySources(null)) - .withMessageContaining("Sources must not be null"); + .withMessageContaining("Sources must not be null"); } @Test @@ -82,8 +82,8 @@ class SpringConfigurationPropertySourcesTests { @Test void shouldNotAdaptSystemEnvironmentPropertyOverrideSource() { MutablePropertySources sources = new MutablePropertySources(); - sources.addLast( - new SystemEnvironmentPropertySource("override", Collections.singletonMap("server.port", "1234"))); + sources + .addLast(new SystemEnvironmentPropertySource("override", Collections.singletonMap("server.port", "1234"))); Iterator iterator = new SpringConfigurationPropertySources(sources).iterator(); ConfigurationPropertyName name = ConfigurationPropertyName.of("server.port"); assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); @@ -112,7 +112,7 @@ class SpringConfigurationPropertySourcesTests { assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("1234"); assertThat(iterator.next().getConfigurationProperty(name).getValue()).isEqualTo("4567"); assertThat(iterator.next().getConfigurationProperty(ConfigurationPropertyName.of("a")).getValue()) - .isEqualTo("b"); + .isEqualTo("b"); assertThat(iterator.hasNext()).isFalse(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java index 6e50482fe2..30c97f02e7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java @@ -50,8 +50,8 @@ class SpringIterableConfigurationPropertySourceTests { @Test void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, mock(PropertyMapper.class))) - .withMessageContaining("PropertySource must not be null"); + .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, mock(PropertyMapper.class))) + .withMessageContaining("PropertySource must not be null"); } @Test @@ -70,8 +70,9 @@ class SpringIterableConfigurationPropertySourceTests { mapper2.addFromPropertySource("key2", "my.key2b"); SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, mapper1, mapper2); - assertThat(adapter.iterator()).toIterable().extracting(Object::toString).containsExactly("my.key1", "my.key2a", - "my.key4"); + assertThat(adapter.iterator()).toIterable() + .extracting(Object::toString) + .containsExactly("my.key1", "my.key2a", "my.key4"); } @Test @@ -116,7 +117,7 @@ class SpringIterableConfigurationPropertySourceTests { SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, mapper); assertThat(adapter.getConfigurationProperty(name).getOrigin()) - .hasToString("\"key\" from property source \"test\""); + .hasToString("\"key\" from property source \"test\""); } @Test @@ -143,11 +144,11 @@ class SpringIterableConfigurationPropertySourceTests { SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, DefaultPropertyMapper.INSTANCE); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("faf"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("fof"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } @Test @@ -160,11 +161,11 @@ class SpringIterableConfigurationPropertySourceTests { SpringIterableConfigurationPropertySource adapter = new SpringIterableConfigurationPropertySource( propertySource, SystemEnvironmentPropertyMapper.INSTANCE); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo.bar-baz"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo.alpha-bravo"))) - .isEqualTo(ConfigurationPropertyState.PRESENT); + .isEqualTo(ConfigurationPropertyState.PRESENT); assertThat(adapter.containsDescendantOf(ConfigurationPropertyName.of("foo.blah"))) - .isEqualTo(ConfigurationPropertyState.ABSENT); + .isEqualTo(ConfigurationPropertyState.ABSENT); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java index ff03e03bdd..a0b5ae1fdd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -117,7 +117,7 @@ class ApplicationConversionServiceTests { @Test void sharedInstanceCannotBeModified() { ApplicationConversionService instance = (ApplicationConversionService) ApplicationConversionService - .getSharedInstance(); + .getSharedInstance(); assertUnmodifiableExceptionThrown(() -> instance.addPrinter(null)); assertUnmodifiableExceptionThrown(() -> instance.addParser(null)); assertUnmodifiableExceptionThrown(() -> instance.addFormatter(null)); @@ -133,7 +133,7 @@ class ApplicationConversionServiceTests { private void assertUnmodifiableExceptionThrown(ThrowingCallable throwingCallable) { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(throwingCallable) - .withMessage("This ApplicationConversionService cannot be modified"); + .withMessage("This ApplicationConversionService cannot be modified"); } static class ExampleGenericConverter implements GenericConverter { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java index 40a7720a0b..bec41a5d63 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ArrayToDelimitedStringConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -80,7 +80,7 @@ class ArrayToDelimitedStringConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new ArrayToDelimitedStringConverter(service))); + .with((service) -> service.addConverter(new ArrayToDelimitedStringConverter(service))); } static class Data { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java index e75f1faf9d..29b7879d2f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/CollectionToDelimitedStringConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -82,7 +82,7 @@ class CollectionToDelimitedStringConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new CollectionToDelimitedStringConverter(service))); + .with((service) -> service.addConverter(new CollectionToDelimitedStringConverter(service))); } static class Data { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java index 0ccb3914cf..ce9b83c8be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToArrayConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,7 @@ class DelimitedStringToArrayConverterTests { void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); assertThat(new DelimitedStringToArrayConverter(conversionService).matches(sourceType, targetType)).isFalse(); } @@ -68,17 +68,17 @@ class DelimitedStringToArrayConverterTests { void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); assertThat( new DelimitedStringToArrayConverter(new ApplicationConversionService()).matches(sourceType, targetType)) - .isTrue(); + .isTrue(); } @Test void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); Integer[] converted = (Integer[]) new ApplicationConversionService().convert(" 1 | 2| 3 ", sourceType, targetType); assertThat(converted).containsExactly(1, 2, 3); @@ -86,7 +86,7 @@ class DelimitedStringToArrayConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new DelimitedStringToArrayConverter(service))); + .with((service) -> service.addConverter(new DelimitedStringToArrayConverter(service))); } static class Values { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java index f445f2db63..69fef031c4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DelimitedStringToCollectionConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class DelimitedStringToCollectionConverterTests { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noAnnotation"), 0); assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) - .isTrue(); + .isTrue(); } @ConversionServiceTest @@ -55,16 +55,16 @@ class DelimitedStringToCollectionConverterTests { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor.nested(ReflectionUtils.findField(Values.class, "noElementType"), 0); assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) - .isTrue(); + .isTrue(); } @ConversionServiceTest void matchesWhenHasAnnotationAndNonConvertibleElementTypeShouldReturnFalse(ConversionService conversionService) { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "nonConvertibleElementType"), 0); assertThat(new DelimitedStringToCollectionConverter(conversionService).matches(sourceType, targetType)) - .isFalse(); + .isFalse(); } @ConversionServiceTest @@ -100,9 +100,10 @@ class DelimitedStringToCollectionConverterTests { void matchesWhenHasAnnotationAndConvertibleElementTypeShouldReturnTrue() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); assertThat(new DelimitedStringToCollectionConverter(new ApplicationConversionService()).matches(sourceType, - targetType)).isTrue(); + targetType)) + .isTrue(); } @Test @@ -110,7 +111,7 @@ class DelimitedStringToCollectionConverterTests { void convertWhenHasConvertibleElementTypeShouldReturnConvertedType() { TypeDescriptor sourceType = TypeDescriptor.valueOf(String.class); TypeDescriptor targetType = TypeDescriptor - .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); + .nested(ReflectionUtils.findField(Values.class, "convertibleElementType"), 0); List converted = (List) new ApplicationConversionService().convert(" 1 | 2| 3 ", sourceType, targetType); assertThat(converted).containsExactly(1, 2, 3); @@ -118,7 +119,7 @@ class DelimitedStringToCollectionConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new DelimitedStringToCollectionConverter(service))); + .with((service) -> service.addConverter(new DelimitedStringToCollectionConverter(service))); } static class Values { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java index 213ee92fa4..66438a7f2f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,7 +35,7 @@ class DurationStyleTests { @Test void detectAndParseWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse(null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test @@ -124,7 +124,7 @@ class DurationStyleTests { @Test void detectAndParseWhenBadFormatShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detectAndParse("10foo")) - .withMessageContaining("'10foo' is not a valid duration"); + .withMessageContaining("'10foo' is not a valid duration"); } @Test @@ -159,7 +159,7 @@ class DurationStyleTests { @Test void detectWhenUnknownShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detect("bad")) - .withMessageContaining("'bad' is not a valid duration"); + .withMessageContaining("'bad' is not a valid duration"); } @Test @@ -191,7 +191,7 @@ class DurationStyleTests { @Test void parseIso8601WhenSimpleShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.ISO8601.parse("10d")) - .withMessageContaining("'10d' is not a valid ISO-8601 duration"); + .withMessageContaining("'10d' is not a valid ISO-8601 duration"); } @Test @@ -208,13 +208,13 @@ class DurationStyleTests { @Test void parseSimpleWhenUnknownUnitShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("10mb")) - .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'")); + .satisfies((ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'")); } @Test void parseSimpleWhenIso8601ShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.SIMPLE.parse("PT10H")) - .withMessageContaining("'PT10H' is not a valid simple duration"); + .withMessageContaining("'PT10H' is not a valid simple duration"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java index 626b0eb375..6f57c1a1b2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class InetAddressFormatterTests { String missingDomain = "ireallydontexist.example.com"; assumingThat(!isResolvable("ireallydontexist.example.com"), () -> assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(missingDomain, InetAddress.class))); + .isThrownBy(() -> conversionService.convert(missingDomain, InetAddress.class))); } private boolean isResolvable(String host) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java index 47eb7f9842..3b05120ed1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,9 +53,10 @@ class InputStreamSourceToByteArrayConverterTests { InputStreamSource source = mock(InputStreamSource.class); given(source.getInputStream()).willThrow(IOException.class); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(source, byte[].class)).havingCause() - .isInstanceOf(IllegalStateException.class) - .withMessageContaining("Unable to read from input stream source"); + .isThrownBy(() -> conversionService.convert(source, byte[].class)) + .havingCause() + .isInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to read from input stream source"); } @ConversionServiceTest @@ -66,8 +67,10 @@ class InputStreamSourceToByteArrayConverterTests { given(source.getInputStream()).willThrow(IOException.class); given(((OriginProvider) source).getOrigin()).willReturn(origin); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(source, byte[].class)).havingCause() - .isInstanceOf(IllegalStateException.class).withMessageContaining("Unable to read from mylocation"); + .isThrownBy(() -> conversionService.convert(source, byte[].class)) + .havingCause() + .isInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to read from mylocation"); } @ConversionServiceTest @@ -77,13 +80,15 @@ class InputStreamSourceToByteArrayConverterTests { given(source.getInputStream()).willThrow(IOException.class); given(source.getDescription()).willReturn("myresource"); assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> conversionService.convert(source, byte[].class)).havingCause() - .isInstanceOf(IllegalStateException.class).withMessageContaining("Unable to read from myresource"); + .isThrownBy(() -> conversionService.convert(source, byte[].class)) + .havingCause() + .isInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to read from myresource"); } static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverter(new InputStreamSourceToByteArrayConverter())); + .with((service) -> service.addConverter(new InputStreamSourceToByteArrayConverter())); } private static class TestOrigin implements Origin { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java index fadac100fd..1b69da57e8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientBooleanToEnumConverterFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -41,7 +41,7 @@ class LenientBooleanToEnumConverterFactoryTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverterFactory(new LenientBooleanToEnumConverterFactory())); + .with((service) -> service.addConverterFactory(new LenientBooleanToEnumConverterFactory())); } enum TestOnOffEnum { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java index 0d2b9b2d88..904fe1d719 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/LenientStringToEnumConverterFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -94,7 +94,7 @@ class LenientStringToEnumConverterFactoryTests { static Stream conversionServices() { return ConversionServiceArguments - .with((service) -> service.addConverterFactory(new LenientStringToEnumConverterFactory())); + .with((service) -> service.addConverterFactory(new LenientStringToEnumConverterFactory())); } enum TestEnum { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java index 41abeac07c..6cea88918d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockDurationTypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ public final class MockDurationTypeDescriptor { } if (style != null) { DurationFormat formatAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", style), DurationFormat.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", style), DurationFormat.class, null); given(descriptor.getAnnotation(DurationFormat.class)).willReturn(formatAnnotation); } given(descriptor.getType()).willReturn((Class) Duration.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java index 599adffe8a..815593a895 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/MockPeriodTypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ public final class MockPeriodTypeDescriptor { } if (style != null) { PeriodFormat formatAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", style), PeriodFormat.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", style), PeriodFormat.class, null); given(descriptor.getAnnotation(PeriodFormat.class)).willReturn(formatAnnotation); } given(descriptor.getType()).willReturn((Class) Period.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java index 15b3296efe..8f5ded746f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDataSizeConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -61,7 +61,7 @@ class NumberToDataSizeConverterTests { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { DataSizeUnit unitAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DataSizeUnit.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DataSizeUnit.class, null); given(targetType.getAnnotation(DataSizeUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) DataSize.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java index 1ed1ef9cc6..c1c8d517be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToDurationConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -61,7 +61,7 @@ class NumberToDurationConverterTests { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { DurationUnit unitAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DurationUnit.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), DurationUnit.class, null); given(targetType.getAnnotation(DurationUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) Duration.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java index 169191f029..56ce68bdd3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/NumberToPeriodConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -67,7 +67,7 @@ class NumberToPeriodConverterTests { TypeDescriptor targetType = mock(TypeDescriptor.class); if (defaultUnit != null) { PeriodUnit unitAnnotation = AnnotationUtils - .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), PeriodUnit.class, null); + .synthesizeAnnotation(Collections.singletonMap("value", defaultUnit), PeriodUnit.class, null); given(targetType.getAnnotation(PeriodUnit.class)).willReturn(unitAnnotation); } given(targetType.getType()).willReturn((Class) Period.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java index 42cf7b6284..866557b9fe 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/PeriodStyleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class PeriodStyleTests { @Test void detectAndParseWhenValueIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detectAndParse(null)) - .withMessageContaining("Value must not be null"); + .withMessageContaining("Value must not be null"); } @Test @@ -109,7 +109,7 @@ class PeriodStyleTests { @Test void detectAndParseWhenBadFormatShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detectAndParse("10foo")) - .withMessageContaining("'10foo' is not a valid period"); + .withMessageContaining("'10foo' is not a valid period"); } @Test @@ -138,7 +138,7 @@ class PeriodStyleTests { @Test void detectWhenUnknownShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.detect("bad")) - .withMessageContaining("'bad' is not a valid period"); + .withMessageContaining("'bad' is not a valid period"); } @Test @@ -168,7 +168,7 @@ class PeriodStyleTests { @Test void parseIso8601WhenSimpleShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.ISO8601.parse("10d")) - .withMessageContaining("'10d' is not a valid ISO-8601 period"); + .withMessageContaining("'10d' is not a valid ISO-8601 period"); } @Test @@ -184,14 +184,15 @@ class PeriodStyleTests { @Test void parseSimpleWhenUnknownUnitShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("10x")).satisfies( - (ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Does not match simple period pattern")); + assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("10x")) + .satisfies( + (ex) -> assertThat(ex.getCause().getMessage()).isEqualTo("Does not match simple period pattern")); } @Test void parseSimpleWhenIso8601ShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> PeriodStyle.SIMPLE.parse("PT10H")) - .withMessageContaining("'PT10H' is not a valid simple period"); + .withMessageContaining("'PT10H' is not a valid simple period"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java index 1a6fb701db..08e2037a4c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -88,8 +88,9 @@ class StringToDataSizeConverterTests { @ConversionServiceTest void convertWhenBadFormatShouldThrowException(ConversionService conversionService) { assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert(conversionService, "10WB")) - .havingCause().isInstanceOf(IllegalArgumentException.class) - .withMessageContaining("'10WB' is not a valid data size"); + .havingCause() + .isInstanceOf(IllegalArgumentException.class) + .withMessageContaining("'10WB' is not a valid data size"); } @ConversionServiceTest diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java index 08cb3bcbce..9e884c83e6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -122,13 +122,14 @@ class StringToDurationConverterTests { @ConversionServiceTest void convertWhenBadFormatShouldThrowException(ConversionService conversionService) { assertThatExceptionOfType(ConversionFailedException.class).isThrownBy(() -> convert(conversionService, "10foo")) - .havingRootCause().withMessageContaining("'10foo' is not a valid duration"); + .havingRootCause() + .withMessageContaining("'10foo' is not a valid duration"); } @ConversionServiceTest void convertWhenStyleMismatchShouldThrowException(ConversionService conversionService) { assertThatExceptionOfType(ConversionFailedException.class) - .isThrownBy(() -> convert(conversionService, "10s", null, DurationStyle.ISO8601)); + .isThrownBy(() -> convert(conversionService, "10s", null, DurationStyle.ISO8601)); } @ConversionServiceTest diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java index a10dbbfedc..e053f15bc1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToFileConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -39,13 +39,13 @@ class StringToFileConverterTests { @ConversionServiceTest void convertWhenSimpleFileReturnsFile(ConversionService conversionService) { assertThat(convert(conversionService, this.temp.getAbsolutePath() + "/test")) - .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); + .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); } @ConversionServiceTest void convertWhenFilePrefixedReturnsFile(ConversionService conversionService) { assertThat(convert(conversionService, "file:" + this.temp.getAbsolutePath() + "/test").getAbsoluteFile()) - .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); + .isEqualTo(new File(this.temp, "test").getAbsoluteFile()); } private File convert(ConversionService conversionService, String source) { @@ -54,7 +54,7 @@ class StringToFileConverterTests { static Stream conversionServices() { return ConversionServiceArguments - .with((conversionService) -> conversionService.addConverter(new StringToFileConverter())); + .with((conversionService) -> conversionService.addConverter(new StringToFileConverter())); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java index de77ceec51..f055da41ab 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/AbstractFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -53,14 +53,15 @@ class AbstractFailureAnalyzerTests { void findCauseWitNestedAndExactMatch() { TestException ex = new TestException(); assertThat(this.failureAnalyzer.findCause(new IllegalArgumentException(new IllegalStateException(ex)), - TestException.class)).isEqualTo(ex); + TestException.class)) + .isEqualTo(ex); } @Test void findCauseWitNestedAndSubClass() { SpecificTestException ex = new SpecificTestException(); assertThat(this.failureAnalyzer.findCause(new IOException(new IllegalStateException(ex)), TestException.class)) - .isEqualTo(ex); + .isEqualTo(ex); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java index 84992fa955..b4ea65292c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,8 @@ class FailureAnalyzersIntegrationTests { @Test void analysisIsPerformed(CapturedOutput output) { - assertThatExceptionOfType(Exception.class).isThrownBy( - () -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run()); + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run()); assertThat(output).contains("APPLICATION FAILED TO START"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java index 9ae4a2a2fa..78bb9b62ec 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzerTests.java @@ -57,7 +57,7 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEmpty(); assertThat(lines.get(2)).isEqualTo("┌─────┐"); assertThat(lines.get(3)).startsWith("| one defined in " + InnerInnerConfiguration.class.getName()); @@ -73,19 +73,19 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { void cycleWithAutowiredFields() throws IOException { FailureAnalysis analysis = performAnalysis(CycleWithAutowiredFields.class); assertThat(analysis.getDescription()) - .startsWith("The dependencies of some of the beans in the application context form a cycle:"); + .startsWith("The dependencies of some of the beans in the application context form a cycle:"); List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(9); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEmpty(); assertThat(lines.get(2)).isEqualTo("┌─────┐"); assertThat(lines.get(3)).startsWith("| three defined in " + BeanThreeConfiguration.class.getName()); assertThat(lines.get(4)).isEqualTo("↑ ↓"); assertThat(lines.get(5)).startsWith("| one defined in " + CycleWithAutowiredFields.class.getName()); assertThat(lines.get(6)).isEqualTo("↑ ↓"); - assertThat(lines.get(7)).startsWith( - "| " + BeanTwoConfiguration.class.getName() + " (field private " + BeanThree.class.getName()); + assertThat(lines.get(7)) + .startsWith("| " + BeanTwoConfiguration.class.getName() + " (field private " + BeanThree.class.getName()); assertThat(lines.get(8)).isEqualTo("└─────┘"); assertThat(analysis.getAction()).isNotNull(); } @@ -96,20 +96,20 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(12); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEmpty(); assertThat(lines.get(2)).contains("refererOne (field " + RefererTwo.class.getName()); assertThat(lines.get(3)).isEqualTo(" ↓"); assertThat(lines.get(4)).contains("refererTwo (field " + BeanOne.class.getName()); assertThat(lines.get(5)).isEqualTo("┌─────┐"); assertThat(lines.get(6)) - .startsWith("| one defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); + .startsWith("| one defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(7)).isEqualTo("↑ ↓"); assertThat(lines.get(8)) - .startsWith("| two defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); + .startsWith("| two defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(9)).isEqualTo("↑ ↓"); assertThat(lines.get(10)) - .startsWith("| three defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); + .startsWith("| three defined in " + CycleReferencedViaOtherBeansConfiguration.class.getName()); assertThat(lines.get(11)).isEqualTo("└─────┘"); assertThat(analysis.getAction()).isNotNull(); } @@ -120,7 +120,7 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { List lines = readDescriptionLines(analysis); assertThat(lines).hasSize(5); assertThat(lines.get(0)) - .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); + .isEqualTo("The dependencies of some of the beans in the application context form a cycle:"); assertThat(lines.get(1)).isEmpty(); assertThat(lines.get(2)).isEqualTo("┌──->──┐"); assertThat(lines.get(3)).startsWith("| bean defined in " + SelfReferenceBeanConfiguration.class.getName()); @@ -165,7 +165,7 @@ class BeanCurrentlyInCreationFailureAnalyzerTests { try { this.context.register(configuration); AbstractAutowireCapableBeanFactory beanFactory = (AbstractAutowireCapableBeanFactory) this.context - .getBeanFactory(); + .getBeanFactory(); beanFactory.setAllowCircularReferences(allowCircularReferences); this.context.refresh(); fail("Expected failure did not occur"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java index 4726c1275d..fea0c3df85 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -54,8 +54,8 @@ class BeanDefinitionOverrideFailureAnalyzerTests { }); String description = analysis.getDescription(); assertThat(description) - .isEqualTo("The bean 'testBean' could not be registered. A bean with that name has already" - + " been defined and overriding is disabled."); + .isEqualTo("The bean 'testBean' could not be registered. A bean with that name has already" + + " been defined and overriding is disabled."); } private FailureAnalysis performAnalysis(Class configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java index 39fa0d576b..f93bde1451 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -46,12 +46,12 @@ class BeanNotOfRequiredTypeFailureAnalyzerTests { FailureAnalysis analysis = performAnalysis(JdkProxyConfiguration.class); assertThat(analysis.getDescription()).startsWith("The bean 'asyncBean'"); assertThat(analysis.getDescription()) - .containsPattern("The bean is of type '" + AsyncBean.class.getPackage().getName() + ".\\$Proxy.*'"); + .containsPattern("The bean is of type '" + AsyncBean.class.getPackage().getName() + ".\\$Proxy.*'"); assertThat(analysis.getDescription()) - .contains(String.format("and implements:%n\t") + SomeInterface.class.getName()); + .contains(String.format("and implements:%n\t") + SomeInterface.class.getName()); assertThat(analysis.getDescription()).contains("Expected a bean of type '" + AsyncBean.class.getName() + "'"); assertThat(analysis.getDescription()) - .contains(String.format("which implements:%n\t") + SomeInterface.class.getName()); + .contains(String.format("which implements:%n\t") + SomeInterface.class.getName()); } private FailureAnalysis performAnalysis(Class configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java index 4bb5afe5c9..f84d8b737f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyNameFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,9 +42,9 @@ class InvalidConfigurationPropertyNameFailureAnalyzerTests { BeanCreationException failure = createFailure(InvalidPrefixConfiguration.class); FailureAnalysis analysis = this.analyzer.analyze(failure); assertThat(analysis.getDescription()) - .contains(String.format("%n Invalid characters: %s%n Bean: %s%n Reason: %s", "'F', 'P'", - "invalidPrefixProperties", "Canonical names should be kebab-case ('-' separated), " - + "lowercase alpha-numeric characters and must start with a letter")); + .contains(String.format("%n Invalid characters: %s%n Bean: %s%n Reason: %s", "'F', 'P'", + "invalidPrefixProperties", "Canonical names should be kebab-case ('-' separated), " + + "lowercase alpha-numeric characters and must start with a letter")); } private BeanCreationException createFailure(Class configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java index f8cf1a3e2b..6f8b468c7c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/InvalidConfigurationPropertyValueFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,8 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { assertCommonParts(failure, analysis); assertThat(analysis.getAction()).contains("Review the value of the property with the provided reason."); assertThat(analysis.getDescription()).contains("Validation failed for the following reason") - .contains("This is not valid.").doesNotContain("Additionally, this property is also set"); + .contains("This is not valid.") + .doesNotContain("Additionally, this property is also set"); } @Test @@ -70,7 +71,7 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { FailureAnalysis analysis = performAnalysis(failure); assertThat(analysis.getAction()).contains("Review the value of the property."); assertThat(analysis.getDescription()).contains("No reason was provided.") - .doesNotContain("Additionally, this property is also set"); + .doesNotContain("Additionally, this property is also set"); } @Test @@ -88,9 +89,9 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { assertCommonParts(failure, analysis); assertThat(analysis.getAction()).contains("Review the value of the property with the provided reason."); assertThat(analysis.getDescription()) - .contains("Additionally, this property is also set in the following property sources:") - .contains("In 'additional' with the value 'valid'") - .contains("In 'another' with the value 'test' (originating from 'TestOrigin test.property')"); + .contains("Additionally, this property is also set in the following property sources:") + .contains("In 'additional' with the value 'valid'") + .contains("In 'another' with the value 'test' (originating from 'TestOrigin test.property')"); } @Test @@ -101,8 +102,9 @@ class InvalidConfigurationPropertyValueFailureAnalyzerTests { } private void assertCommonParts(InvalidConfigurationPropertyValueException failure, FailureAnalysis analysis) { - assertThat(analysis.getDescription()).contains("test.property").contains("invalid") - .contains("TestOrigin test.property"); + assertThat(analysis.getDescription()).contains("test.property") + .contains("invalid") + .contains("TestOrigin test.property"); assertThat(analysis.getCause()).isSameAs(failure); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java index 0a54b31126..e09cf1c510 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/JakartaApiValidationExceptionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -38,8 +38,8 @@ class JakartaApiValidationExceptionFailureAnalyzerTests { @Test void validatedPropertiesTest() { assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) - .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); + .isThrownBy(() -> new AnnotationConfigApplicationContext(TestConfiguration.class).close()) + .satisfies((ex) -> assertThat(new ValidationExceptionFailureAnalyzer().analyze(ex)).isNotNull()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java index a81645e36f..e53afa0e9b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { new HashSet<>(Arrays.asList("com.example.a", "com.example.b")), new HashSet<>(Arrays.asList("com.example.a", "com.example.b"))); FailureAnalysis failureAnalysis = new MutuallyExclusiveConfigurationPropertiesFailureAnalyzer(null) - .analyze(failure); + .analyze(failure); assertThat(failureAnalysis).isNull(); } @@ -81,10 +81,10 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { "Update your configuration so that only one of the mutually exclusive properties is configured."); assertThat(analysis.getDescription()).contains(String.format( "The following configuration properties are mutually exclusive:%n%n\tcom.example.a%n\tcom.example.b%n")) - .contains(String - .format("However, more than one of those properties has been configured at the same time:%n%n" - + "\tcom.example.a (originating from 'TestOrigin test')%n" - + "\tcom.example.b (originating from 'TestOrigin test')%n")); + .contains( + String.format("However, more than one of those properties has been configured at the same time:%n%n" + + "\tcom.example.a (originating from 'TestOrigin test')%n" + + "\tcom.example.b (originating from 'TestOrigin test')%n")); } @Test @@ -93,9 +93,9 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { properties.put("com.example.a", "alpha"); properties.put("com.example.b", "bravo"); this.environment.getPropertySources() - .addFirst(OriginCapablePropertySource.get(new MapPropertySource("test-one", properties))); + .addFirst(OriginCapablePropertySource.get(new MapPropertySource("test-one", properties))); this.environment.getPropertySources() - .addLast(OriginCapablePropertySource.get(new MapPropertySource("test-two", properties))); + .addLast(OriginCapablePropertySource.get(new MapPropertySource("test-two", properties))); MutuallyExclusiveConfigurationPropertiesException failure = new MutuallyExclusiveConfigurationPropertiesException( new HashSet<>(Arrays.asList("com.example.a", "com.example.b")), new HashSet<>(Arrays.asList("com.example.a", "com.example.b"))); @@ -104,12 +104,12 @@ class MutuallyExclusiveConfigurationPropertiesFailureAnalyzerTests { "Update your configuration so that only one of the mutually exclusive properties is configured."); assertThat(analysis.getDescription()).contains(String.format( "The following configuration properties are mutually exclusive:%n%n\tcom.example.a%n\tcom.example.b%n")) - .contains(String - .format("However, more than one of those properties has been configured at the same time:%n%n" - + "\tcom.example.a (originating from 'TestOrigin test-one')%n" - + "\tcom.example.a (originating from 'TestOrigin test-two')%n" - + "\tcom.example.b (originating from 'TestOrigin test-one')%n" - + "\tcom.example.b (originating from 'TestOrigin test-two')%n")); + .contains( + String.format("However, more than one of those properties has been configured at the same time:%n%n" + + "\tcom.example.a (originating from 'TestOrigin test-one')%n" + + "\tcom.example.a (originating from 'TestOrigin test-two')%n" + + "\tcom.example.b (originating from 'TestOrigin test-one')%n" + + "\tcom.example.b (originating from 'TestOrigin test-two')%n")); } private FailureAnalysis performAnalysis(MutuallyExclusiveConfigurationPropertiesException failure) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java index e835b160f8..f1f865e7e7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoSuchMethodFailureAnalyzerTests.java @@ -45,8 +45,8 @@ class NoSuchMethodFailureAnalyzerTests { NoSuchMethodDescriptor descriptor = new NoSuchMethodFailureAnalyzer().getNoSuchMethodDescriptor( "'boolean org.springframework.util.MimeType.isMoreSpecific(org.springframework.util.MimeType)'"); assertThat(descriptor).isNotNull(); - assertThat(descriptor.getErrorMessage()).isEqualTo( - "'boolean org.springframework.util.MimeType.isMoreSpecific(org.springframework.util.MimeType)'"); + assertThat(descriptor.getErrorMessage()) + .isEqualTo("'boolean org.springframework.util.MimeType.isMoreSpecific(org.springframework.util.MimeType)'"); assertThat(descriptor.getClassName()).isEqualTo("org.springframework.util.MimeType"); assertThat(descriptor.getCandidateLocations()).hasSizeGreaterThan(1); List typeHierarchy = descriptor.getTypeHierarchy(); @@ -64,7 +64,7 @@ class NoSuchMethodFailureAnalyzerTests { + "by org.springframework.boot.testsupport.classpath.ModifiedClassPathClassLoader@e0ce6310)."); assertThat(descriptor).isNotNull(); assertThat(descriptor.getErrorMessage()) - .isEqualTo("org/springframework/util/MimeType.isMoreSpecific(Lorg/springframework/util/MimeType;)Z"); + .isEqualTo("org/springframework/util/MimeType.isMoreSpecific(Lorg/springframework/util/MimeType;)Z"); assertThat(descriptor.getClassName()).isEqualTo("org.springframework.util.MimeType"); assertThat(descriptor.getCandidateLocations()).hasSizeGreaterThan(1); List typeHierarchy = descriptor.getTypeHierarchy(); @@ -80,12 +80,12 @@ class NoSuchMethodFailureAnalyzerTests { FailureAnalysis analysis = new NoSuchMethodFailureAnalyzer().analyze(failure); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()) - .contains(NoSuchMethodFailureAnalyzerTests.class.getName() + ".createFailureForMissingMethod(") - .contains("isMoreSpecific(") - .contains("calling method's class, " + NoSuchMethodFailureAnalyzerTests.class.getName() + ",") - .contains("called method's class, org.springframework.util.MimeType,"); + .contains(NoSuchMethodFailureAnalyzerTests.class.getName() + ".createFailureForMissingMethod(") + .contains("isMoreSpecific(") + .contains("calling method's class, " + NoSuchMethodFailureAnalyzerTests.class.getName() + ",") + .contains("called method's class, org.springframework.util.MimeType,"); assertThat(analysis.getAction()).contains(NoSuchMethodFailureAnalyzerTests.class.getName()) - .contains("org.springframework.util.MimeType"); + .contains("org.springframework.util.MimeType"); } @Test @@ -95,12 +95,12 @@ class NoSuchMethodFailureAnalyzerTests { FailureAnalysis analysis = new NoSuchMethodFailureAnalyzer().analyze(failure); assertThat(analysis).isNotNull(); assertThat(analysis.getDescription()).contains(R2dbcMappingContext.class.getName() + ".(") - .contains(R2dbcMappingContext.class.getName() + ".setForceQuote(") - .contains("calling method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") - .contains("called method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") - .contains(" org.springframework.data.r2dbc.mapping.R2dbcMappingContext") - .contains(" org.springframework.data.relational.core.mapping.RelationalMappingContext") - .contains(" org.springframework.data.mapping.context.AbstractMappingContext"); + .contains(R2dbcMappingContext.class.getName() + ".setForceQuote(") + .contains("calling method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") + .contains("called method's class, org.springframework.data.r2dbc.mapping.R2dbcMappingContext,") + .contains(" org.springframework.data.r2dbc.mapping.R2dbcMappingContext") + .contains(" org.springframework.data.relational.core.mapping.RelationalMappingContext") + .contains(" org.springframework.data.mapping.context.AbstractMappingContext"); assertThat(analysis.getAction()).contains("org.springframework.data.r2dbc.mapping.R2dbcMappingContext"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java index 3950d03607..35943e7ccf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/NoUniqueBeanDefinitionFailureAnalyzerTests.java @@ -113,9 +113,9 @@ class NoUniqueBeanDefinitionFailureAnalyzerTests { private void assertFoundBeans(FailureAnalysis analysis) { assertThat(analysis.getDescription()).contains("beanOne: defined in unknown location"); assertThat(analysis.getDescription()) - .contains("beanTwo: defined by method 'beanTwo' in " + DuplicateBeansProducer.class.getName()); + .contains("beanTwo: defined by method 'beanTwo' in " + DuplicateBeansProducer.class.getName()); assertThat(analysis.getDescription()) - .contains("beanThree: defined by method 'beanThree' in " + ParentProducer.class.getName()); + .contains("beanThree: defined by method 'beanThree' in " + ParentProducer.class.getName()); assertThat(analysis.getDescription()).contains("barTestBean"); assertThat(analysis.getDescription()).contains("fooTestBean"); assertThat(analysis.getDescription()).contains("xmlTestBean"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java index 6b9979b036..2284d6af82 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/PatternParseFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -38,8 +38,8 @@ class PatternParseFailureAnalyzerTests { FailureAnalysis failureAnalysis = performAnalysis("/spring/**/framework"); assertThat(failureAnalysis.getDescription()).contains("Invalid mapping pattern detected: /spring/**/framework"); assertThat(failureAnalysis.getAction()) - .contains("Fix this pattern in your application or switch to the legacy parser" - + " implementation with 'spring.mvc.pathmatch.matching-strategy=ant_path_matcher'."); + .contains("Fix this pattern in your application or switch to the legacy parser" + + " implementation with 'spring.mvc.pathmatch.matching-strategy=ant_path_matcher'."); } private FailureAnalysis performAnalysis(String pattern) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java index 634e9a8e97..558a75adf8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ConfigTreePropertySourceTests.java @@ -52,20 +52,20 @@ class ConfigTreePropertySourceTests { @Test void createWhenNameIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource(null, this.directory)) - .withMessageContaining("name must contain"); + .withMessageContaining("name must contain"); } @Test void createWhenSourceIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource("test", null)) - .withMessage("Property source must not be null"); + .withMessage("Property source must not be null"); } @Test void createWhenSourceDoesNotExistThrowsException() { Path missing = this.directory.resolve("missing"); assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource("test", missing)) - .withMessage("Directory '" + missing + "' does not exist"); + .withMessage("Directory '" + missing + "' does not exist"); } @Test @@ -73,7 +73,7 @@ class ConfigTreePropertySourceTests { Path file = this.directory.resolve("file"); FileCopyUtils.copy("test".getBytes(StandardCharsets.UTF_8), file.toFile()); assertThatIllegalArgumentException().isThrownBy(() -> new ConfigTreePropertySource("test", file)) - .withMessage("File '" + file + "' is not a directory"); + .withMessage("File '" + file + "' is not a directory"); } @Test @@ -135,7 +135,7 @@ class ConfigTreePropertySourceTests { Path b = this.directory.resolve("b"); Files.delete(b); assertThatIllegalStateException().isThrownBy(() -> propertySource.getProperty("b").toString()) - .withMessage("The property file '" + b + "' no longer exists"); + .withMessage("The property file '" + b + "' no longer exists"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListenerTests.java index 47b15d2d03..40145f2ce7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -71,7 +71,7 @@ class EnvironmentPostProcessorApplicationListenerTests { @Test void createWhenHasFactoryUsesFactory() { EnvironmentPostProcessorApplicationListener listener = EnvironmentPostProcessorApplicationListener - .with(EnvironmentPostProcessorsFactory.of(TestEnvironmentPostProcessor.class)); + .with(EnvironmentPostProcessorsFactory.of(TestEnvironmentPostProcessor.class)); List postProcessors = listener.getEnvironmentPostProcessors(null, this.bootstrapContext); assertThat(postProcessors).hasSize(1); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java index 7682491b8f..6398bab321 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/EnvironmentPostProcessorsFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ class EnvironmentPostProcessorsFactoryTests { @Test void ofClassesReturnsFactory() { EnvironmentPostProcessorsFactory factory = EnvironmentPostProcessorsFactory - .of(TestEnvironmentPostProcessor.class); + .of(TestEnvironmentPostProcessor.class); List processors = factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext); assertThat(processors).hasSize(1); @@ -61,7 +61,7 @@ class EnvironmentPostProcessorsFactoryTests { @Test void ofClassNamesReturnsFactory() { EnvironmentPostProcessorsFactory factory = EnvironmentPostProcessorsFactory - .of(TestEnvironmentPostProcessor.class.getName()); + .of(TestEnvironmentPostProcessor.class.getName()); List processors = factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext); assertThat(processors).hasSize(1); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java index 7b0ea87d81..6f7cbfda8c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -37,7 +37,7 @@ class NoSnakeYamlPropertySourceLoaderTests { void load() { ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes()); assertThatIllegalStateException().isThrownBy(() -> this.loader.load("resource", resource)) - .withMessageContaining("Attempted to load resource but snakeyaml was not found on the classpath"); + .withMessageContaining("Attempted to load resource but snakeyaml was not found on the classpath"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java index 923aad052a..6fdb3e743b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java @@ -56,8 +56,10 @@ class OriginTrackedPropertiesLoaderTests { void compareToJavaProperties() throws Exception { Properties java = PropertiesLoaderUtils.loadProperties(this.resource); Properties ours = new Properties(); - new OriginTrackedPropertiesLoader(this.resource).load(false).get(0).asMap() - .forEach((k, v) -> ours.put(k, v.getValue())); + new OriginTrackedPropertiesLoader(this.resource).load(false) + .get(0) + .asMap() + .forEach((k, v) -> ours.put(k, v.getValue())); assertThat(ours).isEqualTo(java); } @@ -94,7 +96,7 @@ class OriginTrackedPropertiesLoaderTests { // gh-12716 ClassPathResource resource = new ClassPathResource("test-properties-malformed-unicode.properties", getClass()); assertThatIllegalStateException().isThrownBy(() -> new OriginTrackedPropertiesLoader(resource).load()) - .withMessageContaining("Malformed \\uxxxx encoding"); + .withMessageContaining("Malformed \\uxxxx encoding"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java index b644d1e94f..77732be5db 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/RandomValuePropertySourceTests.java @@ -76,7 +76,7 @@ class RandomValuePropertySourceTests { @Test void intRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int[4,4]")) - .withMessage("Lower bound must be less than upper bound."); + .withMessage("Lower bound must be less than upper bound."); } @Test @@ -95,13 +95,13 @@ class RandomValuePropertySourceTests { @Test void intMaxZero() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int(0)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test void intNegativeBound() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.int(-5)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test @@ -119,7 +119,7 @@ class RandomValuePropertySourceTests { @Test void longRangeWhenLowerBoundEqualsUpperBoundShouldFailWithIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long[4,4]")) - .withMessage("Lower bound must be less than upper bound."); + .withMessage("Lower bound must be less than upper bound."); } @Test @@ -138,13 +138,13 @@ class RandomValuePropertySourceTests { @Test void longMaxZero() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long(0)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test void longNegativeBound() { assertThatIllegalArgumentException().isThrownBy(() -> this.source.getProperty("random.long(-5)")) - .withMessage("Bound must be positive."); + .withMessage("Bound must be positive."); } @Test @@ -183,8 +183,9 @@ class RandomValuePropertySourceTests { @Test void addToEnvironmentAddsAfterSystemEnvironment() { MockEnvironment environment = new MockEnvironment(); - environment.getPropertySources().addFirst(new SystemEnvironmentPropertySource( - StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, Collections.emptyMap())); + environment.getPropertySources() + .addFirst(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, + Collections.emptyMap())); RandomValuePropertySource.addToEnvironment(environment); assertThat(environment.getPropertySources().stream().map(PropertySource::getName)).containsExactly( StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java index 2941b3c15b..16d859df55 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/ReflectionEnvironmentPostProcessorsFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -115,8 +115,8 @@ class ReflectionEnvironmentPostProcessorsFactoryTests { ReflectionEnvironmentPostProcessorsFactory factory = new ReflectionEnvironmentPostProcessorsFactory(null, BadEnvironmentPostProcessor.class.getName()); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext)) - .withMessageContaining("Unable to instantiate"); + .isThrownBy(() -> factory.getEnvironmentPostProcessors(this.logFactory, this.bootstrapContext)) + .withMessageContaining("Unable to instantiate"); } private EnvironmentPostProcessorsFactoryAssert assertThatFactory(EnvironmentPostProcessorsFactory factory) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java index 450db9c6db..9412ae2a47 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,8 +53,8 @@ class SpringApplicationJsonEnvironmentPostProcessorTests { assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar"); assertThatExceptionOfType(JsonParseException.class) - .isThrownBy(() -> this.processor.postProcessEnvironment(this.environment, null)) - .withMessageContaining("Cannot parse JSON"); + .isThrownBy(() -> this.processor.postProcessEnvironment(this.environment, null)) + .withMessageContaining("Cannot parse JSON"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java index 5b29b01970..d90884c9ab 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SystemEnvironmentPropertySourceEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -57,7 +57,8 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { PropertySource original = this.environment.getPropertySources().get("systemEnvironment"); postProcessor.postProcessEnvironment(this.environment, this.application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); Map originalMap = (Map) original.getSource(); Map replacedMap = replaced.getSource(); originalMap.forEach((key, value) -> { @@ -72,7 +73,8 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); postProcessor.postProcessEnvironment(this.environment, this.application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); assertThat(replaced.getOrigin("NON_EXISTENT")).isNull(); } @@ -80,11 +82,12 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { void replacedPropertySourceShouldResolveProperty() { SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor(); Map source = Collections.singletonMap("FOO_BAR_BAZ", "hello"); - this.environment.getPropertySources().replace("systemEnvironment", - new SystemEnvironmentPropertySource("systemEnvironment", source)); + this.environment.getPropertySources() + .replace("systemEnvironment", new SystemEnvironmentPropertySource("systemEnvironment", source)); postProcessor.postProcessEnvironment(this.environment, this.application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); SystemEnvironmentOrigin origin = (SystemEnvironmentOrigin) replaced.getOrigin("foo.bar.baz"); assertThat(origin.getProperty()).isEqualTo("FOO_BAR_BAZ"); assertThat(replaced.getProperty("foo.bar.baz")).isEqualTo("hello"); @@ -97,7 +100,8 @@ class SystemEnvironmentPropertySourceEnvironmentPostProcessorTests { application.setEnvironmentPrefix("my"); postProcessor.postProcessEnvironment(this.environment, application); OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment - .getPropertySources().get("systemEnvironment"); + .getPropertySources() + .get("systemEnvironment"); assertThat(replaced.getPrefix()).isEqualTo("my"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java index 8ee156d04d..c5d076a55d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/YamlPropertySourceLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,7 +59,7 @@ class YamlPropertySourceLoaderTests { } ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes()); EnumerablePropertySource source = (EnumerablePropertySource) this.loader.load("resource", resource) - .get(0); + .get(0); assertThat(source).isNotNull(); assertThat(source.getPropertyNames()).isEqualTo(StringUtils.toStringArray(expected)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java index 276539a8b9..6ec33ae204 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/BuildPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -62,7 +62,7 @@ class BuildPropertiesTests { RuntimeHints runtimeHints = new RuntimeHints(); new BuildProperties.BuildPropertiesRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.resource().forResource("META-INF/build-info.properties")) - .accepts(runtimeHints); + .accepts(runtimeHints); } private static Properties createProperties(String group, String artifact, String version, String buildTime) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java index 8d19236fe9..f6ae8a6974 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -130,18 +130,24 @@ class JsonComponentModuleTests { load(ComponentWithInnerAbstractClass.class); ConfigurableListableBeanFactory beanFactory = this.context.getBeanFactory(); BeanFactoryInitializationAotContribution contribution = new JsonComponentBeanFactoryInitializationAotProcessor() - .processAheadOfTime(beanFactory); + .processAheadOfTime(beanFactory); TestGenerationContext generationContext = new TestGenerationContext(); contribution.applyTo(generationContext, null); RuntimeHints runtimeHints = generationContext.getRuntimeHints(); - assertThat(RuntimeHintsPredicates.reflection().onType(ComponentWithInnerAbstractClass.class) - .withMemberCategory(MemberCategory.DECLARED_CLASSES)).accepts(runtimeHints); - assertThat(RuntimeHintsPredicates.reflection().onType(ConcreteSerializer.class) - .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); - assertThat(RuntimeHintsPredicates.reflection().onType(AbstractSerializer.class) - .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).negate()).accepts(runtimeHints); - assertThat(RuntimeHintsPredicates.reflection().onType(NotSuitable.class) - .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS).negate()).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(ComponentWithInnerAbstractClass.class) + .withMemberCategory(MemberCategory.DECLARED_CLASSES)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(ConcreteSerializer.class) + .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(AbstractSerializer.class) + .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS) + .negate()).accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(NotSuitable.class) + .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS) + .negate()).accepts(runtimeHints); } private void load(Class... configs) { @@ -175,7 +181,7 @@ class JsonComponentModuleTests { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); assertThatExceptionOfType(JsonMappingException.class) - .isThrownBy(() -> mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class)); + .isThrownBy(() -> mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class)); NameAndCareer nameAndCareer = mapper.readValue("{\"name\":\"spring\",\"career\":\"developer\"}", NameAndCareer.class); assertThat(nameAndCareer.getName()).isEqualTo("spring"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessorTests.java index 600e15257b..b2e19ea7b5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleEntriesBeanRegistrationAotProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -65,11 +65,12 @@ class JsonMixinModuleEntriesBeanRegistrationAotProcessorTests { registerEntries(RenameMixInClass.class); processAheadOfTime(); RuntimeHints runtimeHints = this.generationContext.getRuntimeHints(); - assertThat(RuntimeHintsPredicates.reflection().onType(RenameMixInClass.class) - .withMemberCategories(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)) - .accepts(runtimeHints); + assertThat(RuntimeHintsPredicates.reflection() + .onType(RenameMixInClass.class) + .withMemberCategories(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)) + .accepts(runtimeHints); assertThat(RuntimeHintsPredicates.reflection().onMethod(RenameMixInClass.class, "getName").introspect()) - .accepts(runtimeHints); + .accepts(runtimeHints); } @Test @@ -78,22 +79,23 @@ class JsonMixinModuleEntriesBeanRegistrationAotProcessorTests { compile((freshContext, compiled) -> { assertThat(freshContext.getBean(TestConfiguration.class).scanningInvoked).isFalse(); JsonMixinModuleEntries jsonMixinModuleEntries = freshContext.getBean(JsonMixinModuleEntries.class); - assertThat(jsonMixinModuleEntries).extracting("entries", InstanceOfAssertFactories.MAP).containsExactly( - entry(Name.class, RenameMixInClass.class), entry(NameAndAge.class, RenameMixInClass.class)); + assertThat(jsonMixinModuleEntries).extracting("entries", InstanceOfAssertFactories.MAP) + .containsExactly(entry(Name.class, RenameMixInClass.class), + entry(NameAndAge.class, RenameMixInClass.class)); }); } @Test void processAheadOfTimeWhenNonAccessibleClassShouldRegisterClassName() { Class privateMixinClass = ClassUtils - .resolveClassName("org.springframework.boot.jackson.scan.e.PrivateMixInClass", null); + .resolveClassName("org.springframework.boot.jackson.scan.e.PrivateMixInClass", null); registerEntries(privateMixinClass); compile((freshContext, compiled) -> { assertThat(freshContext.getBean(TestConfiguration.class).scanningInvoked).isFalse(); JsonMixinModuleEntries jsonMixinModuleEntries = freshContext.getBean(JsonMixinModuleEntries.class); - assertThat(jsonMixinModuleEntries).extracting("entries", InstanceOfAssertFactories.MAP).containsExactly( - entry(Name.class.getName(), privateMixinClass.getName()), - entry(NameAndAge.class.getName(), privateMixinClass.getName())); + assertThat(jsonMixinModuleEntries).extracting("entries", InstanceOfAssertFactories.MAP) + .containsExactly(entry(Name.class.getName(), privateMixinClass.getName()), + entry(NameAndAge.class.getName(), privateMixinClass.getName())); }); } @@ -110,7 +112,7 @@ class JsonMixinModuleEntriesBeanRegistrationAotProcessorTests { TestCompiler.forSystem().with(this.generationContext).compile((compiled) -> { GenericApplicationContext freshApplicationContext = new GenericApplicationContext(); ApplicationContextInitializer initializer = compiled - .getInstance(ApplicationContextInitializer.class, className.toString()); + .getInstance(ApplicationContextInitializer.class, className.toString()); initializer.initialize(freshApplicationContext); freshApplicationContext.refresh(); result.accept(freshApplicationContext, compiled); @@ -119,8 +121,10 @@ class JsonMixinModuleEntriesBeanRegistrationAotProcessorTests { private void registerEntries(Class... basePackageClasses) { List packageNames = Arrays.stream(basePackageClasses).map(Class::getPackageName).toList(); - this.applicationContext.registerBeanDefinition("configuration", BeanDefinitionBuilder - .rootBeanDefinition(TestConfiguration.class).addConstructorArgValue(packageNames).getBeanDefinition()); + this.applicationContext.registerBeanDefinition("configuration", + BeanDefinitionBuilder.rootBeanDefinition(TestConfiguration.class) + .addConstructorArgValue(packageNames) + .getBeanDefinition()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java index 59557d643a..42bf7a8f81 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonMixinModuleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class JsonMixinModuleTests { @SuppressWarnings("removal") void createWhenContextIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new JsonMixinModule(null, Collections.emptyList())) - .withMessageContaining("Context must not be null"); + .withMessageContaining("Context must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java index 776474c46e..8461ce6ae8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,8 +68,8 @@ class JsonObjectDeserializerTests { @Test void nullSafeValueWhenClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) - .withMessageContaining("Type must not be null"); + .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) + .withMessageContaining("Type must not be null"); } @Test @@ -147,15 +147,15 @@ class JsonObjectDeserializerTests { @Test void nullSafeValueWhenClassIsUnknownShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), InputStream.class)) - .withMessageContaining("Unsupported value type java.io.InputStream"); + .isThrownBy(() -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), InputStream.class)) + .withMessageContaining("Unsupported value type java.io.InputStream"); } @Test void getRequiredNodeWhenTreeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(null, "test")) - .withMessageContaining("Tree must not be null"); + .withMessageContaining("Tree must not be null"); } @Test @@ -163,7 +163,7 @@ class JsonObjectDeserializerTests { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(null); assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) - .withMessageContaining("Missing JSON field 'test'"); + .withMessageContaining("Missing JSON field 'test'"); } @Test @@ -171,7 +171,7 @@ class JsonObjectDeserializerTests { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(NullNode.instance); assertThatIllegalStateException().isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) - .withMessageContaining("Missing JSON field 'test'"); + .withMessageContaining("Missing JSON field 'test'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHintsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHintsTests.java index 8f5658db80..3332d07326 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderRuntimeHintsTests.java @@ -38,18 +38,20 @@ class DataSourceBuilderRuntimeHintsTests { @Test void shouldRegisterDataSourceConstructors() { ReflectionHints hints = registerHints(); - Stream.of(com.mchange.v2.c3p0.ComboPooledDataSource.class, org.h2.jdbcx.JdbcDataSource.class, - com.zaxxer.hikari.HikariDataSource.class, org.apache.commons.dbcp2.BasicDataSource.class, - oracle.jdbc.datasource.OracleDataSource.class, oracle.ucp.jdbc.PoolDataSource.class, - org.postgresql.ds.PGSimpleDataSource.class, - org.springframework.jdbc.datasource.SimpleDriverDataSource.class, - org.apache.tomcat.jdbc.pool.DataSource.class).forEach((dataSourceType) -> { - TypeHint typeHint = hints.getTypeHint(dataSourceType); - assertThat(typeHint).withFailMessage(() -> "No hints found for data source type " + dataSourceType) - .isNotNull(); - Set memberCategories = typeHint.getMemberCategories(); - assertThat(memberCategories).containsExactly(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); - }); + Stream + .of(com.mchange.v2.c3p0.ComboPooledDataSource.class, org.h2.jdbcx.JdbcDataSource.class, + com.zaxxer.hikari.HikariDataSource.class, org.apache.commons.dbcp2.BasicDataSource.class, + oracle.jdbc.datasource.OracleDataSource.class, oracle.ucp.jdbc.PoolDataSource.class, + org.postgresql.ds.PGSimpleDataSource.class, + org.springframework.jdbc.datasource.SimpleDriverDataSource.class, + org.apache.tomcat.jdbc.pool.DataSource.class) + .forEach((dataSourceType) -> { + TypeHint typeHint = hints.getTypeHint(dataSourceType); + assertThat(typeHint).withFailMessage(() -> "No hints found for data source type " + dataSourceType) + .isNotNull(); + Set memberCategories = typeHint.getMemberCategories(); + assertThat(memberCategories).containsExactly(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); + }); } private ReflectionHints registerHints() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java index ad2852adfc..216f22d5b1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -89,38 +89,49 @@ class DataSourceBuilderTests { @Test void buildWhenHikariNotAvailableReturnsTomcatDataSource() { - this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")).url("jdbc:h2:test") - .build(); + this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")) + .url("jdbc:h2:test") + .build(); assertThat(this.dataSource).isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class); } @Test // gh-26633 void buildWhenTomcatDataSourceWithNullPasswordReturnsDataSource() { - this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")).url("jdbc:h2:test") - .username("test").password(null).build(); + this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari")) + .url("jdbc:h2:test") + .username("test") + .password(null) + .build(); assertThat(this.dataSource).isInstanceOf(org.apache.tomcat.jdbc.pool.DataSource.class); } @Test void buildWhenHikariAndTomcatNotAvailableReturnsDbcp2DataSource() { this.dataSource = DataSourceBuilder - .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) - .url("jdbc:h2:test").build(); + .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) + .url("jdbc:h2:test") + .build(); assertThat(this.dataSource).isInstanceOf(BasicDataSource.class); } @Test // gh-26633 void buildWhenDbcp2DataSourceWithNullPasswordReturnsDbcp2DataSource() { this.dataSource = DataSourceBuilder - .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) - .url("jdbc:h2:test").username("test").password(null).build(); + .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool")) + .url("jdbc:h2:test") + .username("test") + .password(null) + .build(); assertThat(this.dataSource).isInstanceOf(BasicDataSource.class); } @Test void buildWhenHikariAndTomcatAndDbcpNotAvailableReturnsOracleUcpDataSource() { - this.dataSource = DataSourceBuilder.create(new HidePackagesClassLoader("com.zaxxer.hikari", - "org.apache.tomcat.jdbc.pool", "org.apache.commons.dbcp2")).url("jdbc:h2:test").build(); + this.dataSource = DataSourceBuilder + .create(new HidePackagesClassLoader("com.zaxxer.hikari", "org.apache.tomcat.jdbc.pool", + "org.apache.commons.dbcp2")) + .url("jdbc:h2:test") + .build(); assertThat(this.dataSource).isInstanceOf(PoolDataSourceImpl.class); } @@ -141,8 +152,11 @@ class DataSourceBuilderTests { @Test void buildWhenOracleTypeSpecifiedReturnsExpectedDataSource() throws SQLException { - this.dataSource = DataSourceBuilder.create().url("jdbc:oracle:thin:@localhost:1521:xe") - .type(OracleDataSource.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:oracle:thin:@localhost:1521:xe") + .type(OracleDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(OracleDataSource.class); OracleDataSource oracleDataSource = (OracleDataSource) this.dataSource; assertThat(oracleDataSource.getURL()).isEqualTo("jdbc:oracle:thin:@localhost:1521:xe"); @@ -151,9 +165,12 @@ class DataSourceBuilderTests { @Test // gh-26631 void buildWhenOracleTypeSpecifiedWithDriverClassReturnsExpectedDataSource() throws SQLException { - this.dataSource = DataSourceBuilder.create().url("jdbc:oracle:thin:@localhost:1521:xe") - .type(OracleDataSource.class).driverClassName("oracle.jdbc.pool.OracleDataSource").username("test") - .build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:oracle:thin:@localhost:1521:xe") + .type(OracleDataSource.class) + .driverClassName("oracle.jdbc.pool.OracleDataSource") + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(OracleDataSource.class); OracleDataSource oracleDataSource = (OracleDataSource) this.dataSource; assertThat(oracleDataSource.getURL()).isEqualTo("jdbc:oracle:thin:@localhost:1521:xe"); @@ -162,8 +179,11 @@ class DataSourceBuilderTests { @Test void buildWhenOracleUcpTypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver") - .type(PoolDataSourceImpl.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .type(PoolDataSourceImpl.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(PoolDataSourceImpl.class); PoolDataSourceImpl upcDataSource = (PoolDataSourceImpl) this.dataSource; assertThat(upcDataSource.getConnectionFactoryClassName()).isEqualTo("org.hsqldb.jdbc.JDBCDriver"); @@ -172,8 +192,12 @@ class DataSourceBuilderTests { @Test void buildWhenH2TypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:h2:test").type(JdbcDataSource.class).username("test") - .password("secret").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:h2:test") + .type(JdbcDataSource.class) + .username("test") + .password("secret") + .build(); assertThat(this.dataSource).isInstanceOf(JdbcDataSource.class); JdbcDataSource h2DataSource = (JdbcDataSource) this.dataSource; assertThat(h2DataSource.getUser()).isEqualTo("test"); @@ -182,8 +206,13 @@ class DataSourceBuilderTests { @Test // gh-26631 void buildWhenH2TypeSpecifiedWithDriverClassReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:h2:test").type(JdbcDataSource.class) - .driverClassName("org.h2.jdbcx.JdbcDataSource").username("test").password("secret").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:h2:test") + .type(JdbcDataSource.class) + .driverClassName("org.h2.jdbcx.JdbcDataSource") + .username("test") + .password("secret") + .build(); assertThat(this.dataSource).isInstanceOf(JdbcDataSource.class); JdbcDataSource h2DataSource = (JdbcDataSource) this.dataSource; assertThat(h2DataSource.getUser()).isEqualTo("test"); @@ -192,8 +221,11 @@ class DataSourceBuilderTests { @Test void buildWhenPostgresTypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:postgresql://localhost/test") - .type(PGSimpleDataSource.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:postgresql://localhost/test") + .type(PGSimpleDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(PGSimpleDataSource.class); PGSimpleDataSource pgDataSource = (PGSimpleDataSource) this.dataSource; assertThat(pgDataSource.getUser()).isEqualTo("test"); @@ -201,9 +233,12 @@ class DataSourceBuilderTests { @Test // gh-26631 void buildWhenPostgresTypeSpecifiedWithDriverClassReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:postgresql://localhost/test") - .type(PGSimpleDataSource.class).driverClassName("org.postgresql.ds.PGSimpleDataSource").username("test") - .build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:postgresql://localhost/test") + .type(PGSimpleDataSource.class) + .driverClassName("org.postgresql.ds.PGSimpleDataSource") + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(PGSimpleDataSource.class); PGSimpleDataSource pgDataSource = (PGSimpleDataSource) this.dataSource; assertThat(pgDataSource.getUser()).isEqualTo("test"); @@ -211,8 +246,11 @@ class DataSourceBuilderTests { @Test // gh-26647 void buildWhenSqlServerTypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:sqlserver://localhost/test") - .type(SQLServerDataSource.class).username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:sqlserver://localhost/test") + .type(SQLServerDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(SQLServerDataSource.class); SQLServerDataSource sqlServerDataSource = (SQLServerDataSource) this.dataSource; assertThat(sqlServerDataSource.getUser()).isEqualTo("test"); @@ -226,8 +264,11 @@ class DataSourceBuilderTests { @Test void buildWhenCustomSubclassTypeSpecifiedReturnsDataSourceWithOnlyBasePropertiesSet() { - this.dataSource = DataSourceBuilder.create().url("jdbc:h2:test").type(CustomTomcatDataSource.class) - .username("test").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:h2:test") + .type(CustomTomcatDataSource.class) + .username("test") + .build(); assertThat(this.dataSource).isInstanceOf(CustomTomcatDataSource.class); CustomTomcatDataSource testDataSource = (CustomTomcatDataSource) this.dataSource; assertThat(testDataSource.getUrl()).isEqualTo("jdbc:h2:test"); @@ -240,8 +281,13 @@ class DataSourceBuilderTests { @Test void buildWhenCustomTypeSpecifiedReturnsDataSourceWithPropertiesSetViaReflection() { - this.dataSource = DataSourceBuilder.create().type(CustomDataSource.class).username("test").password("secret") - .url("jdbc:h2:test").driverClassName("com.example").build(); + this.dataSource = DataSourceBuilder.create() + .type(CustomDataSource.class) + .username("test") + .password("secret") + .url("jdbc:h2:test") + .driverClassName("com.example") + .build(); assertThat(this.dataSource).isInstanceOf(CustomDataSource.class); CustomDataSource testDataSource = (CustomDataSource) this.dataSource; assertThat(testDataSource.getUrl()).isEqualTo("jdbc:h2:test"); @@ -252,8 +298,10 @@ class DataSourceBuilderTests { @Test void buildWhenCustomTypeSpecifiedAndNoSuitableOptionalSetterBuilds() { - assertThatNoException().isThrownBy(() -> DataSourceBuilder.create().type(LimitedCustomDataSource.class) - .driverClassName("com.example").build()); + assertThatNoException().isThrownBy(() -> DataSourceBuilder.create() + .type(LimitedCustomDataSource.class) + .driverClassName("com.example") + .build()); } @Test @@ -268,8 +316,9 @@ class DataSourceBuilderTests { dataSource.setUsername("test"); dataSource.setPassword("secret"); dataSource.setJdbcUrl("jdbc:h2:test"); - HikariDataSource built = (HikariDataSource) DataSourceBuilder.derivedFrom(dataSource).url("jdbc:h2:test2") - .build(); + HikariDataSource built = (HikariDataSource) DataSourceBuilder.derivedFrom(dataSource) + .url("jdbc:h2:test2") + .build(); assertThat(built.getUsername()).isEqualTo("test"); assertThat(built.getPassword()).isEqualTo("secret"); assertThat(built.getJdbcUrl()).isEqualTo("jdbc:h2:test2"); @@ -295,7 +344,7 @@ class DataSourceBuilderTests { dataSource.setPassword("secret"); dataSource.setURL("example.com"); assertThatExceptionOfType(UnsupportedDataSourcePropertyException.class) - .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); + .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); } @Test @@ -305,7 +354,7 @@ class DataSourceBuilderTests { dataSource.setPassword("secret"); dataSource.setURL("example.com"); assertThatExceptionOfType(UnsupportedDataSourcePropertyException.class) - .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); + .isThrownBy(() -> DataSourceBuilder.derivedFrom(dataSource).url("example.org").build()); } @Test @@ -316,10 +365,13 @@ class DataSourceBuilderTests { dataSource.setURL("example.com"); DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource); oracle.jdbc.datasource.impl.OracleDataSource built = (oracle.jdbc.datasource.impl.OracleDataSource) builder - .username("test2").password("secret2").build(); + .username("test2") + .password("secret2") + .build(); assertThat(built.getUser()).isEqualTo("test2"); - assertThat(built).extracting("password").extracting((opaque) -> ((OpaqueString) opaque).get()) - .isEqualTo("secret2"); + assertThat(built).extracting("password") + .extracting((opaque) -> ((OpaqueString) opaque).get()) + .isEqualTo("secret2"); assertThat(built.getURL()).isEqualTo("example.com"); } @@ -332,16 +384,19 @@ class DataSourceBuilderTests { DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource); PoolDataSource built = (PoolDataSource) builder.username("test2").password("secret2").build(); assertThat(built.getUser()).isEqualTo("test2"); - assertThat(built).extracting("password").extracting((opaque) -> ((oracle.ucp.util.OpaqueString) opaque).get()) - .isEqualTo("secret2"); + assertThat(built).extracting("password") + .extracting((opaque) -> ((oracle.ucp.util.OpaqueString) opaque).get()) + .isEqualTo("secret2"); assertThat(built.getURL()).isEqualTo("example.com"); } @Test void buildWhenDerivedFromEmbeddedDatabase() { EmbeddedDatabase database = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).build(); - SimpleDriverDataSource built = (SimpleDriverDataSource) DataSourceBuilder.derivedFrom(database).username("test") - .password("secret").build(); + SimpleDriverDataSource built = (SimpleDriverDataSource) DataSourceBuilder.derivedFrom(database) + .username("test") + .password("secret") + .build(); assertThat(built.getUsername()).isEqualTo("test"); assertThat(built.getPassword()).isEqualTo("secret"); assertThat(built.getUrl()).startsWith("jdbc:hsqldb:mem"); @@ -379,8 +434,9 @@ class DataSourceBuilderTests { dataSource.setUsername("test"); dataSource.setPassword("secret"); dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres"); - DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource).username("alice") - .password("confidential"); + DataSourceBuilder builder = DataSourceBuilder.derivedFrom(dataSource) + .username("alice") + .password("confidential"); CustomDataSource testSource = (CustomDataSource) builder.build(); assertThat(testSource).isNotSameAs(dataSource); assertThat(testSource.getUsername()).isEqualTo("alice"); @@ -403,9 +459,13 @@ class DataSourceBuilderTests { @Test // gh-31920 void buildWhenC3P0TypeSpecifiedReturnsExpectedDataSource() { - this.dataSource = DataSourceBuilder.create().url("jdbc:postgresql://localhost:5432/postgres") - .type(ComboPooledDataSource.class).username("test").password("secret") - .driverClassName("com.example.Driver").build(); + this.dataSource = DataSourceBuilder.create() + .url("jdbc:postgresql://localhost:5432/postgres") + .type(ComboPooledDataSource.class) + .username("test") + .password("secret") + .driverClassName("com.example.Driver") + .build(); assertThat(this.dataSource).isInstanceOf(ComboPooledDataSource.class); ComboPooledDataSource c3p0DataSource = (ComboPooledDataSource) this.dataSource; assertThat(c3p0DataSource.getJdbcUrl()).isEqualTo("jdbc:postgresql://localhost:5432/postgres"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java index cd3ce07f37..068ea8c6fb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperNoSpringJdbcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class DataSourceUnwrapperNoSpringJdbcTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -50,7 +50,7 @@ class DataSourceUnwrapperNoSpringJdbcTests { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, PoolConfiguration.class, DataSourceProxy.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } private DataSource wrapInProxy(DataSource dataSource) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java index 0f93285fdd..b93bfd07ac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,14 +47,14 @@ class DataSourceUnwrapperTests { void unwrapWithTarget() { DataSource dataSource = new HikariDataSource(); assertThat(DataSourceUnwrapper.unwrap(dataSource, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test void unwrapWithWrongTarget() { DataSource dataSource = new HikariDataSource(); assertThat(DataSourceUnwrapper.unwrap(dataSource, SmartDataSource.class, SingleConnectionDataSource.class)) - .isNull(); + .isNull(); } @Test @@ -62,7 +62,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInDelegate(wrapInDelegate(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -70,7 +70,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -78,7 +78,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInDelegate(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -86,7 +86,7 @@ class DataSourceUnwrapperTests { DataSource dataSource = new HikariDataSource(); DataSource actual = wrapInProxy(wrapInDelegate(wrapInDelegate(wrapInProxy(wrapInDelegate(dataSource))))); assertThat(DataSourceUnwrapper.unwrap(actual, HikariConfigMXBean.class, HikariDataSource.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test @@ -94,7 +94,7 @@ class DataSourceUnwrapperTests { org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); DataSource actual = wrapInDelegate(wrapInProxy(dataSource)); assertThat(DataSourceUnwrapper.unwrap(actual, PoolConfiguration.class, DataSourceProxy.class)) - .isSameAs(dataSource); + .isSameAs(dataSource); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java index 511bc8e29b..f2bbd85bac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,8 @@ import static org.assertj.core.api.Assertions.assertThat; class DatabaseDriverClassNameTests { private static final Set EXCLUDED_DRIVERS = Collections - .unmodifiableSet(EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, - DatabaseDriver.HANA, DatabaseDriver.PHOENIX, DatabaseDriver.TERADATA, DatabaseDriver.REDSHIFT)); + .unmodifiableSet(EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, + DatabaseDriver.HANA, DatabaseDriver.PHOENIX, DatabaseDriver.TERADATA, DatabaseDriver.REDSHIFT)); @ParameterizedTest(name = "{0} {2}") @MethodSource @@ -84,9 +84,10 @@ class DatabaseDriverClassNameTests { private static Stream argumentsForType(Class clazz, Predicate predicate, Function classNameExtractor) { - return Stream.of(DatabaseDriver.values()).filter((databaseDriver) -> !EXCLUDED_DRIVERS.contains(databaseDriver)) - .filter(predicate) - .map((databaseDriver) -> Arguments.of(databaseDriver, classNameExtractor.apply(databaseDriver), clazz)); + return Stream.of(DatabaseDriver.values()) + .filter((databaseDriver) -> !EXCLUDED_DRIVERS.contains(databaseDriver)) + .filter(predicate) + .map((databaseDriver) -> Arguments.of(databaseDriver, classNameExtractor.apply(databaseDriver), clazz)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java index d3588ef00a..7ca5f44c90 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ class DatabaseDriverTests { @Test void failureOnMalformedJdbcUrl() { assertThatIllegalArgumentException().isThrownBy(() -> DatabaseDriver.fromJdbcUrl("malformed:url")) - .withMessageContaining("URL must start with"); + .withMessageContaining("URL must start with"); } @Test @@ -95,28 +95,28 @@ class DatabaseDriverTests { assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlite:sample.db")).isEqualTo(DatabaseDriver.SQLITE); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:mysql://localhost:3306/sample")).isEqualTo(DatabaseDriver.MYSQL); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcl")) - .isEqualTo(DatabaseDriver.ORACLE); + .isEqualTo(DatabaseDriver.ORACLE); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:postgresql://127.0.0.1:5432/sample")) - .isEqualTo(DatabaseDriver.POSTGRESQL); - assertThat(DatabaseDriver.fromJdbcUrl( - "jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/sample")) - .isEqualTo(DatabaseDriver.REDSHIFT); + .isEqualTo(DatabaseDriver.POSTGRESQL); + assertThat(DatabaseDriver + .fromJdbcUrl("jdbc:redshift://examplecluster.abc123xyz789.us-west-2.redshift.amazonaws.com:5439/sample")) + .isEqualTo(DatabaseDriver.REDSHIFT); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:jtds:sqlserver://127.0.0.1:1433/sample")) - .isEqualTo(DatabaseDriver.JTDS); + .isEqualTo(DatabaseDriver.JTDS); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sap:localhost")).isEqualTo(DatabaseDriver.HANA); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:sqlserver://127.0.0.1:1433")).isEqualTo(DatabaseDriver.SQLSERVER); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebirdsql://localhost/sample")) - .isEqualTo(DatabaseDriver.FIREBIRD); + .isEqualTo(DatabaseDriver.FIREBIRD); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:firebird://localhost/sample")).isEqualTo(DatabaseDriver.FIREBIRD); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:db2://localhost:50000/sample ")).isEqualTo(DatabaseDriver.DB2); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:as400://localhost")).isEqualTo(DatabaseDriver.DB2_AS400); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:teradata://localhost/SAMPLE")).isEqualTo(DatabaseDriver.TERADATA); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-sqli://localhost:1533/sample")) - .isEqualTo(DatabaseDriver.INFORMIX); + .isEqualTo(DatabaseDriver.INFORMIX); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:informix-direct://sample")).isEqualTo(DatabaseDriver.INFORMIX); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:phoenix:localhost")).isEqualTo(DatabaseDriver.PHOENIX); assertThat(DatabaseDriver.fromJdbcUrl("jdbc:tc:mysql://localhost:3306/sample")) - .isEqualTo(DatabaseDriver.TESTCONTAINERS); + .isEqualTo(DatabaseDriver.TESTCONTAINERS); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java index 2e33af606b..ec0b636d1d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -46,13 +46,13 @@ class EmbeddedDatabaseConnectionTests { @Test void h2CustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.H2.getUrl("mydb")) - .isEqualTo("jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); + .isEqualTo("jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); } @Test void derbyCustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.DERBY.getUrl("myderbydb")) - .isEqualTo("jdbc:derby:memory:myderbydb;create=true"); + .isEqualTo("jdbc:derby:memory:myderbydb;create=true"); } @Test @@ -63,13 +63,13 @@ class EmbeddedDatabaseConnectionTests { @Test void getUrlWithNullDatabaseNameForHsqldb() { assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQLDB.getUrl(null)) - .withMessageContaining("DatabaseName must not be empty"); + .withMessageContaining("DatabaseName must not be empty"); } @Test void getUrlWithEmptyDatabaseNameForHsqldb() { assertThatIllegalArgumentException().isThrownBy(() -> EmbeddedDatabaseConnection.HSQLDB.getUrl(" ")) - .withMessageContaining("DatabaseName must not be empty"); + .withMessageContaining("DatabaseName must not be empty"); } @ParameterizedTest(name = "{0} - {1}") @@ -127,8 +127,8 @@ class EmbeddedDatabaseConnectionTests { @Test void isEmbeddedWithH2File() throws SQLException { assertThat(EmbeddedDatabaseConnection - .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), "jdbc:h2:~/test"))) - .isFalse(); + .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), "jdbc:h2:~/test"))) + .isFalse(); } @Test @@ -139,7 +139,7 @@ class EmbeddedDatabaseConnectionTests { @Test void isEmbeddedWithMissingUrlMetadata() throws SQLException { assertThat(EmbeddedDatabaseConnection - .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), null))).isTrue(); + .isEmbedded(mockDataSource(EmbeddedDatabaseConnection.H2.getDriverClassName(), null))).isTrue(); } DataSource mockDataSource(String productName, String connectionUrl) throws SQLException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java index 475a846b1d..19511e7a70 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/DataSourceScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,13 +44,17 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; class DataSourceScriptDatabaseInitializerTests extends AbstractScriptDatabaseInitializerTests { - private final HikariDataSource embeddedDataSource = DataSourceBuilder.create().type(HikariDataSource.class) - .url("jdbc:h2:mem:" + UUID.randomUUID()).build(); - - private final HikariDataSource standaloneDataSource = DataSourceBuilder.create().type(HikariDataSource.class) - .url("jdbc:h2:file:" + new BuildOutput(DataSourceScriptDatabaseInitializerTests.class).getRootLocation() - .getAbsolutePath() + "/" + UUID.randomUUID()) - .build(); + private final HikariDataSource embeddedDataSource = DataSourceBuilder.create() + .type(HikariDataSource.class) + .url("jdbc:h2:mem:" + UUID.randomUUID()) + .build(); + + private final HikariDataSource standaloneDataSource = DataSourceBuilder.create() + .type(HikariDataSource.class) + .url("jdbc:h2:file:" + + new BuildOutput(DataSourceScriptDatabaseInitializerTests.class).getRootLocation().getAbsolutePath() + + "/" + UUID.randomUUID()) + .build(); @AfterEach void closeDataSource() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java index 1dd057f814..0cbea0e61a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/init/PlatformPlaceholderDatabaseDriverResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -47,14 +47,14 @@ class PlatformPlaceholderDatabaseDriverResolverTests { @Test void resolveAllWithPlatformWhenValueDoesNotContainPlaceholderShouldReturnValueUnchanged() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll("test", "schema.sql")) - .containsExactly("schema.sql"); + .containsExactly("schema.sql"); } @Test void resolveAllWithPlatformWhenValuesContainPlaceholdersShouldReturnValuesWithPlaceholdersReplaced() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll("postgresql", "schema.sql", - "schema-@@platform@@.sql", "data-@@platform@@.sql")).containsExactly("schema.sql", - "schema-postgresql.sql", "data-postgresql.sql"); + "schema-@@platform@@.sql", "data-@@platform@@.sql")) + .containsExactly("schema.sql", "schema-postgresql.sql", "data-postgresql.sql"); } @Test @@ -65,43 +65,43 @@ class PlatformPlaceholderDatabaseDriverResolverTests { @Test void resolveAllWithDataSourceWhenValueDoesNotContainPlaceholderShouldReturnValueUnchanged() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(mock(DataSource.class), "schema.sql")) - .containsExactly("schema.sql"); + .containsExactly("schema.sql"); } @Test void resolveAllWithDataSourceWhenValuesContainPlaceholdersShouldReturnValuesWithPlaceholdersReplaced() throws SQLException { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(dataSourceWithProductName("PostgreSQL"), - "schema.sql", "schema-@@platform@@.sql", "data-@@platform@@.sql")).containsExactly("schema.sql", - "schema-postgresql.sql", "data-postgresql.sql"); + "schema.sql", "schema-@@platform@@.sql", "data-@@platform@@.sql")) + .containsExactly("schema.sql", "schema-postgresql.sql", "data-postgresql.sql"); } @Test void resolveAllWithDataSourceWhenDriverMappingsAreCustomizedShouldResolvePlaceholderUsingCustomMapping() throws SQLException { assertThat(new PlatformPlaceholderDatabaseDriverResolver() - .withDriverPlatform(DatabaseDriver.POSTGRESQL, "postgres") - .resolveAll(dataSourceWithProductName("PostgreSQL"), "schema-@@platform@@.sql")) - .containsExactly("schema-postgres.sql"); + .withDriverPlatform(DatabaseDriver.POSTGRESQL, "postgres") + .resolveAll(dataSourceWithProductName("PostgreSQL"), "schema-@@platform@@.sql")) + .containsExactly("schema-postgres.sql"); } @Test void resolveAllWithDataSourceWhenValueIsAnEmptyStringShouldReturnValueUnchanged() { assertThat(new PlatformPlaceholderDatabaseDriverResolver().resolveAll(mock(DataSource.class), "")) - .containsExactly(""); + .containsExactly(""); } @Test void resolveAllWithDataSourceWhenDriverIsUnknownShouldThrow() { assertThatIllegalStateException().isThrownBy(() -> new PlatformPlaceholderDatabaseDriverResolver() - .resolveAll(dataSourceWithProductName("CustomDB"), "schema-@@platform@@.sql")); + .resolveAll(dataSourceWithProductName("CustomDB"), "schema-@@platform@@.sql")); } @Test void resolveAllWithDataSourceWhenPlaceholderIsCustomizedShouldResolvePlaceholders() throws SQLException { - assertThat(new PlatformPlaceholderDatabaseDriverResolver("##platform##").resolveAll( - dataSourceWithProductName("PostgreSQL"), "schema-##platform##.sql", "schema-@@platform@@.sql")) - .containsExactly("schema-postgresql.sql", "schema-@@platform@@.sql"); + assertThat(new PlatformPlaceholderDatabaseDriverResolver("##platform##") + .resolveAll(dataSourceWithProductName("PostgreSQL"), "schema-##platform##.sql", "schema-@@platform@@.sql")) + .containsExactly("schema-postgresql.sql", "schema-@@platform@@.sql"); } private DataSource dataSourceWithProductName(String productName) throws SQLException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java index 47eafef659..33f2003405 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/AbstractDataSourcePoolMetadataTests.java @@ -96,8 +96,10 @@ abstract class AbstractDataSourcePoolMetadataTests initializeBuilder() { - return DataSourceBuilder.create().driverClassName("org.hsqldb.jdbc.JDBCDriver").url("jdbc:hsqldb:mem:test") - .username("sa"); + return DataSourceBuilder.create() + .driverClassName("org.hsqldb.jdbc.JDBCDriver") + .url("jdbc:hsqldb:mem:test") + .username("sa"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java index 4652be4105..75d4ac1a55 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/CommonsDbcp2DataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,7 @@ class CommonsDbcp2DataSourcePoolMetadataTests BasicDataSource dataSource = createDataSource(); dataSource.setValidationQuery("SELECT FROM FOO"); assertThat(new CommonsDbcp2DataSourcePoolMetadata(dataSource).getValidationQuery()) - .isEqualTo("SELECT FROM FOO"); + .isEqualTo("SELECT FROM FOO"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java index b8379948c0..55d47d428e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/metadata/OracleUcpDataSourcePoolMetadataTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class OracleUcpDataSourcePoolMetadataTests PoolDataSource dataSource = createDataSource(0, 4); dataSource.setSQLForValidateConnection("SELECT NULL FROM DUAL"); assertThat(new OracleUcpDataSourcePoolMetadata(dataSource).getValidationQuery()) - .isEqualTo("SELECT NULL FROM DUAL"); + .isEqualTo("SELECT NULL FROM DUAL"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java index 03e946b9e4..446d0ffe23 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java @@ -102,7 +102,7 @@ abstract class AbstractJsonParserTests { @Test void mapOfLists() { Map map = this.parser - .parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); + .parseMap("{\"foo\":[{\"foo\":\"bar\",\"spam\":1},{\"foo\":\"baz\",\"spam\":2}]}"); assertThat(map).hasSize(1); assertThat(((List) map.get("foo"))).hasSize(2); assertThat(map.get("foo")).asList().allMatch(Map.class::isInstance); @@ -111,8 +111,8 @@ abstract class AbstractJsonParserTests { @SuppressWarnings("unchecked") @Test void nestedLeadingAndTrailingWhitespace() { - Map map = this.parser.parseMap( - " {\"foo\": [ { \"foo\" : \"bar\" , \"spam\" : 1 } , { \"foo\" : \"baz\" , \"spam\" : 2 } ] } "); + Map map = this.parser + .parseMap(" {\"foo\": [ { \"foo\" : \"bar\" , \"spam\" : 1 } , { \"foo\" : \"baz\" , \"spam\" : 2 } ] } "); assertThat(map).hasSize(1); assertThat(((List) map.get("foo"))).hasSize(2); assertThat(map.get("foo")).asList().allMatch(Map.class::isInstance); @@ -182,7 +182,7 @@ abstract class AbstractJsonParserTests { @Test void listWithMalformedMap() { assertThatExceptionOfType(JsonParseException.class) - .isThrownBy(() -> this.parser.parseList("[tru,erqett,{\"foo\":fatrue,true,true,true,tr''ue}]")); + .isThrownBy(() -> this.parser.parseList("[tru,erqett,{\"foo\":fatrue,true,true,true,tr''ue}]")); } @Test @@ -194,8 +194,9 @@ abstract class AbstractJsonParserTests { void listWithRepeatedOpenArray() throws IOException { String input = StreamUtils.copyToString( AbstractJsonParserTests.class.getResourceAsStream("repeated-open-array.txt"), StandardCharsets.UTF_8); - assertThatExceptionOfType(JsonParseException.class).isThrownBy(() -> this.parser.parseList(input)).havingCause() - .withMessageContaining("too deeply nested"); + assertThatExceptionOfType(JsonParseException.class).isThrownBy(() -> this.parser.parseList(input)) + .havingCause() + .withMessageContaining("too deeply nested"); } @Test // gh-31869 diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonRuntimeHintsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonRuntimeHintsTests.java index 5b911a090d..d7c9ef0e61 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JacksonRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,14 +44,15 @@ class JacksonRuntimeHintsTests { @Test void shouldRegisterSerializerConstructors() { ReflectionHints hints = registerHints(); - Stream.of(AtomicBooleanSerializer.class, AtomicIntegerSerializer.class, AtomicLongSerializer.class, - FileSerializer.class, ClassSerializer.class, TokenBufferSerializer.class).forEach((serializer) -> { - TypeHint typeHint = hints.getTypeHint(serializer); - assertThat(typeHint).withFailMessage(() -> "No hints found for serializer " + serializer) - .isNotNull(); - Set memberCategories = typeHint.getMemberCategories(); - assertThat(memberCategories).containsExactly(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); - }); + Stream + .of(AtomicBooleanSerializer.class, AtomicIntegerSerializer.class, AtomicLongSerializer.class, + FileSerializer.class, ClassSerializer.class, TokenBufferSerializer.class) + .forEach((serializer) -> { + TypeHint typeHint = hints.getTypeHint(serializer); + assertThat(typeHint).withFailMessage(() -> "No hints found for serializer " + serializer).isNotNull(); + Set memberCategories = typeHint.getMemberCategories(); + assertThat(memberCategories).containsExactly(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); + }); } private ReflectionHints registerHints() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java index abb98d3623..cff43ce914 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/liquibase/LiquibaseChangelogMissingFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -43,10 +43,10 @@ class LiquibaseChangelogMissingFailureAnalyzerTests { void changelogParseExceptionDueToChangelogNotPresent() { FailureAnalysis analysis = performAnalysis(); assertThat(analysis.getDescription()) - .isEqualTo("Liquibase failed to start because no changelog could be found at '" - + "classpath:/db/changelog/db.changelog-master.yaml'."); + .isEqualTo("Liquibase failed to start because no changelog could be found at '" + + "classpath:/db/changelog/db.changelog-master.yaml'."); assertThat(analysis.getAction()) - .isEqualTo("Make sure a Liquibase changelog is present at the configured path."); + .isEqualTo("Make sure a Liquibase changelog is present at the configured path."); } private FailureAnalysis performAnalysis() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java index 2fdc4afff4..46ab410e0e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LogFileTests.java @@ -73,7 +73,7 @@ class LogFileTests { logFile.applyTo(properties); assertThat(logFile).hasToString("logpath" + File.separatorChar + "spring.log"); assertThat(properties.getProperty(LoggingSystemProperties.LOG_FILE)) - .isEqualTo("logpath" + File.separatorChar + "spring.log"); + .isEqualTo("logpath" + File.separatorChar + "spring.log"); assertThat(properties.getProperty(LoggingSystemProperties.LOG_PATH)).isEqualTo("logpath"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java index 800b3c09d1..3fb0106d71 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -62,7 +62,7 @@ class LoggingSystemPropertiesTests { @Test void consoleLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.console", "console pattern")) - .apply(null); + .apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_PATTERN)).isEqualTo("console pattern"); } @@ -75,14 +75,14 @@ class LoggingSystemPropertiesTests { @Test void consoleCharsetIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.charset.console", "UTF-16")) - .apply(null); + .apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_CHARSET)).isEqualTo("UTF-16"); } @Test void fileLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.file", "file pattern")) - .apply(null); + .apply(null); assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_PATTERN)).isEqualTo("file pattern"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java index 5cd927e1b9..644f7c9c55 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -52,13 +52,13 @@ class LoggingSystemTests { @Test void getLoggerConfigurationIsUnsupported() { assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(() -> new StubLoggingSystem().getLoggerConfiguration("test-logger-name")); + .isThrownBy(() -> new StubLoggingSystem().getLoggerConfiguration("test-logger-name")); } @Test void listLoggerConfigurationsIsUnsupported() { assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(() -> new StubLoggingSystem().getLoggerConfigurations()); + .isThrownBy(() -> new StubLoggingSystem().getLoggerConfigurations()); } private static final class StubLoggingSystem extends LoggingSystem { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index c019c4fa68..cb73992349 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -133,8 +133,8 @@ class JavaLoggingSystemTests extends AbstractLoggingSystemTests { @Test void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); - assertThatIllegalStateException().isThrownBy( - () -> this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", null)); + assertThatIllegalStateException() + .isThrownBy(() -> this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", null)); } @Test @@ -182,7 +182,7 @@ class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java index b76bb2f67c..c89a7e92b9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/ExtendedWhitespaceThrowablePatternConverterTests.java @@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; class ExtendedWhitespaceThrowablePatternConverterTests { private final ThrowablePatternConverter converter = ExtendedWhitespaceThrowablePatternConverter - .newInstance(new DefaultConfiguration(), new String[] {}); + .newInstance(new DefaultConfiguration(), new String[] {}); @Test void noStackTrace() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java index 48e82ebf44..5f28a16b16 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java @@ -159,7 +159,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { assertThat(output).contains("Hello world").contains(tmpDir() + "/tmp.log"); assertThat(new File(tmpDir() + "/tmp.log")).doesNotExist(); assertThat(configuration.getConfigurationSource().getFile().getAbsolutePath()) - .contains("log4j2-nondefault.xml"); + .contains("log4j2-nondefault.xml"); assertThat(configuration.getWatchManager().getIntervalSeconds()).isEqualTo(30); } @@ -236,7 +236,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test @@ -391,7 +391,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel("com.example.test", LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(configuration) - .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); this.loggingSystem.setLogLevel("com.example.test", null); LoggerConfiguration updatedConfiguration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(updatedConfiguration).isNull(); @@ -402,17 +402,18 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); - loggerContext.getConfiguration().addLogger("com.example.test", - new LoggerConfig("com.example.test", org.apache.logging.log4j.Level.INFO, false)); + loggerContext.getConfiguration() + .addLogger("com.example.test", + new LoggerConfig("com.example.test", org.apache.logging.log4j.Level.INFO, false)); this.loggingSystem.setLogLevel("com.example", LogLevel.WARN); this.loggingSystem.setLogLevel("com.example.test", LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(configuration) - .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.DEBUG, LogLevel.DEBUG)); this.loggingSystem.setLogLevel("com.example.test", null); LoggerConfiguration updatedConfiguration = this.loggingSystem.getLoggerConfiguration("com.example.test"); assertThat(updatedConfiguration) - .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.WARN, LogLevel.WARN)); + .isEqualTo(new LoggerConfiguration("com.example.test", LogLevel.WARN, LogLevel.WARN)); } @Test @@ -435,7 +436,7 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { void shutdownHookIsDisabled() { assertThat( PropertiesUtil.getProperties().getBooleanProperty(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, true)) - .isFalse(); + .isFalse(); } @Test @@ -474,9 +475,11 @@ class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { void nonFileUrlsAreResolvedUsingLog4J2UrlConnectionFactory() { this.loggingSystem.beforeInitialize(); assertThatIllegalStateException() - .isThrownBy(() -> this.loggingSystem.initialize(this.initializationContext, - "http://localhost:8080/shouldnotwork", null)) - .havingCause().isInstanceOf(ProtocolException.class).withMessageContaining("http has not been enabled"); + .isThrownBy(() -> this.loggingSystem.initialize(this.initializationContext, + "http://localhost:8080/shouldnotwork", null)) + .havingCause() + .isInstanceOf(ProtocolException.class) + .withMessageContaining("http has not been enabled"); } private String getRelativeClasspathLocation(String fileName) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java index f0a7deb5c2..850d7a4d6b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4j2XmlTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -102,8 +102,8 @@ class Log4j2XmlTests { protected Configuration initializeConfiguration() { LoggerContext context = new LoggerContext("test"); - Configuration configuration = ConfigurationFactory.getInstance().getConfiguration(context, - configurationSource()); + Configuration configuration = ConfigurationFactory.getInstance() + .getConfiguration(context, configurationSource()); configuration.initialize(); return configuration; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java index 633fbf6c1f..56b96c4d4f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringBootPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class SpringBootPropertySourceTests { @Test void allDefaultMethodsAreImplemented() { assertThat(Stream.of(SpringBootPropertySource.class.getMethods()).filter((method) -> method.isDefault())) - .isEmpty(); + .isEmpty(); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentLookupTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentLookupTests.java index 33a85d34d0..a8b6d39c06 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentLookupTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentLookupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,7 @@ class SpringEnvironmentLookupTests { this.loggerContext.removeObject(Log4J2LoggingSystem.ENVIRONMENT_KEY); Interpolator lookup = createLookup(this.loggerContext); assertThatIllegalStateException().isThrownBy(() -> lookup.lookup("spring:test")) - .withMessage("Unable to obtain Spring Environment from LoggerContext"); + .withMessage("Unable to obtain Spring Environment from LoggerContext"); } private Interpolator createLookup(LoggerContext context) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentPropertySourceTests.java index 9a7162b250..287ca23576 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/SpringEnvironmentPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class SpringEnvironmentPropertySourceTests { @Test void createWhenEnvironmentIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringEnvironmentPropertySource(null)) - .withMessage("Environment must not be null"); + .withMessage("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java index a1a0c4c6f9..623aceeb5b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/WhitespaceThrowablePatternConverterTests.java @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat; class WhitespaceThrowablePatternConverterTests { private final ThrowablePatternConverter converter = WhitespaceThrowablePatternConverter - .newInstance(new DefaultConfiguration(), new String[] {}); + .newInstance(new DefaultConfiguration(), new String[] {}); @Test void noStackTrace() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationAotContributionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationAotContributionTests.java index 873a7fd2b3..5681a08019 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationAotContributionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackConfigurationAotContributionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -82,9 +82,10 @@ class LogbackConfigurationAotContributionTests { assertThat(generatedFiles).has(resource("META-INF/spring/logback-model")); assertThat(generatedFiles).has(resource("META-INF/spring/logback-pattern-rules")); SerializationHints serializationHints = generationContext.getRuntimeHints().serialization(); - assertThat(serializationHints.javaSerializationHints().map(JavaSerializationHint::getType) - .map(TypeReference::getName)) - .containsExactlyInAnyOrder(namesOf(Model.class, ArrayList.class, Boolean.class, Integer.class)); + assertThat(serializationHints.javaSerializationHints() + .map(JavaSerializationHint::getType) + .map(TypeReference::getName)) + .containsExactlyInAnyOrder(namesOf(Model.class, ArrayList.class, Boolean.class, Integer.class)); assertThat(generationContext.getRuntimeHints().reflection().typeHints()).isEmpty(); Properties patternRules = load( generatedFiles.getGeneratedFile(Kind.RESOURCE, "META-INF/spring/logback-pattern-rules")); @@ -99,8 +100,8 @@ class LogbackConfigurationAotContributionTests { TestGenerationContext generationContext = applyContribution(new Model()); assertThat(invokePublicConstructorsOf("com.example.Alpha")).accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsOf("com.example.Bravo")).accepts(generationContext.getRuntimeHints()); - Properties patternRules = load(generationContext.getGeneratedFiles().getGeneratedFile(Kind.RESOURCE, - "META-INF/spring/logback-pattern-rules")); + Properties patternRules = load(generationContext.getGeneratedFiles() + .getGeneratedFile(Kind.RESOURCE, "META-INF/spring/logback-pattern-rules")); assertThat(patternRules).hasSize(2); assertThat(patternRules).containsEntry("a", "com.example.Alpha"); assertThat(patternRules).containsEntry("b", "com.example.Bravo"); @@ -114,13 +115,14 @@ class LogbackConfigurationAotContributionTests { model.getSubModels().add(component); TestGenerationContext generationContext = applyContribution(model); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(SizeAndTimeBasedRollingPolicy.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(FileAppender.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(FileSize.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf( - TimeBasedFileNamingAndTriggeringPolicy.class)).accepts(generationContext.getRuntimeHints()); + TimeBasedFileNamingAndTriggeringPolicy.class)) + .accepts(generationContext.getRuntimeHints()); } @Test @@ -131,11 +133,11 @@ class LogbackConfigurationAotContributionTests { model.getSubModels().add(implicit); TestGenerationContext generationContext = applyContribution(model); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(PatternLayoutEncoder.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(Layout.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(Charset.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); } @Test @@ -148,7 +150,7 @@ class LogbackConfigurationAotContributionTests { model.getSubModels().addAll(List.of(importModel, component)); TestGenerationContext generationContext = applyContribution(model); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(SizeAndTimeBasedRollingPolicy.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); } @Test @@ -160,9 +162,9 @@ class LogbackConfigurationAotContributionTests { component.getSubModels().add(implementation); TestGenerationContext generationContext = applyContribution(component); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(Outer.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(Implementation.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); } @Test @@ -174,9 +176,9 @@ class LogbackConfigurationAotContributionTests { component.getSubModels().add(contract); TestGenerationContext generationContext = applyContribution(component); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(OuterWithDefaultClass.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(Implementation.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); } @Test @@ -185,18 +187,20 @@ class LogbackConfigurationAotContributionTests { component.setClassName(ArrayParmeters.class.getName()); TestGenerationContext generationContext = applyContribution(component); assertThat(invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(InetSocketAddress.class)) - .accepts(generationContext.getRuntimeHints()); + .accepts(generationContext.getRuntimeHints()); } private Predicate invokePublicConstructorsOf(String name) { - return RuntimeHintsPredicates.reflection().onType(TypeReference.of(name)) - .withMemberCategory(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); + return RuntimeHintsPredicates.reflection() + .onType(TypeReference.of(name)) + .withMemberCategory(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } private Predicate invokePublicConstructorsAndInspectAndInvokePublicMethodsOf(Class type) { - return RuntimeHintsPredicates.reflection().onType(TypeReference.of(type)).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, MemberCategory.INTROSPECT_PUBLIC_METHODS, - MemberCategory.INVOKE_PUBLIC_METHODS); + return RuntimeHintsPredicates.reflection() + .onType(TypeReference.of(type)) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, MemberCategory.INTROSPECT_PUBLIC_METHODS, + MemberCategory.INVOKE_PUBLIC_METHODS); } private Properties load(InputStreamSource source) { @@ -221,7 +225,7 @@ class LogbackConfigurationAotContributionTests { configurator.setContext(context); withSystemProperty("spring.aot.processing", "true", () -> configurator.processModel(model)); LogbackConfigurationAotContribution contribution = (LogbackConfigurationAotContribution) context - .getObject(BeanFactoryInitializationAotContribution.class.getName()); + .getObject(BeanFactoryInitializationAotContribution.class.getName()); TestGenerationContext generationContext = new TestGenerationContext(); contribution.applyTo(generationContext, null); return generationContext; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java index 5e4f0596d5..2ab61b672f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,7 @@ class LogbackLoggingSystemPropertiesTests { this.systemPropertyNames = new HashSet<>(System.getProperties().keySet()); this.environment = new MockEnvironment(); this.environment - .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); + .setConversionService((ConfigurableConversionService) ApplicationConversionService.getSharedInstance()); } @@ -74,11 +74,11 @@ class LogbackLoggingSystemPropertiesTests { this.environment.setProperty("logging.logback.rollingpolicy.max-history", "mh"); new LogbackLoggingSystemProperties(this.environment).apply(); assertThat(System.getProperties()) - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); } @Test @@ -90,25 +90,25 @@ class LogbackLoggingSystemPropertiesTests { this.environment.setProperty("logging.file.max-history", "mh"); new LogbackLoggingSystemProperties(this.environment).apply(); assertThat(System.getProperties()) - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") - .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_FILE_NAME_PATTERN, "fnp") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, "chos") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "1024") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "2048") + .containsEntry(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, "mh"); } @Test void consoleCharsetWhenNoPropertyUsesDefault() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(System.getProperty(LoggingSystemProperties.CONSOLE_LOG_CHARSET)) - .isEqualTo(Charset.defaultCharset().name()); + .isEqualTo(Charset.defaultCharset().name()); } @Test void fileCharsetWhenNoPropertyUsesDefault() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(System.getProperty(LoggingSystemProperties.FILE_LOG_CHARSET)) - .isEqualTo(Charset.defaultCharset().name()); + .isEqualTo(Charset.defaultCharset().name()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index 61b98c18d3..a0a27b077e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -135,7 +135,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.beforeInitialize(); initialize(this.initializationContext, null, null); assertThat(org.jboss.logging.Logger.getLogger(getClass()).getClass().getName()) - .isEqualTo("org.jboss.logging.Slf4jLocationAwareLogger"); + .isEqualTo("org.jboss.logging.Slf4jLocationAwareLogger"); } @Test @@ -178,8 +178,10 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { initialize(this.initializationContext, "classpath:logback-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); - assertThat(output).doesNotContain("DEBUG").contains("Hello world").contains(tmpDir() + "/tmp.log") - .endsWith("BOOTBOOT"); + assertThat(output).doesNotContain("DEBUG") + .contains("Hello world") + .contains(tmpDir() + "/tmp.log") + .endsWith("BOOTBOOT"); assertThat(new File(tmpDir() + "/tmp.log")).doesNotExist(); } @@ -189,8 +191,8 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { try { this.loggingSystem.beforeInitialize(); initialize(this.initializationContext, null, null); - assertThat(output).contains( - "Ignoring 'logback.configurationFile' system property. Please use 'logging.config' instead."); + assertThat(output) + .contains("Ignoring 'logback.configurationFile' system property. Please use 'logging.config' instead."); } finally { System.clearProperty("logback.configurationFile"); @@ -201,7 +203,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); assertThatIllegalStateException() - .isThrownBy(() -> initialize(this.initializationContext, "classpath:logback-nonexistent.xml", null)); + .isThrownBy(() -> initialize(this.initializationContext, "classpath:logback-nonexistent.xml", null)); } @Test @@ -249,7 +251,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.DEBUG, LogLevel.DEBUG)); } @Test @@ -268,7 +270,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { logger.setLevel(Level.ALL); LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.TRACE, LogLevel.TRACE)); + .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.TRACE, LogLevel.TRACE)); } @Test @@ -574,7 +576,7 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); assertThat(getLineWithText(output, "Hello world")) - .containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}([-+]\\d{2}:\\d{2}|Z)"); + .containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}([-+]\\d{2}:\\d{2}|Z)"); } @Test @@ -616,8 +618,9 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); initialize(this.initializationContext, null, logFile); - assertThat(output).contains("LevelChangePropagator").contains("SizeAndTimeBasedFNATP") - .contains("DebugLogbackConfigurator"); + assertThat(output).contains("LevelChangePropagator") + .contains("SizeAndTimeBasedFNATP") + .contains("DebugLogbackConfigurator"); } finally { System.clearProperty("logback.debug"); @@ -701,8 +704,10 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } private String getLineWithText(CharSequence output, CharSequence outputSearch) { - return Arrays.stream(output.toString().split("\\r?\\n")).filter((line) -> line.contains(outputSearch)) - .findFirst().orElse(null); + return Arrays.stream(output.toString().split("\\r?\\n")) + .filter((line) -> line.contains(outputSearch)) + .findFirst() + .orElse(null); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackRuntimeHintsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackRuntimeHintsTests.java index eac9914fa6..903ef190d0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class LogbackRuntimeHintsTests { ReflectionHints reflection = registerHints(); assertThat(List.of(ColorConverter.class, ExtendedWhitespaceThrowableProxyConverter.class, WhitespaceThrowableProxyConverter.class)) - .allSatisfy(registeredForPublicConstructorInvocation(reflection)); + .allSatisfy(registeredForPublicConstructorInvocation(reflection)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java index 04fdf8965c..f7ba6d72a3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/JarUriTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class JarUriTests { @Test void describeRegularJar() { JarUri uri = JarUri - .from("jar:file:/home/user/project/target/project-0.0.1-SNAPSHOT.jar!/application.properties"); + .from("jar:file:/home/user/project/target/project-0.0.1-SNAPSHOT.jar!/application.properties"); assertThat(uri.getDescription()).isEqualTo("project-0.0.1-SNAPSHOT.jar"); } @@ -50,7 +50,7 @@ class JarUriTests { void getDescriptionMergedWithExisting() { JarUri uri = JarUri.from("jar:file:/project-0.0.1-SNAPSHOT.jar!/application.properties"); assertThat(uri.getDescription("classpath: [application.properties]")) - .isEqualTo("classpath: [application.properties] from project-0.0.1-SNAPSHOT.jar"); + .isEqualTo("classpath: [application.properties] from project-0.0.1-SNAPSHOT.jar"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java index cbec4fb2d2..9721df2bb0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/OriginTrackedResourceTests.java @@ -186,7 +186,7 @@ class OriginTrackedResourceTests { Resource resource = mock(WritableResource.class); Resource tracked = OriginTrackedResource.of(resource, this.origin); assertThat(tracked).isInstanceOf(WritableResource.class) - .isExactlyInstanceOf(OriginTrackedWritableResource.class); + .isExactlyInstanceOf(OriginTrackedWritableResource.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java index 7205127f5d..a8647f6ca1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java @@ -39,20 +39,20 @@ class PropertySourceOriginTests { @Test void createWhenPropertySourceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(null, "name")) - .withMessageContaining("PropertySource must not be null"); + .withMessageContaining("PropertySource must not be null"); } @Test void createWhenPropertyNameIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), null)) - .withMessageContaining("PropertyName must not be empty"); + .isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), null)) + .withMessageContaining("PropertyName must not be empty"); } @Test void createWhenPropertyNameIsEmptyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new PropertySourceOrigin(mock(PropertySource.class), "")) - .withMessageContaining("PropertyName must not be empty"); + .withMessageContaining("PropertyName must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java index ad78dc731e..e9e5e3988d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,7 +66,7 @@ class ConnectionFactoryBuilderTests { @Test void createWithEmbeddedConnectionNoneShouldFail() { assertThatIllegalArgumentException() - .isThrownBy(() -> ConnectionFactoryBuilder.withUrl(EmbeddedDatabaseConnection.NONE.getUrl("test"))); + .isThrownBy(() -> ConnectionFactoryBuilder.withUrl(EmbeddedDatabaseConnection.NONE.getUrl("test"))); } @Test @@ -80,7 +80,8 @@ class ConnectionFactoryBuilderTests { @Test void buildOptionsWithEmbeddedConnectionH2ShouldExposeOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl("testdb")).buildOptions(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl("testdb")) + .buildOptions(); assertThat(options.getRequiredValue(ConnectionFactoryOptions.DRIVER)).isEqualTo("h2"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.PROTOCOL)).isEqualTo("mem"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.DATABASE)).isEqualTo("testdb"); @@ -89,13 +90,14 @@ class ConnectionFactoryBuilderTests { assertThat(options.hasOption(ConnectionFactoryOptions.USER)).isFalse(); assertThat(options.hasOption(ConnectionFactoryOptions.PASSWORD)).isFalse(); assertThat(options.getValue(Option.valueOf("options"))) - .isEqualTo("DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); + .isEqualTo("DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); } @Test void buildOptionsWithCompleteUrlShouldExposeOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder - .withUrl("r2dbc:simple:proto://user:password@myhost:4711/mydatabase").buildOptions(); + .withUrl("r2dbc:simple:proto://user:password@myhost:4711/mydatabase") + .buildOptions(); assertThat(options.getRequiredValue(ConnectionFactoryOptions.DRIVER)).isEqualTo("simple"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.PROTOCOL)).isEqualTo("proto"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("user"); @@ -108,9 +110,13 @@ class ConnectionFactoryBuilderTests { @Test void buildOptionsWithSpecificSettingsShouldOverrideUrlOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder - .withUrl("r2dbc:simple://user:password@myhost/mydatabase").username("another-user") - .password("another-password").hostname("another-host").port(1234).database("another-database") - .buildOptions(); + .withUrl("r2dbc:simple://user:password@myhost/mydatabase") + .username("another-user") + .password("another-password") + .hostname("another-host") + .port(1234) + .database("another-database") + .buildOptions(); assertThat(options.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("another-user"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.PASSWORD)).isEqualTo("another-password"); assertThat(options.getRequiredValue(ConnectionFactoryOptions.HOST)).isEqualTo("another-host"); @@ -121,9 +127,8 @@ class ConnectionFactoryBuilderTests { @Test void buildOptionsWithDriverPropertiesShouldExposeOptions() { ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl("r2dbc:simple://user:password@myhost") - .configure( - (o) -> o.option(Option.valueOf("simpleOne"), "one").option(Option.valueOf("simpleTwo"), "two")) - .buildOptions(); + .configure((o) -> o.option(Option.valueOf("simpleOne"), "one").option(Option.valueOf("simpleTwo"), "two")) + .buildOptions(); assertThat(options.getRequiredValue(Option.valueOf("simpleOne"))).isEqualTo("one"); assertThat(options.getRequiredValue(Option.valueOf("simpleTwo"))).isEqualTo("two"); } @@ -132,7 +137,8 @@ class ConnectionFactoryBuilderTests { void buildShouldExposeConnectionFactory() { String databaseName = UUID.randomUUID().toString(); ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(databaseName)).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(databaseName)) + .build(); assertThat(connectionFactory).isNotNull(); assertThat(connectionFactory.getMetadata().getName()).isEqualTo(H2ConnectionFactoryMetadata.NAME); } @@ -141,11 +147,13 @@ class ConnectionFactoryBuilderTests { void buildWhenDerivedWithNewDatabaseReturnsNewConnectionFactory() { String initialDatabaseName = UUID.randomUUID().toString(); ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(initialDatabaseName)).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(initialDatabaseName)) + .build(); ConnectionFactoryOptions initialOptions = ((OptionsCapableConnectionFactory) connectionFactory).getOptions(); String derivedDatabaseName = UUID.randomUUID().toString(); ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(connectionFactory) - .database(derivedDatabaseName).build(); + .database(derivedDatabaseName) + .build(); ConnectionFactoryOptions derivedOptions = ((OptionsCapableConnectionFactory) derived).getOptions(); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.DATABASE)).isEqualTo(derivedDatabaseName); assertMatchingOptions(derivedOptions, initialOptions, ConnectionFactoryOptions.CONNECT_TIMEOUT, @@ -157,10 +165,13 @@ class ConnectionFactoryBuilderTests { @Test void buildWhenDerivedWithNewCredentialsReturnsNewConnectionFactory() { ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())) + .build(); ConnectionFactoryOptions initialOptions = ((OptionsCapableConnectionFactory) connectionFactory).getOptions(); - ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(connectionFactory).username("admin") - .password("secret").build(); + ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(connectionFactory) + .username("admin") + .password("secret") + .build(); ConnectionFactoryOptions derivedOptions = ((OptionsCapableConnectionFactory) derived).getOptions(); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("admin"); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.PASSWORD)).isEqualTo("secret"); @@ -172,12 +183,15 @@ class ConnectionFactoryBuilderTests { @Test void buildWhenDerivedFromPoolReturnsNewNonPooledConnectionFactory() { ConnectionFactory connectionFactory = ConnectionFactoryBuilder - .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())).build(); + .withUrl(EmbeddedDatabaseConnection.H2.getUrl(UUID.randomUUID().toString())) + .build(); ConnectionFactoryOptions initialOptions = ((OptionsCapableConnectionFactory) connectionFactory).getOptions(); ConnectionPoolConfiguration poolConfiguration = ConnectionPoolConfiguration.builder(connectionFactory).build(); ConnectionPool pool = new ConnectionPool(poolConfiguration); - ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(pool).username("admin").password("secret") - .build(); + ConnectionFactory derived = ConnectionFactoryBuilder.derivedFrom(pool) + .username("admin") + .password("secret") + .build(); assertThat(derived).isNotInstanceOf(ConnectionPool.class).isInstanceOf(OptionsCapableConnectionFactory.class); ConnectionFactoryOptions derivedOptions = ((OptionsCapableConnectionFactory) derived).getOptions(); assertThat(derivedOptions.getRequiredValue(ConnectionFactoryOptions.USER)).isEqualTo("admin"); @@ -193,11 +207,12 @@ class ConnectionFactoryBuilderTests { void optionIsMappedWhenCreatingPoolConfiguration(Option option) { String url = "r2dbc:pool:h2:mem:///" + UUID.randomUUID(); ExpectedOption expectedOption = ExpectedOption.get(option); - ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl(url).configure((builder) -> builder - .option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName").option(option, expectedOption.value)) - .buildOptions(); + ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl(url) + .configure((builder) -> builder.option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName") + .option(option, expectedOption.value)) + .buildOptions(); ConnectionPoolConfiguration configuration = new PoolingAwareOptionsCapableWrapper() - .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); + .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); assertThat(configuration).extracting(expectedOption.property).isEqualTo(expectedOption.value); } @@ -212,11 +227,11 @@ class ConnectionFactoryBuilderTests { String url = "r2dbc:pool:h2:mem:///" + UUID.randomUUID(); ExpectedOption expectedOption = ExpectedOption.get(option); ConnectionFactoryOptions options = ConnectionFactoryBuilder.withUrl(url) - .configure((builder) -> builder.option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName") - .option(option, expectedOption.value.toString())) - .buildOptions(); + .configure((builder) -> builder.option(PoolingConnectionFactoryProvider.POOL_NAME, "defaultName") + .option(option, expectedOption.value.toString())) + .buildOptions(); ConnectionPoolConfiguration configuration = new PoolingAwareOptionsCapableWrapper() - .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); + .connectionPoolConfiguration(options, mock(ConnectionFactory.class)); assertThat(configuration).extracting(expectedOption.property).isEqualTo(expectedOption.value); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java index a5bab4f5b4..57433751ad 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/EmbeddedDatabaseConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -48,50 +48,49 @@ class EmbeddedDatabaseConnectionTests { @Test void getReturnsH2ByDefault() { assertThat(EmbeddedDatabaseConnection.get(EmbeddedDatabaseConnectionTests.class.getClassLoader())) - .isEqualTo(EmbeddedDatabaseConnection.H2); + .isEqualTo(EmbeddedDatabaseConnection.H2); } @Test void getWhenH2IsNotOnTheClasspathReturnsNone() { assertThat(EmbeddedDatabaseConnection.get(new HidePackagesClassLoader("io.r2dbc.h2"))) - .isEqualTo(EmbeddedDatabaseConnection.NONE); + .isEqualTo(EmbeddedDatabaseConnection.NONE); } @Test void whenH2IsInMemoryThenIsEmbeddedReturnsTrue() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:mem:///" + UUID.randomUUID()).build())).isTrue(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:mem:///" + UUID.randomUUID()).build())).isTrue(); } @Test void whenH2IsUsingFileStorageThenIsEmbeddedReturnsFalse() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:file:///" + UUID.randomUUID()).build())) - .isFalse(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:h2:file:///" + UUID.randomUUID()).build())).isFalse(); } @Test void whenPoolIsBasedByH2InMemoryThenIsEmbeddedReturnsTrue() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:mem:///" + UUID.randomUUID()).build())) - .isTrue(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:mem:///" + UUID.randomUUID()).build())) + .isTrue(); } @Test void whenPoolIsBasedByH2WithFileStorageThenIsEmbeddedReturnsFalse() { assertThat(EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:file:///" + UUID.randomUUID()).build())) - .isFalse(); + .isEmbedded(ConnectionFactoryBuilder.withUrl("r2dbc:pool:h2:file:///" + UUID.randomUUID()).build())) + .isFalse(); } @Test void whenConnectionFactoryIsNotOptionsCapableThenIsEmbeddedThrows() { assertThatIllegalArgumentException() - .isThrownBy(() -> EmbeddedDatabaseConnection - .isEmbedded(ConnectionFactories.get("r2dbc:pool:h2:mem:///" + UUID.randomUUID()))) - .withMessage("Cannot determine database's type as ConnectionFactory is not options-capable. To be " - + "options-capable, a ConnectionFactory should be created with " - + "org.springframework.boot.r2dbc.ConnectionFactoryBuilder"); + .isThrownBy(() -> EmbeddedDatabaseConnection + .isEmbedded(ConnectionFactories.get("r2dbc:pool:h2:mem:///" + UUID.randomUUID()))) + .withMessage("Cannot determine database's type as ConnectionFactory is not options-capable. To be " + + "options-capable, a ConnectionFactory should be created with " + + "org.springframework.boot.r2dbc.ConnectionFactoryBuilder"); } static Stream urlParameters() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java index b22d4204a5..1cdb243a1e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/r2dbc/init/R2dbcScriptDatabaseInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -35,15 +35,17 @@ class R2dbcScriptDatabaseInitializerTests extends AbstractScriptDatabaseInitializerTests { private final ConnectionFactory embeddedConnectionFactory = ConnectionFactoryBuilder - .withUrl("r2dbc:h2:mem:///" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .build(); + .withUrl("r2dbc:h2:mem:///" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .build(); private final ConnectionFactory standaloneConnectionFactory = ConnectionFactoryBuilder - .withUrl("r2dbc:h2:file:///" - + new BuildOutput(R2dbcScriptDatabaseInitializerTests.class).getRootLocation().getAbsolutePath() + .withUrl( + "r2dbc:h2:file:///" + + new BuildOutput(R2dbcScriptDatabaseInitializerTests.class).getRootLocation() + .getAbsolutePath() .replace('\\', '/') - + "/" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") - .build(); + + "/" + UUID.randomUUID() + "?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE") + .build(); @Override protected R2dbcScriptDatabaseInitializer createEmbeddedDatabaseInitializer( @@ -68,8 +70,12 @@ class R2dbcScriptDatabaseInitializerTests } private int numberOfRows(ConnectionFactory connectionFactory, String sql) { - return DatabaseClient.create(connectionFactory).sql(sql).map((row, metadata) -> row.get(0)).first() - .map((number) -> ((Number) number).intValue()).block(); + return DatabaseClient.create(connectionFactory) + .sql(sql) + .map((row, metadata) -> row.get(0)) + .first() + .map((number) -> ((Number) number).intValue()) + .block(); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java index ac965f17a8..87efbcc782 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/reactor/DebugAgentEnvironmentPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ class DebugAgentEnvironmentPostProcessorTests { InstrumentedFluxProvider fluxProvider = new InstrumentedFluxProvider(); Flux flux = fluxProvider.newFluxJust(); assertThat(Scannable.from(flux).stepName()) - .startsWith("Flux.just ⇢ at org.springframework.boot.reactor.InstrumentedFluxProvider.newFluxJust"); + .startsWith("Flux.just ⇢ at org.springframework.boot.reactor.InstrumentedFluxProvider.newFluxJust"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java index 4c739922fd..dfdf965fff 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/rsocket/netty/NettyRSocketServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -137,7 +137,7 @@ class NettyRSocketServerFactoryTests { for (int i = 0; i < customizers.length; i++) { customizers[i] = mock(RSocketServerCustomizer.class); will((invocation) -> invocation.getArgument(0)).given(customizers[i]) - .customize(any(io.rsocket.core.RSocketServer.class)); + .customize(any(io.rsocket.core.RSocketServer.class)); } factory.setRSocketServerCustomizers(Arrays.asList(customizers)); this.server = factory.create(new EchoRequestResponseAcceptor()); @@ -242,7 +242,7 @@ class NettyRSocketServerFactoryTests { String payload = "test payload"; Mono responseMono = this.requester.route("test").data(payload).retrieveMono(String.class); StepVerifier.create(responseMono) - .verifyErrorSatisfies((ex) -> assertThat(ex).isInstanceOf(ClosedChannelException.class)); + .verifyErrorSatisfies((ex) -> assertThat(ex).isInstanceOf(ClosedChannelException.class)); } private RSocketRequester createRSocketTcpClient() { @@ -259,13 +259,14 @@ class NettyRSocketServerFactoryTests { private RSocketRequester createSecureRSocketWebSocketClient() { return createRSocketRequesterBuilder() - .transport(WebsocketClientTransport.create(createSecureHttpClient(), "/")); + .transport(WebsocketClientTransport.create(createSecureHttpClient(), "/")); } private HttpClient createSecureHttpClient() { HttpClient httpClient = createHttpClient(); - Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); return httpClient.secure((spec) -> spec.sslContext(sslContextSpec)); } @@ -277,8 +278,9 @@ class NettyRSocketServerFactoryTests { private TcpClient createSecureTcpClient() { TcpClient tcpClient = createTcpClient(); - Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); return tcpClient.secure((spec) -> spec.sslContext(sslContextSpec)); } @@ -289,9 +291,11 @@ class NettyRSocketServerFactoryTests { } private RSocketRequester.Builder createRSocketRequesterBuilder() { - RSocketStrategies strategies = RSocketStrategies.builder().decoder(StringDecoder.allMimeTypes()) - .encoder(CharSequenceEncoder.allMimeTypes()) - .dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)).build(); + RSocketStrategies strategies = RSocketStrategies.builder() + .decoder(StringDecoder.allMimeTypes()) + .encoder(CharSequenceEncoder.allMimeTypes()) + .dataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)) + .build(); return RSocketRequester.builder().rsocketStrategies(strategies); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java index 44955a29ec..a78ea4e37b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -49,8 +49,8 @@ class ApplicationContextServerWebExchangeMatcherTests { @Test void createWhenContextClassIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(null)) - .withMessageContaining("Context class must not be null"); + .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(null)) + .withMessageContaining("Context class must not be null"); } @Test @@ -58,7 +58,8 @@ class ApplicationContextServerWebExchangeMatcherTests { ServerWebExchange exchange = createExchange(); StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ApplicationContext.class) - .callMatchesAndReturnProvidedContext(exchange).get()).isEqualTo(context); + .callMatchesAndReturnProvidedContext(exchange) + .get()).isEqualTo(context); } @Test @@ -67,14 +68,15 @@ class ApplicationContextServerWebExchangeMatcherTests { StaticApplicationContext context = (StaticApplicationContext) exchange.getApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); assertThat(new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange).get()).isEqualTo(context.getBean(ExistingBean.class)); + .callMatchesAndReturnProvidedContext(exchange) + .get()).isEqualTo(context.getBean(ExistingBean.class)); } @Test void matchesWhenContextClassIsMissingBeanShouldProvideException() { ServerWebExchange exchange = createExchange(); Supplier supplier = new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange); + .callMatchesAndReturnProvidedContext(exchange); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(supplier::get); } @@ -82,9 +84,9 @@ class ApplicationContextServerWebExchangeMatcherTests { void matchesWhenContextIsNull() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").build()); assertThatIllegalStateException() - .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange)) - .withMessageContaining("No ApplicationContext found on ServerWebExchange."); + .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) + .callMatchesAndReturnProvidedContext(exchange)) + .withMessageContaining("No ApplicationContext found on ServerWebExchange."); } private ServerWebExchange createExchange() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java index 1a3e42e728..7773b6dbc0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java @@ -47,14 +47,15 @@ class ApplicationContextRequestMatcherTests { @Test void createWhenContextClassIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new TestApplicationContextRequestMatcher<>(null)) - .withMessageContaining("Context class must not be null"); + .withMessageContaining("Context class must not be null"); } @Test void matchesWhenContextClassIsApplicationContextShouldProvideContext() { StaticWebApplicationContext context = createWebApplicationContext(); assertThat(new TestApplicationContextRequestMatcher<>(ApplicationContext.class) - .callMatchesAndReturnProvidedContext(context).get()).isEqualTo(context); + .callMatchesAndReturnProvidedContext(context) + .get()).isEqualTo(context); } @Test @@ -62,14 +63,15 @@ class ApplicationContextRequestMatcherTests { StaticWebApplicationContext context = createWebApplicationContext(); context.registerSingleton("existingBean", ExistingBean.class); assertThat(new TestApplicationContextRequestMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(context).get()).isEqualTo(context.getBean(ExistingBean.class)); + .callMatchesAndReturnProvidedContext(context) + .get()).isEqualTo(context.getBean(ExistingBean.class)); } @Test void matchesWhenContextClassIsBeanThatDoesNotExistShouldSupplyException() { StaticWebApplicationContext context = createWebApplicationContext(); Supplier supplier = new TestApplicationContextRequestMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(context); + .callMatchesAndReturnProvidedContext(context); assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(supplier::get); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java index 4450f6c638..81702612e7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sql/init/AbstractScriptDatabaseInitializerTests.java @@ -69,7 +69,7 @@ public abstract class AbstractScriptDatabaseInitializerTests assertThat(dependencies).containsExactly("alpha")); @@ -107,7 +107,7 @@ class DatabaseInitializationDependencyConfigurerTests { context.refresh(); assertThat(ConstructorInjectionDatabaseInitializerDetector.environment).isEqualTo(this.environment); assertThat(ConstructorInjectionDependsOnDatabaseInitializationDetector.environment) - .isEqualTo(this.environment); + .isEqualTo(this.environment); }); } @@ -120,16 +120,16 @@ class DatabaseInitializationDependencyConfigurerTests { context.registerBeanDefinition("alpha", alpha); context.registerBeanDefinition("bravo", bravo); given(MockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("alpha")); + .willReturn(Collections.singleton("alpha")); given(MockedDependsOnDatabaseInitializationDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("bravo")); + .willReturn(Collections.singleton("bravo")); context.register(DependencyConfigurerConfiguration.class); context.refresh(); assertThat(alpha.getAttribute(DatabaseInitializerDetector.class.getName())) - .isEqualTo(MockDatabaseInitializerDetector.class.getName()); + .isEqualTo(MockDatabaseInitializerDetector.class.getName()); assertThat(bravo.getAttribute(DatabaseInitializerDetector.class.getName())).isNull(); - then(MockDatabaseInitializerDetector.instance).should().detectionComplete(context.getBeanFactory(), - Collections.singleton("alpha")); + then(MockDatabaseInitializerDetector.instance).should() + .detectionComplete(context.getBeanFactory(), Collections.singleton("alpha")); assertThat(bravo.getDependsOn()).containsExactly("alpha"); }); } @@ -147,13 +147,13 @@ class DatabaseInitializationDependencyConfigurerTests { MockedDependsOnDatabaseInitializationDetector.class), (context) -> { given(MockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("alpha")); + .willReturn(Collections.singleton("alpha")); given(OrderedNearLowestMockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(new LinkedHashSet<>(Arrays.asList("bravo1", "bravo2"))); + .willReturn(new LinkedHashSet<>(Arrays.asList("bravo1", "bravo2"))); given(OrderedLowestMockDatabaseInitializerDetector.instance.detect(context.getBeanFactory())) - .willReturn(new LinkedHashSet<>(Arrays.asList("charlie"))); + .willReturn(new LinkedHashSet<>(Arrays.asList("charlie"))); given(MockedDependsOnDatabaseInitializationDetector.instance.detect(context.getBeanFactory())) - .willReturn(Collections.singleton("delta")); + .willReturn(Collections.singleton("delta")); context.registerBeanDefinition("alpha", alpha); context.registerBeanDefinition("bravo1", bravo1); context.registerBeanDefinition("bravo2", bravo2); @@ -326,7 +326,7 @@ class DatabaseInitializationDependencyConfigurerTests { } else if (DependsOnDatabaseInitializationDetector.class.isAssignableFrom(detector)) { this.dependsOnDatabaseInitializationDetectors - .add((Class) detector); + .add((Class) detector); } else { throw new IllegalArgumentException("Unsupported detector type '" + detector.getName() + "'"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java index 2f708cd1da..3c72660ff9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java @@ -49,7 +49,7 @@ class ApplicationPidTests { void throwIllegalStateWritingMissingPid() { ApplicationPid pid = new ApplicationPid(null); assertThatIllegalStateException().isThrownBy(() -> pid.write(new File(this.tempDir, "pid"))) - .withMessageContaining("No PID available"); + .withMessageContaining("No PID available"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java index bbbcc81804..1b283a0fef 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationTempTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,8 @@ class ApplicationTempTests { private void assertDirectoryPermissions(Path path) throws IOException { Set permissions = Files.getFileAttributeView(path, PosixFileAttributeView.class) - .readAttributes().permissions(); + .readAttributes() + .permissions(); assertThat(permissions).containsExactlyInAnyOrder(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java index c06ded413d..52c205e8ed 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,8 +43,12 @@ class TaskExecutorBuilderTests { @Test void poolSettingsShouldApply() { - ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8) - .allowCoreThreadTimeOut(true).keepAlive(Duration.ofMinutes(1)).build(); + ThreadPoolTaskExecutor executor = this.builder.queueCapacity(10) + .corePoolSize(4) + .maxPoolSize(8) + .allowCoreThreadTimeOut(true) + .keepAlive(Duration.ofMinutes(1)) + .build(); assertThat(executor).hasFieldOrPropertyWithValue("queueCapacity", 10); assertThat(executor.getCorePoolSize()).isEqualTo(4); assertThat(executor.getMaxPoolSize()).isEqualTo(8); @@ -81,14 +85,14 @@ class TaskExecutorBuilderTests { @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((TaskExecutorCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -102,19 +106,26 @@ class TaskExecutorBuilderTests { void customizersShouldBeAppliedLast() { TaskDecorator taskDecorator = mock(TaskDecorator.class); ThreadPoolTaskExecutor executor = spy(new ThreadPoolTaskExecutor()); - this.builder.queueCapacity(10).corePoolSize(4).maxPoolSize(8).allowCoreThreadTimeOut(true) - .keepAlive(Duration.ofMinutes(1)).awaitTermination(true).awaitTerminationPeriod(Duration.ofSeconds(30)) - .threadNamePrefix("test-").taskDecorator(taskDecorator).additionalCustomizers((taskExecutor) -> { - then(taskExecutor).should().setQueueCapacity(10); - then(taskExecutor).should().setCorePoolSize(4); - then(taskExecutor).should().setMaxPoolSize(8); - then(taskExecutor).should().setAllowCoreThreadTimeOut(true); - then(taskExecutor).should().setKeepAliveSeconds(60); - then(taskExecutor).should().setWaitForTasksToCompleteOnShutdown(true); - then(taskExecutor).should().setAwaitTerminationSeconds(30); - then(taskExecutor).should().setThreadNamePrefix("test-"); - then(taskExecutor).should().setTaskDecorator(taskDecorator); - }); + this.builder.queueCapacity(10) + .corePoolSize(4) + .maxPoolSize(8) + .allowCoreThreadTimeOut(true) + .keepAlive(Duration.ofMinutes(1)) + .awaitTermination(true) + .awaitTerminationPeriod(Duration.ofSeconds(30)) + .threadNamePrefix("test-") + .taskDecorator(taskDecorator) + .additionalCustomizers((taskExecutor) -> { + then(taskExecutor).should().setQueueCapacity(10); + then(taskExecutor).should().setCorePoolSize(4); + then(taskExecutor).should().setMaxPoolSize(8); + then(taskExecutor).should().setAllowCoreThreadTimeOut(true); + then(taskExecutor).should().setKeepAliveSeconds(60); + then(taskExecutor).should().setWaitForTasksToCompleteOnShutdown(true); + then(taskExecutor).should().setAwaitTerminationSeconds(30); + then(taskExecutor).should().setThreadNamePrefix("test-"); + then(taskExecutor).should().setTaskDecorator(taskDecorator); + }); this.builder.configure(executor); } @@ -123,7 +134,8 @@ class TaskExecutorBuilderTests { TaskExecutorCustomizer customizer1 = mock(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer2 = mock(TaskExecutorCustomizer.class); ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(executor); } @@ -131,23 +143,24 @@ class TaskExecutorBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersShouldAddToExisting() { TaskExecutorCustomizer customizer1 = mock(TaskExecutorCustomizer.class); TaskExecutorCustomizer customizer2 = mock(TaskExecutorCustomizer.class); - ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1).additionalCustomizers(customizer2) - .build(); + ThreadPoolTaskExecutor executor = this.builder.customizers(customizer1) + .additionalCustomizers(customizer2) + .build(); then(customizer1).should().customize(executor); then(customizer2).should().customize(executor); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java index c7cd82ac53..e07573910c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,15 +67,15 @@ class TaskSchedulerBuilderTests { @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -100,7 +100,8 @@ class TaskSchedulerBuilderTests { TaskSchedulerCustomizer customizer1 = mock(TaskSchedulerCustomizer.class); TaskSchedulerCustomizer customizer2 = mock(TaskSchedulerCustomizer.class); ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(scheduler); } @@ -108,23 +109,24 @@ class TaskSchedulerBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((TaskSchedulerCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((TaskSchedulerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersShouldAddToExisting() { TaskSchedulerCustomizer customizer1 = mock(TaskSchedulerCustomizer.class); TaskSchedulerCustomizer customizer2 = mock(TaskSchedulerCustomizer.class); - ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1).additionalCustomizers(customizer2) - .build(); + ThreadPoolTaskScheduler scheduler = this.builder.customizers(customizer1) + .additionalCustomizers(customizer2) + .build(); then(customizer1).should().customize(scheduler); then(customizer2).should().customize(scheduler); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java index a43675e11f..bb208ff4c9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/InstantiatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -83,7 +83,8 @@ class InstantiatorTests { @Test void instantiateTypesCreatesInstance() { WithDefaultConstructor instance = createInstantiator(WithDefaultConstructor.class) - .instantiateTypes(Collections.singleton(WithDefaultConstructor.class)).get(0); + .instantiateTypes(Collections.singleton(WithDefaultConstructor.class)) + .get(0); assertThat(instance).isInstanceOf(WithDefaultConstructor.class); } @@ -99,25 +100,26 @@ class InstantiatorTests { }; WithDefaultConstructor instance = createInstantiator(WithDefaultConstructor.class) - .instantiate(classLoader, Collections.singleton(WithDefaultConstructorSubclass.class.getName())).get(0); + .instantiate(classLoader, Collections.singleton(WithDefaultConstructorSubclass.class.getName())) + .get(0); assertThat(instance.getClass().getClassLoader()).isSameAs(classLoader); } @Test void createWhenWrongTypeThrowsException() { assertThatIllegalArgumentException() - .isThrownBy(() -> createInstantiator(WithDefaultConstructor.class) - .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) - .withMessageContaining("Unable to instantiate"); + .isThrownBy(() -> createInstantiator(WithDefaultConstructor.class) + .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) + .withMessageContaining("Unable to instantiate"); } @Test void createWithFailureHandlerInvokesFailureHandler() { assertThatIllegalStateException() - .isThrownBy(() -> new Instantiator<>(WithDefaultConstructor.class, (availableParameters) -> { - }, new CustomFailureHandler()) - .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) - .withMessageContaining("custom failure handler message"); + .isThrownBy(() -> new Instantiator<>(WithDefaultConstructor.class, (availableParameters) -> { + }, new CustomFailureHandler()) + .instantiate(Collections.singleton(WithAdditionalConstructor.class.getName()))) + .withMessageContaining("custom failure handler message"); } private T createInstance(Class type) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java index 374642980e..0c3c50f531 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,13 +46,13 @@ class LambdaSafeTests { @Test void callbackWhenCallbackTypeIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(null, new Object(), null)) - .withMessageContaining("CallbackType must not be null"); + .withMessageContaining("CallbackType must not be null"); } @Test void callbackWhenCallbackInstanceIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> LambdaSafe.callback(Object.class, null, null)) - .withMessageContaining("CallbackInstance must not be null"); + .withMessageContaining("CallbackInstance must not be null"); } @Test @@ -104,7 +104,7 @@ class LambdaSafeTests { GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callback(GenericMultiArgCallback.class, callbackInstance, argument) - .invoke((c) -> c.handle(1, argument, false)); + .invoke((c) -> c.handle(1, argument, false)); } @Test @@ -113,7 +113,7 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); InvocationResult result = LambdaSafe.callback(NonGenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); } @@ -125,7 +125,7 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); } @@ -137,7 +137,7 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isNull(); } @@ -149,7 +149,7 @@ class LambdaSafeTests { StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); assertThat(result.hasResult()).isTrue(); assertThat(result.get()).isEqualTo(123); @@ -161,7 +161,7 @@ class LambdaSafeTests { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isFalse(); then(callbackInstance).shouldHaveNoInteractions(); } @@ -175,7 +175,7 @@ class LambdaSafeTests { }; String argument = "foo"; InvocationResult result = LambdaSafe.callback(GenericFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result.hasResult()).isFalse(); } @@ -188,7 +188,7 @@ class LambdaSafeTests { }; String argument = "foo"; InvocationResult result = LambdaSafe.callback(GenericMultiArgFactory.class, callbackInstance, argument) - .invokeAnd((c) -> c.handle(1, argument, false)); + .invokeAnd((c) -> c.handle(1, argument, false)); assertThat(result.hasResult()).isFalse(); } @@ -197,7 +197,7 @@ class LambdaSafeTests { NonGenericCallback callbackInstance = mock(NonGenericCallback.class); String argument = "foo"; LambdaSafe.callbacks(NonGenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); } @@ -207,7 +207,7 @@ class LambdaSafeTests { StringCallback callbackInstance = mock(StringCallback.class); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); } @@ -217,7 +217,7 @@ class LambdaSafeTests { StringBuilderCallback callbackInstance = mock(StringBuilderCallback.class); StringBuilder argument = new StringBuilder("foo"); LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); then(callbackInstance).should().handle(argument); } @@ -227,7 +227,7 @@ class LambdaSafeTests { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(null)); + .invoke((c) -> c.handle(null)); then(callbackInstance).shouldHaveNoInteractions(); } @@ -237,7 +237,7 @@ class LambdaSafeTests { GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callbacks(GenericCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(argument)); + .invoke((c) -> c.handle(argument)); } @Test @@ -246,7 +246,7 @@ class LambdaSafeTests { GenericMultiArgCallback callbackInstance = (n, s, b) -> fail("Should not get here"); String argument = "foo"; LambdaSafe.callbacks(GenericMultiArgCallback.class, Collections.singleton(callbackInstance), argument) - .invoke((c) -> c.handle(1, argument, false)); + .invoke((c) -> c.handle(1, argument, false)); } @Test @@ -255,8 +255,8 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); Stream result = LambdaSafe - .callbacks(NonGenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(NonGenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -267,8 +267,8 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(123); Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -279,8 +279,8 @@ class LambdaSafeTests { String argument = "foo"; given(callbackInstance.handle("foo")).willReturn(null); Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly((Integer) null); } @@ -291,8 +291,8 @@ class LambdaSafeTests { StringBuilder argument = new StringBuilder("foo"); given(callbackInstance.handle(any(StringBuilder.class))).willReturn(123); Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(123); } @@ -302,8 +302,8 @@ class LambdaSafeTests { GenericFactory callbackInstance = mock(StringBuilderFactory.class); String argument = "foo"; Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(argument)); assertThat(result).isEmpty(); } @@ -316,8 +316,8 @@ class LambdaSafeTests { }; String argument = "foo"; Stream result = LambdaSafe - .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> (c).handle(argument)); + .callbacks(GenericFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> (c).handle(argument)); assertThat(result).isEmpty(); } @@ -330,8 +330,8 @@ class LambdaSafeTests { }; String argument = "foo"; Stream result = LambdaSafe - .callbacks(GenericMultiArgFactory.class, Collections.singleton(callbackInstance), argument) - .invokeAnd((c) -> c.handle(1, argument, false)); + .callbacks(GenericMultiArgFactory.class, Collections.singleton(callbackInstance), argument) + .invokeAnd((c) -> c.handle(1, argument, false)); assertThat(result).isEmpty(); } @@ -353,7 +353,7 @@ class LambdaSafeTests { callbackInstances.add(callback5); String argument = "foo"; Stream result = LambdaSafe.callbacks(GenericFactory.class, callbackInstances, argument) - .invokeAnd((c) -> c.handle(argument)); + .invokeAnd((c) -> c.handle(argument)); assertThat(result).containsExactly(1, 2, 4); } @@ -362,8 +362,9 @@ class LambdaSafeTests { void callbackWithFilterShouldUseFilter() { GenericCallback callbackInstance = mock(StringBuilderCallback.class); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).withFilter(Filter.allowAll()) - .invoke((c) -> c.handle(null)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) + .withFilter(Filter.allowAll()) + .invoke((c) -> c.handle(null)); then(callbackInstance).should().handle(null); } @@ -374,11 +375,12 @@ class LambdaSafeTests { given(logger.isDebugEnabled()).willReturn(true); GenericCallback callbackInstance = (s) -> fail("Should not get here"); String argument = "foo"; - LambdaSafe.callback(GenericCallback.class, callbackInstance, argument).withLogger(logger) - .invoke((c) -> c.handle(argument)); - then(logger).should().debug( - contains("Non-matching CharSequence type for callback LambdaSafeTests.GenericCallback"), - any(Throwable.class)); + LambdaSafe.callback(GenericCallback.class, callbackInstance, argument) + .withLogger(logger) + .invoke((c) -> c.handle(argument)); + then(logger).should() + .debug(contains("Non-matching CharSequence type for callback LambdaSafeTests.GenericCallback"), + any(Throwable.class)); } interface NonGenericCallback { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java index 5d5100e308..0c549e34ba 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class MessageInterpolatorFactoryTests { assertThat(interpolator).isInstanceOf(MessageSourceMessageInterpolator.class); assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource); assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator")) - .isInstanceOf(ResourceBundleMessageInterpolator.class); + .isInstanceOf(ResourceBundleMessageInterpolator.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java index a32f64a094..71aed8a35d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,8 +42,8 @@ class MessageInterpolatorFactoryWithoutElIntegrationTests { void defaultMessageInterpolatorShouldFail() { // Sanity test assertThatExceptionOfType(ValidationException.class) - .isThrownBy(Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) - .withMessageContaining("jakarta.el.ExpressionFactory"); + .isThrownBy(Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) + .withMessageContaining("jakarta.el.ExpressionFactory"); } @Test @@ -60,7 +60,7 @@ class MessageInterpolatorFactoryWithoutElIntegrationTests { assertThat(interpolator).isInstanceOf(MessageSourceMessageInterpolator.class); assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource); assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator")) - .isInstanceOf(ParameterMessageInterpolator.class); + .isInstanceOf(ParameterMessageInterpolator.class); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java index acff21370c..bf1f4b4759 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -86,7 +86,7 @@ class MessageSourceMessageInterpolatorIntegrationTests { @Test void recursion() { assertThatThrownBy(() -> validate("recursion")) - .hasStackTraceContaining("Circular reference '{recursion -> middle -> recursion}'"); + .hasStackTraceContaining("Circular reference '{recursion -> middle -> recursion}'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java index d408279b93..66653ef9ad 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ class MessageSourceMessageInterpolatorTests { void interpolateWhenParametersAreUnknownShouldLeaveThemUnchanged() { this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}"); assertThat(this.interpolator.interpolate("{foo}{top}{bar}", this.context)) - .isEqualTo("{foo}{child}+{child}{bar}"); + .isEqualTo("{foo}{child}+{child}{bar}"); } @Test @@ -63,7 +63,7 @@ class MessageSourceMessageInterpolatorTests { this.messageSource.setUseCodeAsDefaultMessage(true); this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}"); assertThat(this.interpolator.interpolate("{foo}{top}{bar}", this.context)) - .isEqualTo("{foo}{child}+{child}{bar}"); + .isEqualTo("{foo}{child}+{child}{bar}"); } @Test @@ -107,7 +107,7 @@ class MessageSourceMessageInterpolatorTests { this.messageSource.addMessage("b", Locale.getDefault(), "{c}"); this.messageSource.addMessage("c", Locale.getDefault(), "{a}"); assertThatIllegalArgumentException().isThrownBy(() -> this.interpolator.interpolate("{a}", this.context)) - .withMessage("Circular reference '{a -> b -> c -> a}'"); + .withMessage("Circular reference '{a -> b -> c -> a}'"); } private static final class IdentityMessageInterpolator implements MessageInterpolator { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/AbstractClientHttpRequestFactoriesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/AbstractClientHttpRequestFactoriesTests.java index 14b2b80617..947f833254 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/AbstractClientHttpRequestFactoriesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/AbstractClientHttpRequestFactoriesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ abstract class AbstractClientHttpRequestFactoriesTests ClientHttpRequestFactories - .get(ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(true))); + .get(ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(true))); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesOkHttp4Tests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesOkHttp4Tests.java index 826a86d9c4..13158708f5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesOkHttp4Tests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesOkHttp4Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,13 +45,13 @@ class ClientHttpRequestFactoriesOkHttp4Tests @Test void okHttp4IsBeingUsed() { assertThat(new File(OkHttpClient.class.getProtectionDomain().getCodeSource().getLocation().getFile()).getName()) - .startsWith("okhttp-4."); + .startsWith("okhttp-4."); } @Test void getFailsWhenBufferRequestBodyIsEnabled() { assertThatIllegalStateException().isThrownBy(() -> ClientHttpRequestFactories - .get(ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(true))); + .get(ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(true))); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesRuntimeHintsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesRuntimeHintsTests.java index f398cf8322..bb143d3297 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,14 +57,14 @@ class ClientHttpRequestFactoriesRuntimeHintsTests { new ClientHttpRequestFactoriesRuntimeHints().registerHints(hints, getClass().getClassLoader()); ReflectionHintsPredicates reflection = RuntimeHintsPredicates.reflection(); assertThat(reflection - .onMethod(method(HttpComponentsClientHttpRequestFactory.class, "setConnectTimeout", int.class))) - .accepts(hints); + .onMethod(method(HttpComponentsClientHttpRequestFactory.class, "setConnectTimeout", int.class))) + .accepts(hints); assertThat( reflection.onMethod(method(HttpComponentsClientHttpRequestFactory.class, "setReadTimeout", int.class))) - .accepts(hints); + .accepts(hints); assertThat(reflection - .onMethod(method(HttpComponentsClientHttpRequestFactory.class, "setBufferRequestBody", boolean.class))) - .accepts(hints); + .onMethod(method(HttpComponentsClientHttpRequestFactory.class, "setBufferRequestBody", boolean.class))) + .accepts(hints); } @Test @@ -73,9 +73,9 @@ class ClientHttpRequestFactoriesRuntimeHintsTests { new ClientHttpRequestFactoriesRuntimeHints().registerHints(hints, getClass().getClassLoader()); ReflectionHintsPredicates reflection = RuntimeHintsPredicates.reflection(); assertThat(reflection.onMethod(method(OkHttp3ClientHttpRequestFactory.class, "setConnectTimeout", int.class))) - .accepts(hints); + .accepts(hints); assertThat(reflection.onMethod(method(OkHttp3ClientHttpRequestFactory.class, "setReadTimeout", int.class))) - .accepts(hints); + .accepts(hints); assertThat(hints.reflection().getTypeHint(OkHttp3ClientHttpRequestFactory.class).methods()).hasSize(2); } @@ -85,12 +85,12 @@ class ClientHttpRequestFactoriesRuntimeHintsTests { new ClientHttpRequestFactoriesRuntimeHints().registerHints(hints, getClass().getClassLoader()); ReflectionHintsPredicates reflection = RuntimeHintsPredicates.reflection(); assertThat(reflection.onMethod(method(SimpleClientHttpRequestFactory.class, "setConnectTimeout", int.class))) - .accepts(hints); + .accepts(hints); assertThat(reflection.onMethod(method(SimpleClientHttpRequestFactory.class, "setReadTimeout", int.class))) - .accepts(hints); + .accepts(hints); assertThat(reflection - .onMethod(method(SimpleClientHttpRequestFactory.class, "setBufferRequestBody", boolean.class))) - .accepts(hints); + .onMethod(method(SimpleClientHttpRequestFactory.class, "setBufferRequestBody", boolean.class))) + .accepts(hints); } private static Method method(Class target, String name, Class... parameterTypes) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesTests.java index 4bff39170b..34d591efb3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactoriesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,7 +43,7 @@ class ClientHttpRequestFactoriesTests { @Test void getReturnsRequestFactoryOfExpectedType() { ClientHttpRequestFactory requestFactory = ClientHttpRequestFactories - .get(ClientHttpRequestFactorySettings.DEFAULTS); + .get(ClientHttpRequestFactorySettings.DEFAULTS); assertThat(requestFactory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @@ -64,7 +64,7 @@ class ClientHttpRequestFactoriesTests { @Test void getOfHttpComponentsFactoryReturnsHttpComponentsFactory() { ClientHttpRequestFactory requestFactory = ClientHttpRequestFactories - .get(HttpComponentsClientHttpRequestFactory.class, ClientHttpRequestFactorySettings.DEFAULTS); + .get(HttpComponentsClientHttpRequestFactory.class, ClientHttpRequestFactorySettings.DEFAULTS); assertThat(requestFactory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @@ -88,7 +88,7 @@ class ClientHttpRequestFactoriesTests { ClientHttpRequestFactorySettings.DEFAULTS.withConnectTimeout(Duration.ofSeconds(60))); assertThat(requestFactory).isInstanceOf(TestClientHttpRequestFactory.class); assertThat(((TestClientHttpRequestFactory) requestFactory).connectTimeout) - .isEqualTo(Duration.ofSeconds(60).toMillis()); + .isEqualTo(Duration.ofSeconds(60).toMillis()); } @Test @@ -97,7 +97,7 @@ class ClientHttpRequestFactoriesTests { ClientHttpRequestFactorySettings.DEFAULTS.withReadTimeout(Duration.ofSeconds(90))); assertThat(requestFactory).isInstanceOf(TestClientHttpRequestFactory.class); assertThat(((TestClientHttpRequestFactory) requestFactory).readTimeout) - .isEqualTo(Duration.ofSeconds(90).toMillis()); + .isEqualTo(Duration.ofSeconds(90).toMillis()); } @Test @@ -111,49 +111,49 @@ class ClientHttpRequestFactoriesTests { @Test void getOfUnconfigurableTypeWithConnectTimeoutThrows() { assertThatIllegalStateException() - .isThrownBy(() -> ClientHttpRequestFactories.get(UnconfigurableClientHttpRequestFactory.class, - ClientHttpRequestFactorySettings.DEFAULTS.withConnectTimeout(Duration.ofSeconds(60)))) - .withMessageContaining("suitable setConnectTimeout method"); + .isThrownBy(() -> ClientHttpRequestFactories.get(UnconfigurableClientHttpRequestFactory.class, + ClientHttpRequestFactorySettings.DEFAULTS.withConnectTimeout(Duration.ofSeconds(60)))) + .withMessageContaining("suitable setConnectTimeout method"); } @Test void getOfUnconfigurableTypeWithReadTimeoutThrows() { assertThatIllegalStateException() - .isThrownBy(() -> ClientHttpRequestFactories.get(UnconfigurableClientHttpRequestFactory.class, - ClientHttpRequestFactorySettings.DEFAULTS.withReadTimeout(Duration.ofSeconds(60)))) - .withMessageContaining("suitable setReadTimeout method"); + .isThrownBy(() -> ClientHttpRequestFactories.get(UnconfigurableClientHttpRequestFactory.class, + ClientHttpRequestFactorySettings.DEFAULTS.withReadTimeout(Duration.ofSeconds(60)))) + .withMessageContaining("suitable setReadTimeout method"); } @Test void getOfUnconfigurableTypeWithBodyBufferingThrows() { assertThatIllegalStateException() - .isThrownBy(() -> ClientHttpRequestFactories.get(UnconfigurableClientHttpRequestFactory.class, - ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(true))) - .withMessageContaining("suitable setBufferRequestBody method"); + .isThrownBy(() -> ClientHttpRequestFactories.get(UnconfigurableClientHttpRequestFactory.class, + ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(true))) + .withMessageContaining("suitable setBufferRequestBody method"); } @Test void getOfTypeWithDeprecatedConnectTimeoutThrowsWithConnectTimeout() { assertThatIllegalStateException() - .isThrownBy(() -> ClientHttpRequestFactories.get(DeprecatedMethodsClientHttpRequestFactory.class, - ClientHttpRequestFactorySettings.DEFAULTS.withConnectTimeout(Duration.ofSeconds(60)))) - .withMessageContaining("setConnectTimeout method marked as deprecated"); + .isThrownBy(() -> ClientHttpRequestFactories.get(DeprecatedMethodsClientHttpRequestFactory.class, + ClientHttpRequestFactorySettings.DEFAULTS.withConnectTimeout(Duration.ofSeconds(60)))) + .withMessageContaining("setConnectTimeout method marked as deprecated"); } @Test void getOfTypeWithDeprecatedReadTimeoutThrowsWithReadTimeout() { assertThatIllegalStateException() - .isThrownBy(() -> ClientHttpRequestFactories.get(DeprecatedMethodsClientHttpRequestFactory.class, - ClientHttpRequestFactorySettings.DEFAULTS.withReadTimeout(Duration.ofSeconds(60)))) - .withMessageContaining("setReadTimeout method marked as deprecated"); + .isThrownBy(() -> ClientHttpRequestFactories.get(DeprecatedMethodsClientHttpRequestFactory.class, + ClientHttpRequestFactorySettings.DEFAULTS.withReadTimeout(Duration.ofSeconds(60)))) + .withMessageContaining("setReadTimeout method marked as deprecated"); } @Test void getOfTypeWithDeprecatedBufferRequestBodyThrowsWithBufferRequestBody() { assertThatIllegalStateException() - .isThrownBy(() -> ClientHttpRequestFactories.get(DeprecatedMethodsClientHttpRequestFactory.class, - ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(false))) - .withMessageContaining("setBufferRequestBody method marked as deprecated"); + .isThrownBy(() -> ClientHttpRequestFactories.get(DeprecatedMethodsClientHttpRequestFactory.class, + ClientHttpRequestFactorySettings.DEFAULTS.withBufferRequestBody(false))) + .withMessageContaining("setBufferRequestBody method marked as deprecated"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettingsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettingsTests.java index e143d26617..5d6663a5c7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettingsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/ClientHttpRequestFactorySettingsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class ClientHttpRequestFactorySettingsTests { @Test void withConnectTimeoutReturnsInstanceWithUpdatedConnectionTimeout() { ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS - .withConnectTimeout(ONE_SECOND); + .withConnectTimeout(ONE_SECOND); assertThat(settings.connectTimeout()).isEqualTo(ONE_SECOND); assertThat(settings.readTimeout()).isNull(); assertThat(settings.bufferRequestBody()).isNull(); @@ -51,7 +51,7 @@ class ClientHttpRequestFactorySettingsTests { @Test void withReadTimeoutReturnsInstanceWithUpdatedReadTimeout() { ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS - .withReadTimeout(ONE_SECOND); + .withReadTimeout(ONE_SECOND); assertThat(settings.connectTimeout()).isNull(); assertThat(settings.readTimeout()).isEqualTo(ONE_SECOND); assertThat(settings.bufferRequestBody()).isNull(); @@ -60,7 +60,7 @@ class ClientHttpRequestFactorySettingsTests { @Test void withBufferRequestBodyReturnsInstanceWithUpdatedBufferRequestBody() { ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS - .withBufferRequestBody(true); + .withBufferRequestBody(true); assertThat(settings.connectTimeout()).isNull(); assertThat(settings.readTimeout()).isNull(); assertThat(settings.bufferRequestBody()).isTrue(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java index b8b4ae2ab5..5e7ff9a91b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderClientHttpRequestInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -49,7 +49,8 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { @Test void createRequestWhenHasBasicAuthAndNoAuthHeaderAddsHeader() { new RestTemplateBuilderClientHttpRequestInitializer(new BasicAuthentication("spring", "boot", null), - Collections.emptyMap(), Collections.emptySet()).initialize(this.request); + Collections.emptyMap(), Collections.emptySet()) + .initialize(this.request); assertThat(this.request.getHeaders().get(HttpHeaders.AUTHORIZATION)).containsExactly("Basic c3ByaW5nOmJvb3Q="); } @@ -57,7 +58,8 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { void createRequestWhenHasBasicAuthAndExistingAuthHeaderDoesNotAddHeader() { this.request.getHeaders().setBasicAuth("boot", "spring"); new RestTemplateBuilderClientHttpRequestInitializer(new BasicAuthentication("spring", "boot", null), - Collections.emptyMap(), Collections.emptySet()).initialize(this.request); + Collections.emptyMap(), Collections.emptySet()) + .initialize(this.request); assertThat(this.request.getHeaders().get(HttpHeaders.AUTHORIZATION)).doesNotContain("Basic c3ByaW5nOmJvb3Q="); } @@ -69,7 +71,7 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { defaultHeaders.put("two", Arrays.asList("2", "3")); defaultHeaders.put("three", Collections.singletonList("4")); new RestTemplateBuilderClientHttpRequestInitializer(null, defaultHeaders, Collections.emptySet()) - .initialize(this.request); + .initialize(this.request); assertThat(this.request.getHeaders().get("one")).containsExactly("existing"); assertThat(this.request.getHeaders().get("two")).containsExactly("2", "3"); assertThat(this.request.getHeaders().get("three")).containsExactly("4"); @@ -83,7 +85,7 @@ class RestTemplateBuilderClientHttpRequestInitializerTests { customizers.add(mock(RestTemplateRequestCustomizer.class)); customizers.add(mock(RestTemplateRequestCustomizer.class)); new RestTemplateBuilderClientHttpRequestInitializer(null, Collections.emptyMap(), customizers) - .initialize(this.request); + .initialize(this.request); InOrder inOrder = inOrder(customizers.toArray()); for (RestTemplateRequestCustomizer customizer : customizers) { inOrder.verify((RestTemplateRequestCustomizer) customizer).customize(this.request); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index 8b2e706317..c4d1e8ea40 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,7 @@ class RestTemplateBuilderTests { void createWhenCustomizersAreNullShouldThrowException() { RestTemplateCustomizer[] customizers = null; assertThatIllegalArgumentException().isThrownBy(() -> new RestTemplateBuilder(customizers)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test @@ -121,8 +121,9 @@ class RestTemplateBuilderTests { @Test void rootUriShouldApplyAfterUriTemplateHandler() { UriTemplateHandler uriTemplateHandler = mock(UriTemplateHandler.class); - RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler).rootUri("https://example.com") - .build(); + RestTemplate template = this.builder.uriTemplateHandler(uriTemplateHandler) + .rootUri("https://example.com") + .build(); UriTemplateHandler handler = template.getUriTemplateHandler(); handler.expand("/hello"); assertThat(handler).isInstanceOf(RootUriTemplateHandler.class); @@ -132,15 +133,15 @@ class RestTemplateBuilderTests { @Test void messageConvertersWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageConverters((HttpMessageConverter[]) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.messageConverters((HttpMessageConverter[]) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageConverters((Set>) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.messageConverters((Set>) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test @@ -152,29 +153,31 @@ class RestTemplateBuilderTests { @Test void messageConvertersShouldReplaceExisting() { RestTemplate template = this.builder.messageConverters(new ResourceHttpMessageConverter()) - .messageConverters(Collections.singleton(this.messageConverter)).build(); + .messageConverters(Collections.singleton(this.messageConverter)) + .build(); assertThat(template.getMessageConverters()).containsOnly(this.messageConverter); } @Test void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalMessageConverters((HttpMessageConverter[]) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.additionalMessageConverters((HttpMessageConverter[]) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalMessageConverters((Set>) null)) - .withMessageContaining("MessageConverters must not be null"); + .isThrownBy(() -> this.builder.additionalMessageConverters((Set>) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test void additionalMessageConvertersShouldAddToExisting() { HttpMessageConverter resourceConverter = new ResourceHttpMessageConverter(); RestTemplate template = this.builder.messageConverters(resourceConverter) - .additionalMessageConverters(this.messageConverter).build(); + .additionalMessageConverters(this.messageConverter) + .build(); assertThat(template.getMessageConverters()).containsOnly(resourceConverter, this.messageConverter); } @@ -195,15 +198,15 @@ class RestTemplateBuilderTests { @Test void interceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) + .withMessageContaining("interceptors must not be null"); } @Test void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.interceptors((Set) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.interceptors((Set) null)) + .withMessageContaining("interceptors must not be null"); } @Test @@ -215,22 +218,23 @@ class RestTemplateBuilderTests { @Test void interceptorsShouldReplaceExisting() { RestTemplate template = this.builder.interceptors(mock(ClientHttpRequestInterceptor.class)) - .interceptors(Collections.singleton(this.interceptor)).build(); + .interceptors(Collections.singleton(this.interceptor)) + .build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null)) + .withMessageContaining("interceptors must not be null"); } @Test void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) - .withMessageContaining("interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) + .withMessageContaining("interceptors must not be null"); } @Test @@ -243,8 +247,8 @@ class RestTemplateBuilderTests { @Test void requestFactoryClassWhenFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.requestFactory((Class) null)) - .withMessageContaining("RequestFactoryType must not be null"); + .isThrownBy(() -> this.builder.requestFactory((Class) null)) + .withMessageContaining("RequestFactoryType must not be null"); } @Test @@ -262,16 +266,16 @@ class RestTemplateBuilderTests { @Test void requestFactoryWhenSupplierIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.requestFactory((Supplier) null)) - .withMessageContaining("RequestFactorySupplier must not be null"); + .isThrownBy(() -> this.builder.requestFactory((Supplier) null)) + .withMessageContaining("RequestFactorySupplier must not be null"); } @Test void requestFactoryWhenFunctionIsNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder - .requestFactory((Function) null)) - .withMessageContaining("RequestFactoryFunction must not be null"); + .isThrownBy(() -> this.builder + .requestFactory((Function) null)) + .withMessageContaining("RequestFactoryFunction must not be null"); } @Test @@ -284,7 +288,7 @@ class RestTemplateBuilderTests { @Test void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.uriTemplateHandler(null)) - .withMessageContaining("UriTemplateHandler must not be null"); + .withMessageContaining("UriTemplateHandler must not be null"); } @Test @@ -297,7 +301,7 @@ class RestTemplateBuilderTests { @Test void errorHandlerWhenHandlerIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.errorHandler(null)) - .withMessageContaining("ErrorHandler must not be null"); + .withMessageContaining("ErrorHandler must not be null"); } @Test @@ -342,7 +346,8 @@ class RestTemplateBuilderTests { @Test void requestCustomizersAddsCustomizers() { RestTemplate template = this.builder - .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")).build(); + .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")) + .build(); ClientHttpRequest request = createRequest(template); assertThat(request.getHeaders()).contains(entry("spring", Collections.singletonList("framework"))); } @@ -350,24 +355,25 @@ class RestTemplateBuilderTests { @Test void additionalRequestCustomizersAddsCustomizers() { RestTemplate template = this.builder - .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")) - .additionalRequestCustomizers((request) -> request.getHeaders().add("for", "java")).build(); + .requestCustomizers((request) -> request.getHeaders().add("spring", "framework")) + .additionalRequestCustomizers((request) -> request.getHeaders().add("for", "java")) + .build(); ClientHttpRequest request = createRequest(template); assertThat(request.getHeaders()).contains(entry("spring", Collections.singletonList("framework"))) - .contains(entry("for", Collections.singletonList("java"))); + .contains(entry("for", Collections.singletonList("java"))); } @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.customizers((RestTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Set) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -389,8 +395,9 @@ class RestTemplateBuilderTests { void customizersShouldReplaceExisting() { RestTemplateCustomizer customizer1 = mock(RestTemplateCustomizer.class); RestTemplateCustomizer customizer2 = mock(RestTemplateCustomizer.class); - RestTemplate template = this.builder.customizers(customizer1).customizers(Collections.singleton(customizer2)) - .build(); + RestTemplate template = this.builder.customizers(customizer1) + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(template); } @@ -398,15 +405,15 @@ class RestTemplateBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) - .withMessageContaining("RestTemplateCustomizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((Set) null)) + .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test @@ -423,18 +430,23 @@ class RestTemplateBuilderTests { void customizerShouldBeAppliedAtTheEnd() { ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - this.builder.interceptors(this.interceptor).messageConverters(this.messageConverter) - .rootUri("http://localhost:8080").errorHandler(errorHandler).basicAuthentication("spring", "boot") - .requestFactory(() -> requestFactory).customizers((restTemplate) -> { - assertThat(restTemplate.getInterceptors()).hasSize(1); - assertThat(restTemplate.getMessageConverters()).contains(this.messageConverter); - assertThat(restTemplate.getUriTemplateHandler()).isInstanceOf(RootUriTemplateHandler.class); - assertThat(restTemplate.getErrorHandler()).isEqualTo(errorHandler); - ClientHttpRequestFactory actualRequestFactory = restTemplate.getRequestFactory(); - assertThat(actualRequestFactory).isInstanceOf(InterceptingClientHttpRequestFactory.class); - ClientHttpRequestInitializer initializer = restTemplate.getClientHttpRequestInitializers().get(0); - assertThat(initializer).isInstanceOf(RestTemplateBuilderClientHttpRequestInitializer.class); - }).build(); + this.builder.interceptors(this.interceptor) + .messageConverters(this.messageConverter) + .rootUri("http://localhost:8080") + .errorHandler(errorHandler) + .basicAuthentication("spring", "boot") + .requestFactory(() -> requestFactory) + .customizers((restTemplate) -> { + assertThat(restTemplate.getInterceptors()).hasSize(1); + assertThat(restTemplate.getMessageConverters()).contains(this.messageConverter); + assertThat(restTemplate.getUriTemplateHandler()).isInstanceOf(RootUriTemplateHandler.class); + assertThat(restTemplate.getErrorHandler()).isEqualTo(errorHandler); + ClientHttpRequestFactory actualRequestFactory = restTemplate.getRequestFactory(); + assertThat(actualRequestFactory).isInstanceOf(InterceptingClientHttpRequestFactory.class); + ClientHttpRequestInitializer initializer = restTemplate.getClientHttpRequestInitializers().get(0); + assertThat(initializer).isInstanceOf(RestTemplateBuilderClientHttpRequestInitializer.class); + }) + .build(); } @Test @@ -460,7 +472,7 @@ class RestTemplateBuilderTests { void unwrappingDoesNotAffectRequestFactoryThatIsSetOnTheBuiltTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); RestTemplate template = this.builder.requestFactory(() -> new BufferingClientHttpRequestFactory(requestFactory)) - .build(); + .build(); assertThat(template.getRequestFactory()).isInstanceOf(BufferingClientHttpRequestFactory.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java index f75da6468b..2e81400089 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -61,13 +61,13 @@ class RootUriTemplateHandlerTests { @Test void createWithNullRootUriShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler((String) null)) - .withMessageContaining("RootUri must not be null"); + .withMessageContaining("RootUri must not be null"); } @Test void createWithNullHandlerShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new RootUriTemplateHandler("https://example.com", null)) - .withMessageContaining("Handler must not be null"); + .withMessageContaining("Handler must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java index ae9f86e566..09ecc2c3ce 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -67,15 +67,15 @@ class JettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactor void setNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setServerCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java index add574036a..63fe240223 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -330,8 +330,9 @@ class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryT response = request.get(); assertThat(response).isInstanceOf(HttpResponse.class); assertThat(((HttpResponse) response).getCode()).isEqualTo(200); - assertThat(((HttpResponse) response).getFirstHeader("Connection")).isNotNull().extracting(Header::getValue) - .isEqualTo("close"); + assertThat(((HttpResponse) response).getFirstHeader("Connection")).isNotNull() + .extracting(Header::getValue) + .isEqualTo("close"); this.webServer.stop(); } @@ -432,7 +433,7 @@ class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryT threadPool.setMinThreads(2); }); assertThatExceptionOfType(WebServerException.class).isThrownBy(factory.getWebServer()::start) - .withCauseInstanceOf(IllegalStateException.class); + .withCauseInstanceOf(IllegalStateException.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java index 4122e0e5b2..bd00d201fb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,7 +58,7 @@ class SslServerCustomizerTests { assertThat(server.getConnectors()).hasSize(1); List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); assertThat(factories).extracting((factory) -> (Class) factory.getClass()) - .containsExactly(SslConnectionFactory.class, HttpConnectionFactory.class); + .containsExactly(SslConnectionFactory.class, HttpConnectionFactory.class); } @Test @@ -71,9 +71,9 @@ class SslServerCustomizerTests { Server server = createCustomizedServer(http2); assertThat(server.getConnectors()).hasSize(1); List factories = new ArrayList<>(server.getConnectors()[0].getConnectionFactories()); - assertThat(factories).extracting((factory) -> (Class) factory.getClass()).containsExactly( - SslConnectionFactory.class, ALPNServerConnectionFactory.class, HTTP2ServerConnectionFactory.class, - HttpConnectionFactory.class); + assertThat(factories).extracting((factory) -> (Class) factory.getClass()) + .containsExactly(SslConnectionFactory.class, ALPNServerConnectionFactory.class, + HTTP2ServerConnectionFactory.class, HttpConnectionFactory.class); } @Test @@ -93,11 +93,11 @@ class SslServerCustomizerTests { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); assertThatExceptionOfType(Exception.class) - .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) - .satisfies((ex) -> { - assertThat(ex).isInstanceOf(WebServerException.class); - assertThat(ex).hasMessageContaining("Could not load key store 'null'"); - }); + .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) + .satisfies((ex) -> { + assertThat(ex).isInstanceOf(WebServerException.class); + assertThat(ex).hasMessageContaining("Could not load key store 'null'"); + }); } @Test @@ -109,8 +109,8 @@ class SslServerCustomizerTests { ssl.setKeyPassword("password"); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); assertThatIllegalStateException() - .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) - .withMessageContaining("must be empty or null for PKCS11 key stores"); + .isThrownBy(() -> customizer.configureSsl(new SslContextFactory.Server(), ssl, null)) + .withMessageContaining("must be empty or null for PKCS11 key stores"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java index 899fa38155..983317ccf6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -67,7 +67,8 @@ class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactor this.webServer.start(); factory.setPort(this.webServer.getPort()); assertThatExceptionOfType(PortInUseException.class).isThrownBy(factory.getWebServer(new EchoHandler())::start) - .satisfies(this::portMatchesRequirement).withCauseInstanceOf(Throwable.class); + .satisfies(this::portMatchesRequirement) + .withCauseInstanceOf(Throwable.class); } @Test @@ -147,10 +148,16 @@ class NettyReactiveWebServerFactoryTests extends AbstractReactiveWebServerFactor this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); ReactorClientHttpConnector connector = buildTrustAllSslConnector(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(connector).build(); - return client.post().uri("/test").contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromValue("Hello World")) - .retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(connector) + .build(); + return client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java index 0c82384386..25dda5d4be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,8 +47,8 @@ class SslServerCustomizerTests { ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.KeyStoreProvider"); + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.KeyStoreProvider"); } @Test @@ -59,8 +59,8 @@ class SslServerCustomizerTests { ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getTrustManagerFactory(ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.TrustStoreProvider"); + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.TrustStoreProvider"); } @Test @@ -68,7 +68,8 @@ class SslServerCustomizerTests { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) - .withCauseInstanceOf(WebServerException.class).withMessageContaining("Could not load key store 'null'"); + .withCauseInstanceOf(WebServerException.class) + .withMessageContaining("Could not load key store 'null'"); } @Test @@ -80,8 +81,8 @@ class SslServerCustomizerTests { ssl.setKeyPassword("password"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); assertThatIllegalStateException().isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) - .withCauseInstanceOf(IllegalStateException.class) - .withMessageContaining("must be empty or null for PKCS11 key stores"); + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("must be empty or null for PKCS11 key stores"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java index 6634d1c164..53c6973f45 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -185,8 +185,8 @@ class SslConnectorCustomizerTests { @Test void customizeWhenSslIsEnabledWithNoKeyStoreAndNotPkcs11ThrowsException() { assertThatExceptionOfType(WebServerException.class) - .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null).customize(this.tomcat.getConnector())) - .withMessageContaining("Could not load key store 'null'"); + .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null).customize(this.tomcat.getConnector())) + .withMessageContaining("Could not load key store 'null'"); } @Test @@ -198,7 +198,7 @@ class SslConnectorCustomizerTests { ssl.setKeyPassword("password"); SslConnectorCustomizer customizer = new SslConnectorCustomizer(ssl, null); assertThatIllegalStateException().isThrownBy(() -> customizer.customize(this.tomcat.getConnector())) - .withMessageContaining("must be empty or null for PKCS11 key stores"); + .withMessageContaining("must be empty or null for PKCS11 key stores"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java index cb4be3552b..7dd30e2735 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedWebappClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ class TomcatEmbeddedWebappClassLoaderTests { void getResourceFindsResourceFromParentClassLoader() throws Exception { File war = createWar(); withWebappClassLoader(war, (classLoader) -> assertThat(classLoader.getResource("test.txt")) - .isEqualTo(new URL(webInfClassesUrlString(war) + "test.txt"))); + .isEqualTo(new URL(webInfClassesUrlString(war) + "test.txt"))); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java index 0368235f60..42235365d5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -123,30 +123,30 @@ class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFacto void setNullConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullAddConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void setNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test void addNullProtocolHandlerCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test @@ -195,7 +195,7 @@ class TomcatReactiveWebServerFactoryTests extends AbstractReactiveWebServerFacto void addNullAdditionalConnectorsThrows() { TomcatReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.addAdditionalTomcatConnectors((Connector[]) null)) - .withMessageContaining("Connectors must not be null"); + .withMessageContaining("Connectors must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java index 1e1d9e83cf..41528d119c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -222,7 +222,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void tomcatProtocolHandlerCanBeCustomized() { TomcatServletWebServerFactory factory = getFactory(); TomcatProtocolHandlerCustomizer> customizer = (protocolHandler) -> protocolHandler - .setProcessorCache(250); + .setProcessorCache(250); factory.addProtocolHandlerCustomizers(customizer); Tomcat tomcat = getTomcat(factory); Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors().get(tomcat.getService())[0]; @@ -245,7 +245,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void addNullAdditionalConnectorThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.addAdditionalTomcatConnectors((Connector[]) null)) - .withMessageContaining("Connectors must not be null"); + .withMessageContaining("Connectors must not be null"); } @Test @@ -282,45 +282,45 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void setNullTomcatContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatContextCustomizers(null)) - .withMessageContaining("TomcatContextCustomizers must not be null"); + .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test void addNullContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) - .withMessageContaining("TomcatContextCustomizers must not be null"); + .isThrownBy(() -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) + .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test void setNullTomcatConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) - .withMessageContaining("TomcatConnectorCustomizers must not be null"); + .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test void addNullConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) - .withMessageContaining("TomcatConnectorCustomizers must not be null"); + .isThrownBy(() -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test void setNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setTomcatProtocolHandlerCustomizers(null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test void addNullTomcatProtocolHandlerCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) - .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); + .isThrownBy(() -> factory.addProtocolHandlerCustomizers((TomcatProtocolHandlerCustomizer[]) null)) + .withMessageContaining("TomcatProtocolHandlerCustomizers must not be null"); } @Test @@ -417,7 +417,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory this.webServer = factory.getWebServer(); // override defaults, see org.apache.catalina.util.CharsetMapperDefault.properties Properties charsetMapperDefault = PropertiesLoaderUtils - .loadProperties(new ClassPathResource("CharsetMapperDefault.properties", CharsetMapper.class)); + .loadProperties(new ClassPathResource("CharsetMapperDefault.properties", CharsetMapper.class)); for (String language : charsetMapperDefault.stringPropertyNames()) { assertThat(getCharset(new Locale(language))).isEqualTo(StandardCharsets.UTF_8); } @@ -488,7 +488,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory } }); this.webServer = factory - .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); assertThatExceptionOfType(WebServerException.class).isThrownBy(this.webServer::start); } @@ -501,7 +501,7 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory } }); this.webServer = factory - .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); this.webServer.start(); } @@ -598,9 +598,9 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory blockingServlet.awaitQueue(); this.webServer.shutDownGracefully((result) -> { }); - Object unconnectableRequest = Awaitility.await().until( - () -> initiateGetRequest(HttpClients.createDefault(), port, "/").get(), - (result) -> result instanceof Exception); + Object unconnectableRequest = Awaitility.await() + .until(() -> initiateGetRequest(HttpClients.createDefault(), port, "/").get(), + (result) -> result instanceof Exception); assertThat(unconnectableRequest).isInstanceOf(HttpHostConnectException.class); blockingServlet.admitOne(); assertThat(request.get()).isInstanceOf(HttpResponse.class); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java index c0bcf88840..d06092bb48 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,8 +50,8 @@ class SslBuilderCustomizerTests { ssl.setKeyStore("src/test/resources/test.jks"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); KeyManager[] keyManagers = ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); - Class name = Class.forName( - "org.springframework.boot.web.embedded.undertow.SslBuilderCustomizer$ConfigurableAliasKeyManager"); + Class name = Class + .forName("org.springframework.boot.web.embedded.undertow.SslBuilderCustomizer$ConfigurableAliasKeyManager"); assertThat(keyManagers[0]).isNotInstanceOf(name); } @@ -63,9 +63,9 @@ class SslBuilderCustomizerTests { ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.KeyStoreProvider"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.KeyStoreProvider"); } @Test @@ -76,9 +76,9 @@ class SslBuilderCustomizerTests { ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null)) - .withCauseInstanceOf(NoSuchProviderException.class) - .withMessageContaining("com.example.TrustStoreProvider"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.TrustStoreProvider"); } @Test @@ -86,8 +86,9 @@ class SslBuilderCustomizerTests { Ssl ssl = new Ssl(); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) - .withCauseInstanceOf(WebServerException.class).withMessageContaining("Could not load key store 'null'"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) + .withCauseInstanceOf(WebServerException.class) + .withMessageContaining("Could not load key store 'null'"); } @Test @@ -99,9 +100,9 @@ class SslBuilderCustomizerTests { ssl.setKeyPassword("password"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatIllegalStateException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) - .withCauseInstanceOf(IllegalArgumentException.class) - .withMessageContaining("Input keystore location is not valid for keystore type 'PKCS11'"); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("Input keystore location is not valid for keystore type 'PKCS11'"); } @Test @@ -112,7 +113,7 @@ class SslBuilderCustomizerTests { ssl.setKeyStorePassword("1234"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); assertThatNoException() - .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)); + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java index f9b86c6274..836532109f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java @@ -62,15 +62,15 @@ class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebServerFac void setNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -139,8 +139,12 @@ class UndertowReactiveWebServerFactoryTests extends AbstractReactiveWebServerFac this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); WebClient client = getWebClient(this.webServer.getPort()).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); File accessLog = new File(accessLogDirectory, expectedFile); awaitFile(accessLog); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java index e6a6f14e7d..dd42e2bf99 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java @@ -96,15 +96,15 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto void setNullBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setBuilderCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullAddBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -125,15 +125,15 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto void setNullDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException().isThrownBy(() -> factory.setDeploymentInfoCustomizers(null)) - .withMessageContaining("Customizers must not be null"); + .withMessageContaining("Customizers must not be null"); } @Test void addNullAddDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); assertThatIllegalArgumentException() - .isThrownBy(() -> factory.addDeploymentInfoCustomizers((UndertowDeploymentInfoCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> factory.addDeploymentInfoCustomizers((UndertowDeploymentInfoCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -231,23 +231,23 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto @Override protected void addConnector(int port, AbstractServletWebServerFactory factory) { ((UndertowServletWebServerFactory) factory) - .addBuilderCustomizers((builder) -> builder.addHttpListener(port, "0.0.0.0")); + .addBuilderCustomizers((builder) -> builder.addHttpListener(port, "0.0.0.0")); } @Test void sslRestrictedProtocolsEmptyCipherFailure() { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, - new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" })) - .isInstanceOfAny(SSLException.class, SSLHandshakeException.class, SocketException.class); + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, + new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" })) + .isInstanceOfAny(SSLException.class, SSLHandshakeException.class, SocketException.class); } @Test void sslRestrictedProtocolsECDHETLS1Failure() { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, - new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })) - .isInstanceOfAny(SSLException.class, SocketException.class); + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, + new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })) + .isInstanceOfAny(SSLException.class, SocketException.class); } @Test @@ -265,9 +265,9 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto @Test void sslRestrictedProtocolsRSATLS11Failure() { assertThatIOException() - .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, - new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" })) - .isInstanceOfAny(SSLException.class, SocketException.class); + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, + new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" })) + .isInstanceOfAny(SSLException.class, SocketException.class); } @Override @@ -291,14 +291,16 @@ class UndertowServletWebServerFactoryTests extends AbstractServletWebServerFacto @Override protected Map getActualMimeMappings() { - return ((UndertowServletWebServer) this.webServer).getDeploymentManager().getDeployment() - .getMimeExtensionMappings(); + return ((UndertowServletWebServer) this.webServer).getDeploymentManager() + .getDeployment() + .getMimeExtensionMappings(); } @Override protected Charset getCharset(Locale locale) { - DeploymentInfo info = ((UndertowServletWebServer) this.webServer).getDeploymentManager().getDeployment() - .getDeploymentInfo(); + DeploymentInfo info = ((UndertowServletWebServer) this.webServer).getDeploymentManager() + .getDeployment() + .getDeploymentInfo(); String charsetName = info.getLocaleCharsetMapping().get(locale.toString()); return (charsetName != null) ? Charset.forName(charsetName) : null; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerRuntimeHintsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerRuntimeHintsTests.java index f2ea77b0a3..58f84e02fd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerRuntimeHintsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowWebServerRuntimeHintsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -43,12 +43,12 @@ class UndertowWebServerRuntimeHintsTests { assertThat(reflectionOnField("io.undertow.Undertow$ListenerConfig", "type")).accepts(runtimeHints); assertThat(reflectionOnField("io.undertow.Undertow$ListenerConfig", "port")).accepts(runtimeHints); assertThat(reflectionOnField("io.undertow.protocols.ssl.UndertowAcceptingSslChannel", "ssl")) - .accepts(runtimeHints); + .accepts(runtimeHints); } private FieldHintPredicate reflectionOnField(String className, String fieldName) throws ClassNotFoundException { return RuntimeHintsPredicates.reflection() - .onField(ReflectionUtils.findField(Class.forName(className), fieldName)); + .onField(ReflectionUtils.findField(Class.forName(className), fieldName)); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java index 8f93c71d5d..13177c6fd2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/ReactiveWebServerApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -60,16 +60,17 @@ class ReactiveWebServerApplicationContextTests { @Test void whenThereIsNoWebServerFactoryBeanThenContextRefreshWillFail() { assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .havingRootCause().withMessageContaining( - "Unable to start ReactiveWebServerApplicationContext due to missing ReactiveWebServerFactory bean"); + .havingRootCause() + .withMessageContaining( + "Unable to start ReactiveWebServerApplicationContext due to missing ReactiveWebServerFactory bean"); } @Test void whenThereIsNoHttpHandlerBeanThenContextRefreshWillFail() { addWebServerFactoryBean(); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .havingRootCause() - .withMessageContaining("Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean"); + .havingRootCause() + .withMessageContaining("Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean"); } @Test @@ -77,8 +78,9 @@ class ReactiveWebServerApplicationContextTests { addWebServerFactoryBean(); addWebServerFactoryBean("anotherWebServerFactory"); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .havingRootCause().withMessageContaining( - "Unable to start ReactiveWebApplicationContext due to multiple ReactiveWebServerFactory beans"); + .havingRootCause() + .withMessageContaining( + "Unable to start ReactiveWebApplicationContext due to multiple ReactiveWebServerFactory beans"); } @Test @@ -87,8 +89,8 @@ class ReactiveWebServerApplicationContextTests { addHttpHandlerBean("httpHandler1"); addHttpHandlerBean("httpHandler2"); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .havingRootCause().withMessageContaining( - "Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans"); + .havingRootCause() + .withMessageContaining("Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans"); } @Test @@ -99,8 +101,9 @@ class ReactiveWebServerApplicationContextTests { this.context.addApplicationListener(listener); this.context.refresh(); List events = listener.receivedEvents(); - assertThat(events).hasSize(2).extracting("class").containsExactly(ReactiveWebServerInitializedEvent.class, - ContextRefreshedEvent.class); + assertThat(events).hasSize(2) + .extracting("class") + .containsExactly(ReactiveWebServerInitializedEvent.class, ContextRefreshedEvent.class); ReactiveWebServerInitializedEvent initializedEvent = (ReactiveWebServerInitializedEvent) events.get(0); assertThat(initializedEvent.getSource().getPort()).isGreaterThanOrEqualTo(0); assertThat(initializedEvent.getApplicationContext()).isEqualTo(this.context); @@ -137,10 +140,11 @@ class ReactiveWebServerApplicationContextTests { this.context.addApplicationListener(listener); this.context.close(); List events = listener.receivedEvents(); - assertThat(events).hasSize(2).extracting("class").contains(AvailabilityChangeEvent.class, - ContextClosedEvent.class); + assertThat(events).hasSize(2) + .extracting("class") + .contains(AvailabilityChangeEvent.class, ContextClosedEvent.class); assertThat(((AvailabilityChangeEvent) events.get(0)).getState()) - .isEqualTo(ReadinessState.REFUSING_TRAFFIC); + .isEqualTo(ReadinessState.REFUSING_TRAFFIC); } @Test @@ -161,7 +165,7 @@ class ReactiveWebServerApplicationContextTests { addHttpHandlerBean(); this.context.refresh(); assertThatIllegalStateException().isThrownBy(() -> this.context.refresh()) - .withMessageContaining("multiple refresh attempts"); + .withMessageContaining("multiple refresh attempts"); } private void addHttpHandlerBean() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java index f77057b3e0..06633045c3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java @@ -64,8 +64,8 @@ class DefaultErrorAttributesTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build()); ServerRequest request = ServerRequest.create(exchange, this.readers); assertThatIllegalStateException() - .isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, ErrorAttributeOptions.defaults())) - .withMessageContaining("Missing exception attribute in ServerWebExchange"); + .isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, ErrorAttributeOptions.defaults())) + .withMessageContaining("Missing exception attribute in ServerWebExchange"); } @Test @@ -243,9 +243,9 @@ class DefaultErrorAttributesTests { Map attributes = this.errorAttributes.getErrorAttributes(buildServerRequest(request, ex), ErrorAttributeOptions.of(Include.MESSAGE, Include.BINDING_ERRORS)); assertThat(attributes.get("message")).asString() - .startsWith("Validation failed for argument at index 0 in method: " - + "int org.springframework.boot.web.reactive.error.DefaultErrorAttributesTests" - + ".method(java.lang.String), with 1 error(s)"); + .startsWith("Validation failed for argument at index 0 in method: " + + "int org.springframework.boot.web.reactive.error.DefaultErrorAttributesTests" + + ".method(java.lang.String), with 1 error(s)"); assertThat(attributes).containsEntry("errors", bindingResult.getAllErrors()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java index cecfd57d9a..b4add7efcf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/result/view/MustacheViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -52,9 +52,10 @@ class MustacheViewTests { view.setCharset(StandardCharsets.UTF_8.displayName()); view.setApplicationContext(this.context); view.render(Collections.singletonMap("World", "Spring"), MediaType.TEXT_HTML, exchange) - .block(Duration.ofSeconds(30)); + .block(Duration.ofSeconds(30)); StepVerifier.create(exchange.getResponse().getBodyAsString()) - .assertNext((body) -> assertThat(body).isEqualToIgnoringWhitespace("Hello Spring")).verifyComplete(); + .assertNext((body) -> assertThat(body).isEqualToIgnoringWhitespace("Hello Spring")) + .verifyComplete(); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java index 1dab6a94f4..3497230ce8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java @@ -112,9 +112,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer.start(); return this.webServer.getPort(); }); - Mono result = getWebClient(this.webServer.getPort()).build().post().uri("/test") - .contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromValue("Hello World")).retrieve() - .bodyToMono(String.class); + Mono result = getWebClient(this.webServer.getPort()).build() + .post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); assertThat(this.webServer.getPort()).isEqualTo(specificPort); } @@ -150,10 +154,16 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); ReactorClientHttpConnector connector = buildTrustAllSslConnector(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(connector).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(connector) + .build(); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); } @@ -171,11 +181,17 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); ReactorClientHttpConnector connector = buildTrustAllSslConnector(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(connector).build(); - - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(connector) + .build(); + + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); StepVerifier.create(result).expectNext("Hello World").verifyComplete(); @@ -199,8 +215,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { } protected ReactorClientHttpConnector buildTrustAllSslConnector() { - Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient().configure( - (builder) -> builder.sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE)); + Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE)); HttpClient client = HttpClient.create().wiretap(true).secure((spec) -> spec.sslContext(sslContextSpec)); return new ReactorClientHttpConnector(client); } @@ -234,12 +251,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { clientKeyStore.load(stream, "secret".toCharArray()); } KeyManagerFactory clientKeyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); clientKeyManagerFactory.init(clientKeyStore, keyStorePassword.toCharArray()); Http11SslContextSpec sslContextSpec = Http11SslContextSpec.forClient() - .configure((builder) -> builder.sslProvider(SslProvider.JDK) - .trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(clientKeyManagerFactory)); + .configure((builder) -> builder.sslProvider(SslProvider.JDK) + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .keyManager(clientKeyManagerFactory)); HttpClient client = HttpClient.create().wiretap(true).secure((spec) -> spec.sslContext(sslContextSpec)); return new ReactorClientHttpConnector(client); } @@ -249,10 +267,16 @@ public abstract class AbstractReactiveWebServerFactoryTests { factory.setSsl(sslConfiguration); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(clientConnector).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(clientConnector) + .build(); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); } @@ -293,10 +317,16 @@ public abstract class AbstractReactiveWebServerFactoryTests { factory.setSsl(sslConfiguration); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - WebClient client = WebClient.builder().baseUrl("https://localhost:" + this.webServer.getPort()) - .clientConnector(clientConnector).build(); - Mono result = client.post().uri("/test").contentType(MediaType.TEXT_PLAIN) - .body(BodyInserters.fromValue("Hello World")).retrieve().bodyToMono(String.class); + WebClient client = WebClient.builder() + .baseUrl("https://localhost:" + this.webServer.getPort()) + .clientConnector(clientConnector) + .build(); + Mono result = client.post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); StepVerifier.create(result).expectError(WebClientRequestException.class).verify(Duration.ofSeconds(10)); } @@ -350,8 +380,11 @@ public abstract class AbstractReactiveWebServerFactoryTests { compression.setEnabled(true); compression.setExcludedUserAgents(new String[] { "testUserAgent" }); WebClient client = prepareCompressionTest(compression); - ResponseEntity response = client.get().header("User-Agent", "testUserAgent").retrieve().toBodilessEntity() - .block(Duration.ofSeconds(30)); + ResponseEntity response = client.get() + .header("User-Agent", "testUserAgent") + .retrieve() + .toBodilessEntity() + .block(Duration.ofSeconds(30)); assertResponseIsNotCompressed(response); } @@ -368,7 +401,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { @Test void whenSslIsEnabledAndNoKeyStoreIsConfiguredThenServerFailsToStart() { assertThatThrownBy(() -> testBasicSslWithKeyStore(null, null)) - .hasMessageContaining("Could not load key store 'null'"); + .hasMessageContaining("Could not load key store 'null'"); } @Test @@ -390,8 +423,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -415,8 +450,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -434,8 +471,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { // Continue } System.out.println("Stopped"); - Awaitility.await().atMost(Duration.ofSeconds(5)) - .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); + Awaitility.await() + .atMost(Duration.ofSeconds(5)) + .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); blockingHandler.completeOne(); } @@ -446,8 +484,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -458,8 +498,9 @@ public abstract class AbstractReactiveWebServerFactoryTests { AtomicReference result = new AtomicReference<>(); this.webServer.shutDownGracefully(result::set); this.webServer.stop(); - Awaitility.await().atMost(Duration.ofSeconds(30)) - .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .until(() -> GracefulShutdownResult.REQUESTS_ACTIVE == result.get()); blockingHandler.completeOne(); } @@ -469,8 +510,10 @@ public abstract class AbstractReactiveWebServerFactoryTests { BlockingHandler blockingHandler = new BlockingHandler(); this.webServer = factory.getWebServer(blockingHandler); this.webServer.start(); - Mono> request = getWebClient(this.webServer.getPort()).build().get().retrieve() - .toBodilessEntity(); + Mono> request = getWebClient(this.webServer.getPort()).build() + .get() + .retrieve() + .toBodilessEntity(); AtomicReference> responseReference = new AtomicReference<>(); CountDownLatch responseLatch = new CountDownLatch(1); request.subscribe((response) -> { @@ -500,7 +543,8 @@ public abstract class AbstractReactiveWebServerFactoryTests { client.start(); try { ContentResponse response = client.POST("http://localhost:" + this.webServer.getPort()) - .body(new StringRequestContent("text/plain", "Hello World")).send(); + .body(new StringRequestContent("text/plain", "Hello World")) + .send(); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(response.getContentAsString()).isEqualTo("Hello World"); } @@ -517,9 +561,13 @@ public abstract class AbstractReactiveWebServerFactoryTests { factory.setHttp2(http2); this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); - Mono result = getWebClient(this.webServer.getPort()).build().post().uri("/test") - .contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromValue("Hello World")).retrieve() - .bodyToMono(String.class); + Mono result = getWebClient(this.webServer.getPort()).build() + .post() + .uri("/test") + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromValue("Hello World")) + .retrieve() + .bodyToMono(String.class); assertThat(result.block(Duration.ofSeconds(30))).isEqualTo("Hello World"); } @@ -539,9 +587,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { this.webServer = factory.getWebServer(new CharsHandler(3000, responseContentType)); this.webServer.start(); - HttpClient client = HttpClient.create().wiretap(true).compress(true) - .doOnConnected((connection) -> connection.channel().pipeline().addBefore(NettyPipeline.HttpDecompressor, - "CompressionTest", new CompressionDetectionHandler())); + HttpClient client = HttpClient.create() + .wiretap(true) + .compress(true) + .doOnConnected((connection) -> connection.channel() + .pipeline() + .addBefore(NettyPipeline.HttpDecompressor, "CompressionTest", new CompressionDetectionHandler())); return getWebClient(client, this.webServer.getPort()).build(); } @@ -558,8 +609,12 @@ public abstract class AbstractReactiveWebServerFactoryTests { protected void assertForwardHeaderIsUsed(AbstractReactiveWebServerFactory factory) { this.webServer = factory.getWebServer(new XForwardedHandler()); this.webServer.start(); - String body = getWebClient(this.webServer.getPort()).build().get().header("X-Forwarded-Proto", "https") - .retrieve().bodyToMono(String.class).block(Duration.ofSeconds(30)); + String body = getWebClient(this.webServer.getPort()).build() + .get() + .header("X-Forwarded-Proto", "https") + .retrieve() + .bodyToMono(String.class) + .block(Duration.ofSeconds(30)); assertThat(body).isEqualTo("https"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java index 1130e995cd..1455b4db88 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/CertificateParserTests.java @@ -51,7 +51,7 @@ class CertificateParserTests { void parseWithInvalidPathWillThrowException() { String path = "file:///bad/path/cert.pem"; assertThatIllegalStateException().isThrownBy(() -> CertificateParser.parse("file:///bad/path/cert.pem")) - .withMessageContaining(path); + .withMessageContaining(path); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java index aae9ebcbe9..7cb5e324a8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/MimeMappingsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ class MimeMappingsTests { @Test void defaultsCannotBeModified() { assertThatExceptionOfType(UnsupportedOperationException.class) - .isThrownBy(() -> MimeMappings.DEFAULT.add("foo", "foo/bar")); + .isThrownBy(() -> MimeMappings.DEFAULT.add("foo", "foo/bar")); } @Test @@ -218,9 +218,9 @@ class MimeMappingsTests { @Test void mimeMappingsMatchesTomcatDefaults() throws IOException { Properties ourDefaultMimeMappings = PropertiesLoaderUtils - .loadProperties(new ClassPathResource("mime-mappings.properties", getClass())); + .loadProperties(new ClassPathResource("mime-mappings.properties", getClass())); Properties tomcatDefaultMimeMappings = PropertiesLoaderUtils - .loadProperties(new ClassPathResource("MimeTypeMappings.properties", Tomcat.class)); + .loadProperties(new ClassPathResource("MimeTypeMappings.properties", Tomcat.class)); assertThat(ourDefaultMimeMappings).isEqualTo(tomcatDefaultMimeMappings); } @@ -229,7 +229,7 @@ class MimeMappingsTests { RuntimeHints runtimeHints = new RuntimeHints(); new MimeMappingsRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.resource() - .forResource("org/springframework/boot/web/server/mime-mappings.properties")).accepts(runtimeHints); + .forResource("org/springframework/boot/web/server/mime-mappings.properties")).accepts(runtimeHints); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java index 31a5474803..390fb1b2b6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/PrivateKeyParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ class PrivateKeyParserTests { void parseWithNonKeyFileWillThrowException() { String path = "classpath:test-banner.txt"; assertThatIllegalStateException().isThrownBy(() -> PrivateKeyParser.parse("file://" + path)) - .withMessageContaining(path); + .withMessageContaining(path); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java index aef81cb9ca..95672ce2d9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/SslConfigurationValidatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -66,16 +66,16 @@ class SslConfigurationValidatorTests { @Test void validateKeyAliasWhenAliasNotFoundShouldThrowException() { assertThatThrownBy(() -> SslConfigurationValidator.validateKeyAlias(this.keyStore, INVALID_ALIAS)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Keystore does not contain specified alias '" + INVALID_ALIAS + "'"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Keystore does not contain specified alias '" + INVALID_ALIAS + "'"); } @Test void validateKeyAliasWhenKeyStoreThrowsExceptionOnContains() throws KeyStoreException { KeyStore uninitializedKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); assertThatThrownBy(() -> SslConfigurationValidator.validateKeyAlias(uninitializedKeyStore, "alias")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Could not determine if keystore contains alias 'alias'"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Could not determine if keystore contains alias 'alias'"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java index 76c36b1e78..0b35d88e61 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,8 +56,7 @@ class WebServerFactoryCustomizerBeanPostProcessorTests { @Test void setBeanFactoryWhenNotListableShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.processor.setBeanFactory(mock(BeanFactory.class))) - .withMessageContaining( - "WebServerCustomizerBeanPostProcessor can only be used with a ListableBeanFactory"); + .withMessageContaining("WebServerCustomizerBeanPostProcessor can only be used with a ListableBeanFactory"); } @Test @@ -153,7 +152,7 @@ class WebServerFactoryCustomizerBeanPostProcessorTests { @SuppressWarnings({ "unchecked", "rawtypes" }) private void addMockBeans(Map beans) { given(this.beanFactory.getBeansOfType(WebServerFactoryCustomizer.class, false, false)) - .willReturn((Map) beans); + .willReturn((Map) beans); } private void postProcessBeforeInitialization(Class type) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java index 16f0ece123..24823c913b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -86,10 +86,10 @@ abstract class AbstractFilterRegistrationBeanTests { expectedInitParameters.put("a", "b"); expectedInitParameters.put("c", "d"); then(this.registration).should().setInitParameters(expectedInitParameters); - then(this.registration).should().addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/a", "/b", - "/c"); - then(this.registration).should().addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "s4", "s5", - "s1", "s2", "s3"); + then(this.registration).should() + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/a", "/b", "/c"); + then(this.registration).should() + .addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "s4", "s5", "s1", "s2", "s3"); } @Test @@ -119,15 +119,15 @@ abstract class AbstractFilterRegistrationBeanTests { void setServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletRegistrationBeans(null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test void addServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException() - .isThrownBy(() -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .isThrownBy(() -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test @@ -154,28 +154,28 @@ abstract class AbstractFilterRegistrationBeanTests { void setUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlPatterns(null)) - .withMessageContaining("UrlPatterns must not be null"); + .withMessageContaining("UrlPatterns must not be null"); } @Test void addUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlPatterns((String[]) null)) - .withMessageContaining("UrlPatterns must not be null"); + .withMessageContaining("UrlPatterns must not be null"); } @Test void setServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletNames(null)) - .withMessageContaining("ServletNames must not be null"); + .withMessageContaining("ServletNames must not be null"); } @Test void addServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); assertThatIllegalArgumentException().isThrownBy(() -> bean.addServletNames((String[]) null)) - .withMessageContaining("ServletNames must not be null"); + .withMessageContaining("ServletNames must not be null"); } @Test @@ -185,7 +185,7 @@ abstract class AbstractFilterRegistrationBeanTests { bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD); bean.onStartup(this.servletContext); then(this.registration).should() - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), false, "/*"); + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), false, "/*"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java index 25e6ded7c0..c165c4db1a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,13 +51,13 @@ class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrat @Test void targetBeanNameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean(null)) - .withMessageContaining("TargetBeanName must not be null or empty"); + .withMessageContaining("TargetBeanName must not be null or empty"); } @Test void targetBeanNameMustNotBeEmpty() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("")) - .withMessageContaining("TargetBeanName must not be null or empty"); + .withMessageContaining("TargetBeanName must not be null or empty"); } @Test @@ -88,9 +88,8 @@ class DelegatingFilterProxyRegistrationBeanTests extends AbstractFilterRegistrat @Test void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy( - () -> new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("mockFilter", (ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java index 78eaea6ff6..fac7646c35 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,20 +68,20 @@ class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanTests { void setFilterMustNotBeNull() { FilterRegistrationBean bean = new FilterRegistrationBean<>(); assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) - .withMessageContaining("Filter must not be null"); + .withMessageContaining("Filter must not be null"); } @Test void constructFilterMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new FilterRegistrationBean<>(null)) - .withMessageContaining("Filter must not be null"); + .withMessageContaining("Filter must not be null"); } @Test void createServletRegistrationBeanMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, (ServletRegistrationBean[]) null)) - .withMessageContaining("ServletRegistrationBeans must not be null"); + .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, (ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java index a19452c8d2..8f3b41b0ac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ class ServletComponentScanRegistrarTests { void packagesConfiguredWithValue() { this.context = new AnnotationConfigApplicationContext(ValuePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @@ -57,7 +57,7 @@ class ServletComponentScanRegistrarTests { this.context.registerBeanDefinition("valuePackages", new RootBeanDefinition(ValuePackages.class.getName())); this.context.refresh(); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @@ -65,7 +65,7 @@ class ServletComponentScanRegistrarTests { void packagesConfiguredWithBackPackages() { this.context = new AnnotationConfigApplicationContext(BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar"); } @@ -73,23 +73,25 @@ class ServletComponentScanRegistrarTests { void packagesConfiguredWithBasePackageClasses() { this.context = new AnnotationConfigApplicationContext(BasePackageClasses.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains(getClass().getPackage().getName()); } @Test void packagesConfiguredWithBothValueAndBasePackages() { assertThatExceptionOfType(AnnotationConfigurationException.class) - .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class)) - .withMessageContaining("'value'").withMessageContaining("'basePackages'") - .withMessageContaining("com.example.foo").withMessageContaining("com.example.bar"); + .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class)) + .withMessageContaining("'value'") + .withMessageContaining("'basePackages'") + .withMessageContaining("com.example.foo") + .withMessageContaining("com.example.bar"); } @Test void packagesFromMultipleAnnotationsAreMerged() { this.context = new AnnotationConfigApplicationContext(BasePackages.class, AdditionalPackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).contains("com.example.foo", "com.example.bar", "com.example.baz"); } @@ -97,7 +99,7 @@ class ServletComponentScanRegistrarTests { void withNoBasePackagesScanningUsesBasePackageOfAnnotatedClass() { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).containsExactly("org.springframework.boot.web.servlet"); } @@ -105,7 +107,7 @@ class ServletComponentScanRegistrarTests { void noBasePackageAndBasePackageAreCombinedCorrectly() { this.context = new AnnotationConfigApplicationContext(NoBasePackages.class, BasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", "com.example.foo", "com.example.bar"); } @@ -114,7 +116,7 @@ class ServletComponentScanRegistrarTests { void basePackageAndNoBasePackageAreCombinedCorrectly() { this.context = new AnnotationConfigApplicationContext(BasePackages.class, NoBasePackages.class); ServletComponentRegisteringPostProcessor postProcessor = this.context - .getBean(ServletComponentRegisteringPostProcessor.class); + .getBean(ServletComponentRegisteringPostProcessor.class); assertThat(postProcessor.getPackagesToScan()).containsExactlyInAnyOrder("org.springframework.boot.web.servlet", "com.example.foo", "com.example.bar"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java index c67471e158..2f8272265c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletContextInitializerBeansTests.java @@ -76,9 +76,10 @@ class ServletContextInitializerBeansTests { ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans( this.context.getBeanFactory()); assertThat(initializerBeans).hasSize(1); - assertThat(initializerBeans).first().isInstanceOf(ServletListenerRegistrationBean.class) - .extracting((initializer) -> ((ServletListenerRegistrationBean) initializer).getListener()) - .isInstanceOf(HttpSessionIdListener.class); + assertThat(initializerBeans).first() + .isInstanceOf(ServletListenerRegistrationBean.class) + .extracting((initializer) -> ((ServletListenerRegistrationBean) initializer).getListener()) + .isInstanceOf(HttpSessionIdListener.class); } private void load(Class... configuration) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java index ca98c26fdd..a8d3d2acdd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -64,9 +64,10 @@ class ServletListenerRegistrationBeanTests { @Test void cannotRegisterUnsupportedType() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ServletListenerRegistrationBean<>(new EventListener() { + .isThrownBy(() -> new ServletListenerRegistrationBean<>(new EventListener() { - })).withMessageContaining("Listener is not of a supported type"); + })) + .withMessageContaining("Listener is not of a supported type"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java index a3a98ff62d..74bf5531be 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -131,34 +131,34 @@ class ServletRegistrationBeanTests { void setServletMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(); assertThatIllegalArgumentException().isThrownBy(() -> bean.onStartup(this.servletContext)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test void createServletMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new ServletRegistrationBean(null)) - .withMessageContaining("Servlet must not be null"); + .withMessageContaining("Servlet must not be null"); } @Test void setMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlMappings(null)) - .withMessageContaining("UrlMappings must not be null"); + .withMessageContaining("UrlMappings must not be null"); } @Test void createMappingMustNotBeNull() { assertThatIllegalArgumentException() - .isThrownBy(() -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) - .withMessageContaining("UrlMappings must not be null"); + .isThrownBy(() -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) + .withMessageContaining("UrlMappings must not be null"); } @Test void addMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>(this.servlet); assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlMappings((String[]) null)) - .withMessageContaining("UrlMappings must not be null"); + .withMessageContaining("UrlMappings must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java index 96a93a5515..7661634cd1 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,11 +59,11 @@ class WebFilterHandlerTests { AnnotatedBeanDefinition definition = createBeanDefinition(DefaultConfigurationFilter.class); this.handler.handle(definition, this.registry); BeanDefinition filterRegistrationBean = this.registry - .getBeanDefinition(DefaultConfigurationFilter.class.getName()); + .getBeanDefinition(DefaultConfigurationFilter.class.getName()); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat((EnumSet) propertyValues.get("dispatcherTypes")) - .containsExactly(DispatcherType.REQUEST); + .containsExactly(DispatcherType.REQUEST); assertThat(((Map) propertyValues.get("initParameters"))).isEmpty(); assertThat((String[]) propertyValues.get("servletNames")).isEmpty(); assertThat((String[]) propertyValues.get("urlPatterns")).isEmpty(); @@ -102,7 +102,7 @@ class WebFilterHandlerTests { BeanDefinition filterRegistrationBean = handleBeanDefinitionForClass(InitParametersFilter.class); MutablePropertyValues propertyValues = filterRegistrationBean.getPropertyValues(); assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") - .containsEntry("b", "bravo"); + .containsEntry("b", "bravo"); } @Test @@ -129,8 +129,8 @@ class WebFilterHandlerTests { @Test void urlPatternsDeclaredTwice() { assertThatIllegalStateException() - .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceFilter.class)) - .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); + .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceFilter.class)) + .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } private AnnotatedBeanDefinition createBeanDefinition(Class filterClass) throws IOException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java index 766eae86e3..02d1b15ef3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebListenerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,9 @@ class WebListenerHandlerTests { void listener() throws IOException { AnnotatedBeanDefinition definition = mock(AnnotatedBeanDefinition.class); given(definition.getBeanClassName()).willReturn(TestListener.class.getName()); - given(definition.getMetadata()).willReturn(new SimpleMetadataReaderFactory() - .getMetadataReader(TestListener.class.getName()).getAnnotationMetadata()); + given(definition.getMetadata()) + .willReturn(new SimpleMetadataReaderFactory().getMetadataReader(TestListener.class.getName()) + .getAnnotationMetadata()); this.handler.handle(definition, this.registry); this.registry.getBeanDefinition(TestListener.class.getName() + "Registrar"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java index cbcb71c11b..660713a5e3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -52,7 +52,7 @@ class WebServletHandlerTests { AnnotatedBeanDefinition servletDefinition = createBeanDefinition(DefaultConfigurationServlet.class); this.handler.handle(servletDefinition, this.registry); BeanDefinition servletRegistrationBean = this.registry - .getBeanDefinition(DefaultConfigurationServlet.class.getName()); + .getBeanDefinition(DefaultConfigurationServlet.class.getName()); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat(propertyValues.get("asyncSupported")).isEqualTo(false); assertThat(((Map) propertyValues.get("initParameters"))).isEmpty(); @@ -84,7 +84,7 @@ class WebServletHandlerTests { BeanDefinition servletRegistrationBean = handleBeanDefinitionForClass(InitParametersServlet.class); MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues(); assertThat((Map) propertyValues.get("initParameters")).containsEntry("a", "alpha") - .containsEntry("b", "bravo"); + .containsEntry("b", "bravo"); } @Test @@ -104,8 +104,8 @@ class WebServletHandlerTests { @Test void urlPatternsDeclaredTwice() { assertThatIllegalStateException() - .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceServlet.class)) - .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); + .isThrownBy(() -> handleBeanDefinitionForClass(UrlPatternsDeclaredTwiceServlet.class)) + .withMessageContaining("The urlPatterns and value attributes are mutually exclusive."); } private AnnotatedBeanDefinition createBeanDefinition(Class servletClass) throws IOException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java index caef4cd7a4..1cd3c0f654 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java @@ -113,10 +113,10 @@ class ServletWebServerApplicationContextTests { // Ensure that the context has been set up assertThat(this.context.getServletContext()).isEqualTo(factory.getServletContext()); then(factory.getServletContext()).should() - .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); + .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); // Ensure WebApplicationContextUtils.registerWebApplicationScopes was called assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_SESSION)) - .isInstanceOf(SessionScope.class); + .isInstanceOf(SessionScope.class); // Ensure WebApplicationContextUtils.registerEnvironmentBeans was called assertThat(this.context.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)).isTrue(); } @@ -137,8 +137,9 @@ class ServletWebServerApplicationContextTests { this.context.registerBeanDefinition("listener", new RootBeanDefinition(TestApplicationListener.class)); this.context.refresh(); List events = this.context.getBean(TestApplicationListener.class).receivedEvents(); - assertThat(events).hasSize(2).extracting("class").containsExactly(ServletWebServerInitializedEvent.class, - ContextRefreshedEvent.class); + assertThat(events).hasSize(2) + .extracting("class") + .containsExactly(ServletWebServerInitializedEvent.class, ContextRefreshedEvent.class); ServletWebServerInitializedEvent initializedEvent = (ServletWebServerInitializedEvent) events.get(0); assertThat(initializedEvent.getSource().getPort()).isGreaterThanOrEqualTo(0); assertThat(initializedEvent.getApplicationContext()).isEqualTo(this.context); @@ -170,8 +171,9 @@ class ServletWebServerApplicationContextTests { this.context.refresh(); this.context.addApplicationListener(listener); this.context.close(); - assertThat(listener.receivedEvents()).hasSize(2).extracting("class").contains(AvailabilityChangeEvent.class, - ContextClosedEvent.class); + assertThat(listener.receivedEvents()).hasSize(2) + .extracting("class") + .contains(AvailabilityChangeEvent.class, ContextClosedEvent.class); } @Test @@ -204,9 +206,9 @@ class ServletWebServerApplicationContextTests { @Test void missingServletWebServerFactory() { assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .havingRootCause() - .withMessageContaining("Unable to start ServletWebServerApplicationContext due to missing " - + "ServletWebServerFactory bean"); + .havingRootCause() + .withMessageContaining("Unable to start ServletWebServerApplicationContext due to missing " + + "ServletWebServerFactory bean"); } @Test @@ -215,8 +217,9 @@ class ServletWebServerApplicationContextTests { this.context.registerBeanDefinition("webServerFactory2", new RootBeanDefinition(MockServletWebServerFactory.class)); assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> this.context.refresh()) - .havingRootCause().withMessageContaining("Unable to start ServletWebServerApplicationContext due to " - + "multiple ServletWebServerFactory beans"); + .havingRootCause() + .withMessageContaining("Unable to start ServletWebServerApplicationContext due to " + + "multiple ServletWebServerFactory beans"); } @@ -305,9 +308,9 @@ class ServletWebServerApplicationContextTests { then(factory.getServletContext()).should(ordered).addFilter("filterBean1", filter1); then(factory.getServletContext()).should(ordered).addFilter("filterBean2", filter2); then(factory.getRegisteredFilter(0).getRegistration()).should() - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); then(factory.getRegisteredFilter(1).getRegistration()).should() - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); } @Test @@ -409,8 +412,8 @@ class ServletWebServerApplicationContextTests { // the delegate proxy will trigger creation and an exception assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> { this.filterCaptor.getValue().init(new MockFilterConfig()); - this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), - new MockFilterChain()); + this.filterCaptor.getValue() + .doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain()); }).withMessageContaining("Create FilterBean Failure"); } @@ -464,7 +467,7 @@ class ServletWebServerApplicationContextTests { addWebServerFactoryBean(); this.context.refresh(); assertThat(this.context.getBeanFactory().getRegisteredScope(WebApplicationContext.SCOPE_APPLICATION)) - .isNotNull(); + .isNotNull(); } private void addWebServerFactoryBean() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java index 4406eb0b8d..e8496ade45 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/XmlServletWebServerApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -31,8 +31,9 @@ import static org.mockito.BDDMockito.then; */ class XmlServletWebServerApplicationContextTests { - private static final String PATH = XmlServletWebServerApplicationContextTests.class.getPackage().getName() - .replace('.', '/') + "/"; + private static final String PATH = XmlServletWebServerApplicationContextTests.class.getPackage() + .getName() + .replace('.', '/') + "/"; private static final String FILE = "exampleEmbeddedWebApplicationConfiguration.xml"; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java index 0f6414fca0..71405232b6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/error/DefaultErrorAttributesTests.java @@ -89,7 +89,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(ex); + .isSameAs(ex); assertThat(modelAndView).isNull(); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes).containsEntry("message", "Test"); @@ -103,7 +103,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(ex); + .isSameAs(ex); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes).containsEntry("message", "Test"); } @@ -116,7 +116,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.defaults()); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(ex); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(ex); + .isSameAs(ex); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes).doesNotContainKey("message"); } @@ -167,7 +167,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(wrapped); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(wrapped); + .isSameAs(wrapped); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes).containsEntry("message", "Test"); } @@ -180,7 +180,7 @@ class DefaultErrorAttributesTests { ErrorAttributeOptions.of(Include.MESSAGE)); assertThat(this.errorAttributes.getError(this.webRequest)).isSameAs(error); assertThat(this.webRequest.getAttribute(ErrorAttributes.ERROR_ATTRIBUTE, WebRequest.SCOPE_REQUEST)) - .isSameAs(error); + .isSameAs(error); assertThat(attributes).doesNotContainKey("exception"); assertThat(attributes).containsEntry("message", "Test error"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java index d2ef917e9a..82140ebe1d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java @@ -182,7 +182,7 @@ public abstract class AbstractServletWebServerFactoryTests { private final HttpClientContext httpClientContext = HttpClientContext.create(); private final Supplier httpClientBuilder = () -> HttpClients.custom() - .setRetryStrategy(new DefaultHttpRequestRetryStrategy(10, TimeValue.of(200, TimeUnit.MILLISECONDS))); + .setRetryStrategy(new DefaultHttpRequestRetryStrategy(10, TimeValue.of(200, TimeUnit.MILLISECONDS))); @AfterEach void tearDown() { @@ -279,7 +279,7 @@ public abstract class AbstractServletWebServerFactoryTests { AbstractServletWebServerFactory factory = getFactory(); final InitCountingServlet servlet = new InitCountingServlet(); this.webServer = factory - .getWebServer((servletContext) -> servletContext.addServlet("test", servlet).setLoadOnStartup(1)); + .getWebServer((servletContext) -> servletContext.addServlet("test", servlet).setLoadOnStartup(1)); assertThat(servlet.getInitCount()).isZero(); this.webServer.start(); assertThat(servlet.getInitCount()).isOne(); @@ -329,19 +329,19 @@ public abstract class AbstractServletWebServerFactoryTests { @Test void contextPathMustStartWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("missingslash")) - .withMessageContaining("ContextPath must start with '/' and not end with '/'"); + .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test void contextPathMustNotEndWithSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("extraslash/")) - .withMessageContaining("ContextPath must start with '/' and not end with '/'"); + .withMessageContaining("ContextPath must start with '/' and not end with '/'"); } @Test void contextRootPathMustNotBeSlash() { assertThatIllegalArgumentException().isThrownBy(() -> getFactory().setContextPath("/")) - .withMessageContaining("Root ContextPath must be specified using an empty string"); + .withMessageContaining("Root ContextPath must be specified using an empty string"); } @Test @@ -426,7 +426,7 @@ public abstract class AbstractServletWebServerFactoryTests { new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpComponentsClientHttpRequestFactory requestFactory = createHttpComponentsRequestFactory(socketFactory); assertThatExceptionOfType(SSLException.class) - .isThrownBy(() -> getResponse(getLocalUrl("https", "/hello"), requestFactory)); + .isThrownBy(() -> getResponse(getLocalUrl("https", "/hello"), requestFactory)); } @Test @@ -453,7 +453,8 @@ public abstract class AbstractServletWebServerFactoryTests { TrustStrategy trustStrategy = new SerialNumberValidatingTrustSelfSignedStrategy("3a3aaec8"); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(); PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create() - .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)).build(); + .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) + .build(); HttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); String response = getResponse(getLocalUrl("https", "/hello"), new HttpComponentsClientHttpRequestFactory(httpClient)); @@ -484,7 +485,8 @@ public abstract class AbstractServletWebServerFactoryTests { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create() - .setSSLSocketFactory(socketFactory).build(); + .setSSLSocketFactory(socketFactory) + .build(); HttpClient httpClient = this.httpClientBuilder.get().setConnectionManager(connectionManager).build(); ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient)); @@ -501,7 +503,8 @@ public abstract class AbstractServletWebServerFactoryTests { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create() - .setSSLSocketFactory(socketFactory).build(); + .setSSLSocketFactory(socketFactory) + .build(); HttpClient httpClient = this.httpClientBuilder.get().setConnectionManager(connectionManager).build(); ClientHttpResponse response = getClientResponse(getLocalUrl("https", "/hello"), HttpMethod.GET, new HttpComponentsClientHttpRequestFactory(httpClient)); @@ -531,7 +534,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.p12")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "secret".toCharArray()).build()); + .loadKeyMaterial(keyStore, "secret".toCharArray()) + .build()); HttpComponentsClientHttpRequestFactory requestFactory = createHttpComponentsRequestFactory(socketFactory); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @@ -547,7 +551,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.p12")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "secret".toCharArray()).build()); + .loadKeyMaterial(keyStore, "secret".toCharArray()) + .build()); HttpComponentsClientHttpRequestFactory requestFactory = createHttpComponentsRequestFactory(socketFactory); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @@ -564,7 +569,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.jks")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray()).build()); + .loadKeyMaterial(keyStore, "password".toCharArray()) + .build()); HttpComponentsClientHttpRequestFactory requestFactory = createHttpComponentsRequestFactory(socketFactory); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @@ -587,15 +593,16 @@ public abstract class AbstractServletWebServerFactoryTests { void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractServletWebServerFactory factory = getFactory(); addTestTxtFile(factory); - factory.setSsl( - getSsl(ClientAuth.WANT, "password", "classpath:test.jks", null, new String[] { "TLSv1.2" }, null)); + factory + .setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks", null, new String[] { "TLSv1.2" }, null)); this.webServer = factory.getWebServer(); this.webServer.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); loadStore(keyStore, new FileSystemResource("src/test/resources/test.jks")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray()).build()); + .loadKeyMaterial(keyStore, "password".toCharArray()) + .build()); HttpComponentsClientHttpRequestFactory requestFactory = createHttpComponentsRequestFactory(socketFactory); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); } @@ -631,7 +638,8 @@ public abstract class AbstractServletWebServerFactoryTests { loadStore(keyStore, new FileSystemResource("src/test/resources/test.jks")); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .loadKeyMaterial(keyStore, "password".toCharArray()).build()); + .loadKeyMaterial(keyStore, "password".toCharArray()) + .build()); HttpComponentsClientHttpRequestFactory requestFactory = createHttpComponentsRequestFactory(socketFactory); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test"); then(sslStoreProvider).should(atLeastOnce()).getKeyStore(); @@ -721,7 +729,8 @@ public abstract class AbstractServletWebServerFactoryTests { private HttpComponentsClientHttpRequestFactory createHttpComponentsRequestFactory( SSLConnectionSocketFactory socketFactory) { PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create() - .setSSLSocketFactory(socketFactory).build(); + .setSSLSocketFactory(socketFactory) + .build(); HttpClient httpClient = this.httpClientBuilder.get().setConnectionManager(connectionManager).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return requestFactory; @@ -792,7 +801,7 @@ public abstract class AbstractServletWebServerFactoryTests { file.createNewFile(); factory.getSession().setStoreDir(file); assertThatIllegalStateException().isThrownBy(() -> factory.getValidSessionStoreDir(false)) - .withMessageContaining("points to a file"); + .withMessageContaining("points to a file"); } @Test @@ -883,7 +892,7 @@ public abstract class AbstractServletWebServerFactoryTests { AtomicReference contextReference = new AtomicReference<>(); this.webServer = factory.getWebServer(contextReference::set); assertThat(contextReference.get().getEffectiveSessionTrackingModes()) - .isEqualTo(EnumSet.of(jakarta.servlet.SessionTrackingMode.SSL)); + .isEqualTo(EnumSet.of(jakarta.servlet.SessionTrackingMode.SSL)); } @Test @@ -934,8 +943,8 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(); Map configuredMimeMappings = getActualMimeMappings(); Collection expectedMimeMappings = MimeMappings.DEFAULT.getAll(); - configuredMimeMappings.forEach( - (key, value) -> assertThat(expectedMimeMappings).contains(new MimeMappings.Mapping(key, value))); + configuredMimeMappings + .forEach((key, value) -> assertThat(expectedMimeMappings).contains(new MimeMappings.Mapping(key, value))); for (MimeMappings.Mapping mapping : expectedMimeMappings) { assertThat(configuredMimeMappings).containsEntry(mapping.getExtension(), mapping.getMimeType()); } @@ -1084,8 +1093,8 @@ public abstract class AbstractServletWebServerFactoryTests { AtomicReference contextReference = new AtomicReference<>(); factory.getWebServer(contextReference::set).start(); ServletContext servletContext = contextReference.get(); - assertThat(servletContext.getEffectiveSessionTrackingModes()).isEqualTo( - EnumSet.of(jakarta.servlet.SessionTrackingMode.COOKIE, jakarta.servlet.SessionTrackingMode.URL)); + assertThat(servletContext.getEffectiveSessionTrackingModes()) + .isEqualTo(EnumSet.of(jakarta.servlet.SessionTrackingMode.COOKIE, jakarta.servlet.SessionTrackingMode.URL)); assertThat(servletContext.getSessionCookieConfig().getName()).isEqualTo("testname"); assertThat(servletContext.getSessionCookieConfig().getDomain()).isEqualTo("testdomain"); assertThat(servletContext.getSessionCookieConfig().getPath()).isEqualTo("/testpath"); @@ -1110,9 +1119,9 @@ public abstract class AbstractServletWebServerFactoryTests { void exceptionThrownOnLoadFailureIsRethrown() { AbstractServletWebServerFactory factory = getFactory(); this.webServer = factory - .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); + .getWebServer((context) -> context.addServlet("failing", FailingServlet.class).setLoadOnStartup(0)); assertThatExceptionOfType(WebServerException.class).isThrownBy(this.webServer::start) - .satisfies(this::wrapsFailingServletException); + .satisfies(this::wrapsFailingServletException); } @Test @@ -1177,7 +1186,7 @@ public abstract class AbstractServletWebServerFactoryTests { AbstractServletWebServerFactory factory = getFactory(); BlockingServlet blockingServlet = new BlockingServlet(); this.webServer = factory - .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); + .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); this.webServer.start(); int port = this.webServer.getPort(); initiateGetRequest(port, "/"); @@ -1229,7 +1238,7 @@ public abstract class AbstractServletWebServerFactoryTests { factory.setShutdown(Shutdown.GRACEFUL); BlockingServlet blockingServlet = new BlockingServlet(); this.webServer = factory - .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); + .getWebServer((context) -> context.addServlet("blockingServlet", blockingServlet).addMapping("/")); this.webServer.start(); int port = this.webServer.getPort(); initiateGetRequest(port, "/"); @@ -1238,7 +1247,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.shutDownGracefully(result::set); this.webServer.stop(); assertThat(Awaitility.await().atMost(Duration.ofSeconds(30)).until(result::get, Objects::nonNull)) - .isEqualTo(GracefulShutdownResult.REQUESTS_ACTIVE); + .isEqualTo(GracefulShutdownResult.REQUESTS_ACTIVE); try { blockingServlet.admitOne(); } @@ -1298,8 +1307,10 @@ public abstract class AbstractServletWebServerFactoryTests { LinkedHashMap contentDecoderMap = new LinkedHashMap<>(); contentDecoderMap.put("gzip", inputStreamFactory); String response = getResponse(getLocalUrl("/test.txt"), method, - new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().setUserAgent("testUserAgent") - .setContentDecoderRegistry(contentDecoderMap).build())); + new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() + .setUserAgent("testUserAgent") + .setContentDecoderRegistry(contentDecoderMap) + .build())); assertThat(response).isEqualTo(testContent); return inputStreamFactory.wasCompressionUsed(); } @@ -1412,7 +1423,7 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); assertThat(getResponse(getLocalUrl("/hello"), "X-Forwarded-For:140.211.11.130")) - .contains("remoteaddr=140.211.11.130"); + .contains("remoteaddr=140.211.11.130"); } protected abstract AbstractServletWebServerFactory getFactory(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java index ca28af2c7b..fb48d1c138 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/CookieSameSiteSupplierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -39,14 +39,14 @@ class CookieSameSiteSupplierTests { void whenHasNameWhenNameIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasName((String) null)) - .withMessage("Name must not be empty"); + .withMessage("Name must not be empty"); } @Test void whenHasNameWhenNameIsEmptyThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasName("")) - .withMessage("Name must not be empty"); + .withMessage("Name must not be empty"); } @Test @@ -65,7 +65,7 @@ class CookieSameSiteSupplierTests { void whenHasSuppliedNameWhenNameIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasName((Supplier) null)) - .withMessage("NameSupplier must not be empty"); + .withMessage("NameSupplier must not be empty"); } @Test @@ -84,14 +84,14 @@ class CookieSameSiteSupplierTests { void whenHasNameMatchingRegexWhenRegexIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasNameMatching((String) null)) - .withMessage("Regex must not be empty"); + .withMessage("Regex must not be empty"); } @Test void whenHasNameMatchingRegexWhenRegexIsEmptyThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasNameMatching("")) - .withMessage("Regex must not be empty"); + .withMessage("Regex must not be empty"); } @Test @@ -110,14 +110,14 @@ class CookieSameSiteSupplierTests { void whenHasNameMatchingPatternWhenPatternIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.whenHasNameMatching((Pattern) null)) - .withMessage("Pattern must not be null"); + .withMessage("Pattern must not be null"); } @Test void whenHasNameMatchingPatternWhenNameMatchesCallsGetSameSite() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThat(supplier.whenHasNameMatching(Pattern.compile("te.*")).getSameSite(new Cookie("test", "x"))) - .isEqualTo(SameSite.LAX); + .isEqualTo(SameSite.LAX); } @Test @@ -130,21 +130,21 @@ class CookieSameSiteSupplierTests { void whenWhenPredicateIsNullThrowsException() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThatIllegalArgumentException().isThrownBy(() -> supplier.when(null)) - .withMessage("Predicate must not be null"); + .withMessage("Predicate must not be null"); } @Test void whenWhenPredicateMatchesCallsGetSameSite() { CookieSameSiteSupplier supplier = (cookie) -> SameSite.LAX; assertThat(supplier.when((cookie) -> cookie.getName().equals("test")).getSameSite(new Cookie("test", "x"))) - .isEqualTo(SameSite.LAX); + .isEqualTo(SameSite.LAX); } @Test void whenWhenPredicateDoesNotMatchDoesNotCallGetSameSite() { CookieSameSiteSupplier supplier = (cookie) -> fail("Supplier Called"); assertThat(supplier.when((cookie) -> cookie.getName().equals("test")).getSameSite(new Cookie("tset", "x"))) - .isNull(); + .isNull(); } @Test @@ -165,13 +165,13 @@ class CookieSameSiteSupplierTests { @Test void ofWhenNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> CookieSameSiteSupplier.of(null)) - .withMessage("SameSite must not be null"); + .withMessage("SameSite must not be null"); } @Test void ofSuppliesValue() { assertThat(CookieSameSiteSupplier.of(SameSite.STRICT).getSameSite(new Cookie("test", "x"))) - .isEqualTo(SameSite.STRICT); + .isEqualTo(SameSite.STRICT); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java index eed4ce0164..502af7db90 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/MockServletWebServerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -63,8 +63,9 @@ public class MockServletWebServerFactory extends AbstractServletWebServerFactory extends org.springframework.boot.testsupport.web.servlet.MockServletWebServer implements WebServer { MockServletWebServer(ServletContextInitializer[] initializers, int port) { - super(Arrays.stream(initializers).map((initializer) -> (Initializer) initializer::onStartup) - .toArray(Initializer[]::new), port); + super(Arrays.stream(initializers) + .map((initializer) -> (Initializer) initializer::onStartup) + .toArray(Initializer[]::new), port); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java index 5d29d21a34..65601ab149 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ErrorPageFilterTests.java @@ -91,7 +91,7 @@ class ErrorPageFilterTests { this.filter.doFilter(this.request, this.response, this.chain); assertThat(((HttpServletResponse) this.chain.getResponse()).getStatus()).isEqualTo(201); assertThat(((HttpServletResponse) ((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()) - .getStatus()).isEqualTo(201); + .getStatus()).isEqualTo(201); assertThat(this.response.isCommitted()).isTrue(); } @@ -397,12 +397,12 @@ class ErrorPageFilterTests { assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).isEqualTo(500); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_MESSAGE)) - .isEqualTo("Required request parameter 'test' for method parameter type string is not present"); + .isEqualTo("Required request parameter 'test' for method parameter type string is not present"); Map requestAttributes = getAttributesForDispatch("/500"); assertThat(requestAttributes).containsEntry(RequestDispatcher.ERROR_EXCEPTION_TYPE, MissingServletRequestParameterException.class); assertThat(requestAttributes.get(RequestDispatcher.ERROR_EXCEPTION)) - .isInstanceOf(MissingServletRequestParameterException.class); + .isInstanceOf(MissingServletRequestParameterException.class); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_EXCEPTION)).isNull(); assertThat(this.request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI)).isEqualTo("/test/path"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java index 2f93d4a898..1bb95e507d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/ServletContextApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,14 +47,14 @@ class ServletContextApplicationContextInitializerTests { void applicationContextIsNotStoredInServletContextByDefault() { new ServletContextApplicationContextInitializer(this.servletContext).initialize(this.applicationContext); then(this.servletContext).should(never()) - .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); + .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } @Test void applicationContextCanBeStoredInServletContext() { new ServletContextApplicationContextInitializer(this.servletContext, true).initialize(this.applicationContext); - then(this.servletContext).should().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - this.applicationContext); + then(this.servletContext).should() + .setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.applicationContext); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java index 84143d97c7..d3f77badfa 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java @@ -80,9 +80,8 @@ class SpringBootServletInitializerTests { @Test void failsWithoutConfigure() { assertThatIllegalStateException() - .isThrownBy( - () -> new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext)) - .withMessageContaining("No SpringApplication sources have been defined"); + .isThrownBy(() -> new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext)) + .withMessageContaining("No SpringApplication sources have been defined"); } @Test @@ -116,7 +115,7 @@ class SpringBootServletInitializerTests { void shutdownHooksAreNotRegistered() throws ServletException { new WithConfigurationAnnotation().onStartup(this.servletContext); assertThat(this.servletContext.getAttribute(LoggingApplicationListener.REGISTER_SHUTDOWN_HOOK_PROPERTY)) - .isEqualTo(false); + .isEqualTo(false); assertThat(this.application).hasFieldOrPropertyWithValue("registerShutdownHook", false); } @@ -124,7 +123,7 @@ class SpringBootServletInitializerTests { void errorPageFilterRegistrationCanBeDisabled() { WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { assertThat(context.getBeansOfType(ErrorPageFilter.class)).isEmpty(); } }); @@ -141,9 +140,9 @@ class SpringBootServletInitializerTests { void errorPageFilterIsRegisteredWithNearHighestPrecedence() { WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilter() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { Map registrations = context - .getBeansOfType(FilterRegistrationBean.class); + .getBeansOfType(FilterRegistrationBean.class); assertThat(registrations).hasSize(1); FilterRegistrationBean errorPageFilterRegistration = registrations.get("errorPageFilterRegistration"); assertThat(errorPageFilterRegistration.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE + 1); @@ -162,9 +161,9 @@ class SpringBootServletInitializerTests { void errorPageFilterIsRegisteredForRequestAndAsyncDispatch() { WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> { try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilter() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { Map registrations = context - .getBeansOfType(FilterRegistrationBean.class); + .getBeansOfType(FilterRegistrationBean.class); assertThat(registrations).hasSize(1); FilterRegistrationBean errorPageFilterRegistration = registrations.get("errorPageFilterRegistration"); assertThat(errorPageFilterRegistration).hasFieldOrPropertyWithValue("dispatcherTypes", @@ -190,11 +189,11 @@ class SpringBootServletInitializerTests { void servletContextPropertySourceIsAvailablePriorToRefresh() { ServletContext servletContext = mock(ServletContext.class); given(servletContext.getInitParameterNames()) - .willReturn(Collections.enumeration(Collections.singletonList("spring.profiles.active"))); + .willReturn(Collections.enumeration(Collections.singletonList("spring.profiles.active"))); given(servletContext.getInitParameter("spring.profiles.active")).willReturn("from-servlet-context"); given(servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration()); try (ConfigurableApplicationContext context = (ConfigurableApplicationContext) new PropertySourceVerifyingSpringBootServletInitializer() - .createRootApplicationContext(servletContext)) { + .createRootApplicationContext(servletContext)) { assertThat(context.getEnvironment().getActiveProfiles()).containsExactly("from-servlet-context"); } } @@ -324,8 +323,9 @@ class SpringBootServletInitializerTests { @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - PropertySource propertySource = event.getEnvironment().getPropertySources() - .get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); + PropertySource propertySource = event.getEnvironment() + .getPropertySources() + .get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME); assertThat(propertySource.getProperty("spring.profiles.active")).isEqualTo("from-servlet-context"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java index 824061f787..0047904791 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -34,8 +34,9 @@ public class TestListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { - sce.getServletContext().addFilter("listenerAddedFilter", new ListenerAddedFilter()) - .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); + sce.getServletContext() + .addFilter("listenerAddedFilter", new ListenerAddedFilter()) + .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); sce.getServletContext().setAttribute("listenerAttribute", "alpha"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java index 5405ed7389..d9c0844b99 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/testcomponents/TestServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -29,8 +29,9 @@ public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.getWriter().print(((String) req.getServletContext().getAttribute("listenerAttribute")) + " " - + req.getAttribute("filterAttribute") + " " + req.getAttribute("listenerAddedFilterAttribute")); + resp.getWriter() + .print(((String) req.getServletContext().getAttribute("listenerAttribute")) + " " + + req.getAttribute("filterAttribute") + " " + req.getAttribute("listenerAddedFilterAttribute")); resp.getWriter().flush(); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java index f1fa61aff5..e48feb9be0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,8 @@ class HttpWebServiceMessageSenderBuilderOkHttp3IntegrationTests { @Test void buildWithCustomTimeouts() { WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2)).build(); + .setReadTimeout(Duration.ofSeconds(2)) + .build(); OkHttp3ClientHttpRequestFactory factory = assertOkHttp3RequestFactory(messageSender); OkHttpClient client = (OkHttpClient) ReflectionTestUtils.getField(factory, "client"); assertThat(client).isNotNull(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java index f3632fbd07..2c3cb53748 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderSimpleIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,8 @@ class HttpWebServiceMessageSenderBuilderSimpleIntegrationTests { @Test void buildWithCustomTimeouts() { WebServiceMessageSender messageSender = this.builder.setConnectTimeout(Duration.ofSeconds(5)) - .setReadTimeout(Duration.ofSeconds(2)).build(); + .setReadTimeout(Duration.ofSeconds(2)) + .build(); SimpleClientHttpRequestFactory requestFactory = assertSimpleClientRequestFactory(messageSender); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 5000); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 2000); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java index 67380ed480..2b0b312590 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/HttpWebServiceMessageSenderBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,17 +48,19 @@ class HttpWebServiceMessageSenderBuilderTests { void buildWithReadAndConnectTimeout() { ClientHttpRequestMessageSender messageSender = build( new HttpWebServiceMessageSenderBuilder().requestFactory(SimpleClientHttpRequestFactory::new) - .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2))); + .setConnectTimeout(Duration.ofSeconds(5)) + .setReadTimeout(Duration.ofSeconds(2))); SimpleClientHttpRequestFactory requestFactory = (SimpleClientHttpRequestFactory) messageSender - .getRequestFactory(); + .getRequestFactory(); assertThat(requestFactory).hasFieldOrPropertyWithValue("connectTimeout", 5000); assertThat(requestFactory).hasFieldOrPropertyWithValue("readTimeout", 2000); } @Test void buildUsesHttpComponentsByDefault() { - ClientHttpRequestMessageSender messageSender = build(new HttpWebServiceMessageSenderBuilder() - .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(5))); + ClientHttpRequestMessageSender messageSender = build( + new HttpWebServiceMessageSenderBuilder().setConnectTimeout(Duration.ofSeconds(5)) + .setReadTimeout(Duration.ofSeconds(5))); ClientHttpRequestFactory requestFactory = messageSender.getRequestFactory(); assertThat(requestFactory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java index 550bc0f8c6..f6987ceb00 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -90,15 +90,15 @@ class WebServiceTemplateBuilderTests { @Test void messageSendersWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageSenders((WebServiceMessageSender[]) null)) - .withMessageContaining("MessageSenders must not be null"); + .isThrownBy(() -> this.builder.messageSenders((WebServiceMessageSender[]) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test void messageSendersCollectionWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.messageSenders((Collection) null)) - .withMessageContaining("MessageSenders must not be null"); + .isThrownBy(() -> this.builder.messageSenders((Collection) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test @@ -110,29 +110,32 @@ class WebServiceTemplateBuilderTests { @Test void messageSendersShouldReplaceExisting() { WebServiceTemplate template = this.builder.messageSenders(new ClientHttpRequestMessageSender()) - .messageSenders(this.messageSender).build(); + .messageSenders(this.messageSender) + .build(); assertThat(template.getMessageSenders()).containsOnly(this.messageSender); } @Test void additionalMessageSendersWhenSendersAreAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalMessageSenders((WebServiceMessageSender[]) null)) - .withMessageContaining("MessageSenders must not be null"); + .isThrownBy(() -> this.builder.additionalMessageSenders((WebServiceMessageSender[]) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test void additionalMessageSendersCollectionWhenSendersAreAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalMessageSenders((Collection) null)) - .withMessageContaining("MessageSenders must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.builder.additionalMessageSenders((Collection) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test void additionalMessageSendersShouldAddToExisting() { ClientHttpRequestMessageSender httpMessageSender = new ClientHttpRequestMessageSender(); WebServiceTemplate template = this.builder.messageSenders(httpMessageSender) - .additionalMessageSenders(this.messageSender).build(); + .additionalMessageSenders(this.messageSender) + .build(); assertThat(template.getMessageSenders()).containsOnly(httpMessageSender, this.messageSender); } @@ -146,14 +149,14 @@ class WebServiceTemplateBuilderTests { @Test void interceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.builder.interceptors((ClientInterceptor[]) null)) - .withMessageContaining("Interceptors must not be null"); + .withMessageContaining("Interceptors must not be null"); } @Test void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.interceptors((Collection) null)) - .withMessageContaining("Interceptors must not be null"); + .isThrownBy(() -> this.builder.interceptors((Collection) null)) + .withMessageContaining("Interceptors must not be null"); } @Test @@ -165,29 +168,31 @@ class WebServiceTemplateBuilderTests { @Test void interceptorsShouldReplaceExisting() { WebServiceTemplate template = this.builder.interceptors(mock(ClientInterceptor.class)) - .interceptors(Collections.singleton(this.interceptor)).build(); + .interceptors(Collections.singleton(this.interceptor)) + .build(); assertThat(template.getInterceptors()).containsOnly(this.interceptor); } @Test void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) - .withMessageContaining("Interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) + .withMessageContaining("Interceptors must not be null"); } @Test void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) - .withMessageContaining("Interceptors must not be null"); + .isThrownBy(() -> this.builder.additionalInterceptors((Set) null)) + .withMessageContaining("Interceptors must not be null"); } @Test void additionalInterceptorsShouldAddToExisting() { ClientInterceptor interceptor = mock(ClientInterceptor.class); - WebServiceTemplate template = this.builder.interceptors(interceptor).additionalInterceptors(this.interceptor) - .build(); + WebServiceTemplate template = this.builder.interceptors(interceptor) + .additionalInterceptors(this.interceptor) + .build(); assertThat(template.getInterceptors()).containsOnly(interceptor, this.interceptor); } @@ -204,15 +209,15 @@ class WebServiceTemplateBuilderTests { @Test void customizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void customizersCollectionWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.customizers((Collection) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.customizers((Collection) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -235,7 +240,8 @@ class WebServiceTemplateBuilderTests { WebServiceTemplateCustomizer customizer1 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplateCustomizer customizer2 = mock(WebServiceTemplateCustomizer.class); WebServiceTemplate template = this.builder.customizers(customizer1) - .customizers(Collections.singleton(customizer2)).build(); + .customizers(Collections.singleton(customizer2)) + .build(); then(customizer1).shouldHaveNoInteractions(); then(customizer2).should().customize(template); } @@ -243,15 +249,16 @@ class WebServiceTemplateBuilderTests { @Test void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.builder.additionalCustomizers((WebServiceTemplateCustomizer[]) null)) - .withMessageContaining("Customizers must not be null"); + .isThrownBy(() -> this.builder.additionalCustomizers((WebServiceTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.builder.additionalCustomizers((Collection) null)) - .withMessageContaining("Customizers must not be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.builder.additionalCustomizers((Collection) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java b/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java index 3dcedcd68c..d10861b833 100644 --- a/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java +++ b/spring-boot-system-tests/spring-boot-deployment-tests/src/systemTest/java/org/springframework/boot/deployment/AbstractDeploymentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -95,12 +95,11 @@ abstract class AbstractDeploymentTests { private void test(Consumer consumer) { TestRestTemplate rest = new TestRestTemplate(new RestTemplateBuilder() - .rootUri("http://" + this.container.getHost() + ":" + this.container.getMappedPort(this.port) - + "/spring-boot") - .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(HttpClients.custom() - .setRetryStrategy( - new DefaultHttpRequestRetryStrategy(10, TimeValue.of(1, TimeUnit.SECONDS))) - .build()))); + .rootUri("http://" + this.container.getHost() + ":" + this.container.getMappedPort(this.port) + + "/spring-boot") + .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(HttpClients.custom() + .setRetryStrategy(new DefaultHttpRequestRetryStrategy(10, TimeValue.of(1, TimeUnit.SECONDS))) + .build()))); try { Awaitility.await().atMost(Duration.ofMinutes(10)).until(() -> { try { @@ -124,8 +123,9 @@ abstract class AbstractDeploymentTests { WarDeploymentContainer(String baseImage, String deploymentLocation, int port) { super(new ImageFromDockerfile().withFileFromFile("spring-boot.war", findWarToDeploy()) - .withDockerfileFromBuilder((builder) -> builder.from(baseImage) - .add("spring-boot.war", deploymentLocation + "/spring-boot.war").build())); + .withDockerfileFromBuilder((builder) -> builder.from(baseImage) + .add("spring-boot.war", deploymentLocation + "/spring-boot.war") + .build())); withExposedPorts(port).withStartupTimeout(Duration.ofMinutes(5)).withStartupAttempts(3); } diff --git a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/assertions/ContainerConfigAssert.java b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/assertions/ContainerConfigAssert.java index fdd3eb5eba..6db0630252 100644 --- a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/assertions/ContainerConfigAssert.java +++ b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/assertions/ContainerConfigAssert.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -102,8 +102,10 @@ public class ContainerConfigAssert extends AbstractAssert, String, ObjectAssert> processOfType(String type) { - return this.actual.extractingJsonPathArrayValue("$.processes[?(@.type=='%s')]", type).singleElement() - .extracting("command", "args").flatExtracting((list) -> (List) list); + return this.actual.extractingJsonPathArrayValue("$.processes[?(@.type=='%s')]", type) + .singleElement() + .extracting("command", "args") + .flatExtracting((list) -> (List) list); } diff --git a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java index 4c5ed9edeb..489abd2b1e 100644 --- a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java +++ b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/LayersIndex.java @@ -38,8 +38,10 @@ import org.yaml.snakeyaml.constructor.Constructor; class LayersIndex extends ArrayList>> { List getLayer(String layerName) { - return stream().filter((entry) -> entry.containsKey(layerName)).findFirst().map((entry) -> entry.get(layerName)) - .orElse(Collections.emptyList()); + return stream().filter((entry) -> entry.containsKey(layerName)) + .findFirst() + .map((entry) -> entry.get(layerName)) + .orElse(Collections.emptyList()); } static LayersIndex fromArchiveFile(File archiveFile) throws IOException { diff --git a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java index 12354ccda4..439cdf2e9c 100644 --- a/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java +++ b/spring-boot-system-tests/spring-boot-image-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -87,12 +87,13 @@ class PaketoBuilderTests { ContainerConfig config = container.getContainerInfo().getConfig(); assertLabelsMatchManifestAttributes(config); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/executable-jar", - "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/executable-jar", "paketo-buildpacks/dist-zip", + "paketo-buildpacks/spring-boot"); metadata.processOfType("web").containsExactly("java", "org.springframework.boot.loader.JarLauncher"); - metadata.processOfType("executable-jar").containsExactly("java", - "org.springframework.boot.loader.JarLauncher"); + metadata.processOfType("executable-jar") + .containsExactly("java", "org.springframework.boot.loader.JarLauncher"); }); assertImageHasJvmSbomLayer(imageReference, config); assertImageHasDependenciesSbomLayer(imageReference, config, "executable-jar"); @@ -157,9 +158,9 @@ class PaketoBuilderTests { container.waitingFor(Wait.forHttp("/test")).start(); ContainerConfig config = container.getContainerInfo().getConfig(); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/dist-zip", - "paketo-buildpacks/spring-boot"); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); String launcher = "/workspace/" + projectName + "-boot/bin/" + projectName; metadata.processOfType("web").containsExactly(launcher); metadata.processOfType("dist-zip").containsExactly(launcher); @@ -168,10 +169,12 @@ class PaketoBuilderTests { assertImageHasDependenciesSbomLayer(imageReference, config, "dist-zip"); DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); - ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), - (layer) -> layer.entries().contains(projectName + "-boot/bin/" + projectName, - projectName + "-boot/lib/" + projectName + ".jar")); + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); + ImageAssertions.assertThat(imageReference) + .layer(digest.getDigest(), + (layer) -> layer.entries() + .contains(projectName + "-boot/bin/" + projectName, + projectName + "-boot/lib/" + projectName + ".jar")); } finally { removeImage(imageReference); @@ -191,9 +194,9 @@ class PaketoBuilderTests { container.waitingFor(Wait.forHttp("/test")).start(); ContainerConfig config = container.getContainerInfo().getConfig(); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/dist-zip", - "paketo-buildpacks/spring-boot"); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); String launcher = "/workspace/" + projectName + "/bin/" + projectName; metadata.processOfType("web").containsExactly(launcher); metadata.processOfType("dist-zip").containsExactly(launcher); @@ -202,8 +205,9 @@ class PaketoBuilderTests { assertImageHasDependenciesSbomLayer(imageReference, config, "dist-zip"); DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); - ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), (layer) -> layer.entries() + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); + ImageAssertions.assertThat(imageReference) + .layer(digest.getDigest(), (layer) -> layer.entries() .contains(projectName + "/bin/" + projectName, projectName + "/lib/" + projectName + "-plain.jar") .anyMatch((s) -> s.startsWith(projectName + "/lib/spring-boot-")) .anyMatch((s) -> s.startsWith(projectName + "/lib/spring-core-")) @@ -228,12 +232,13 @@ class PaketoBuilderTests { ContainerConfig config = container.getContainerInfo().getConfig(); assertLabelsMatchManifestAttributes(config); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/executable-jar", - "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/executable-jar", "paketo-buildpacks/dist-zip", + "paketo-buildpacks/spring-boot"); metadata.processOfType("web").containsExactly("java", "org.springframework.boot.loader.WarLauncher"); - metadata.processOfType("executable-jar").containsExactly("java", - "org.springframework.boot.loader.WarLauncher"); + metadata.processOfType("executable-jar") + .containsExactly("java", "org.springframework.boot.loader.WarLauncher"); }); assertImageHasJvmSbomLayer(imageReference, config); assertImageHasDependenciesSbomLayer(imageReference, config, "executable-jar"); @@ -257,9 +262,10 @@ class PaketoBuilderTests { container.waitingFor(Wait.forHttp("/test")).start(); ContainerConfig config = container.getContainerInfo().getConfig(); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/apache-tomcat", - "paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot"); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/apache-tomcat", "paketo-buildpacks/dist-zip", + "paketo-buildpacks/spring-boot"); metadata.processOfType("web").containsExactly("bash", "catalina.sh", "run"); metadata.processOfType("tomcat").containsExactly("bash", "catalina.sh", "run"); }); @@ -267,9 +273,10 @@ class PaketoBuilderTests { assertImageHasDependenciesSbomLayer(imageReference, config, "apache-tomcat"); DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); - ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), - (layer) -> layer.entries() + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest)); + ImageAssertions.assertThat(imageReference) + .layer(digest.getDigest(), + (layer) -> layer.entries() .contains("WEB-INF/classes/example/ExampleApplication.class", "WEB-INF/classes/example/HelloController.class", "META-INF/MANIFEST.MF") .anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-boot-")) @@ -295,9 +302,10 @@ class PaketoBuilderTests { ContainerConfig config = container.getContainerInfo().getConfig(); assertLabelsMatchManifestAttributes(config); ImageAssertions.assertThat(config).buildMetadata((metadata) -> { - metadata.buildpacks().contains("paketo-buildpacks/ca-certificates", - "paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/executable-jar", - "paketo-buildpacks/spring-boot", "paketo-buildpacks/native-image"); + metadata.buildpacks() + .contains("paketo-buildpacks/ca-certificates", "paketo-buildpacks/bellsoft-liberica", + "paketo-buildpacks/executable-jar", "paketo-buildpacks/spring-boot", + "paketo-buildpacks/native-image"); metadata.processOfType("web").containsExactly("/workspace/example.ExampleApplication"); metadata.processOfType("native-image").containsExactly("/workspace/example.ExampleApplication"); }); @@ -403,16 +411,17 @@ class PaketoBuilderTests { DigestCapturingCondition digest = new DigestCapturingCondition(); ImageAssertions.assertThat(config).lifecycleMetadata((metadata) -> metadata.sbomLayerSha().has(digest)); ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), (layer) -> { - layer.entries().contains("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json", - "/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json"); + layer.entries() + .contains("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json", + "/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json"); layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json", - (json) -> json.extractingJsonPathArrayValue("$.artifacts.[*].name").contains("spring-beans", - "spring-boot", "spring-boot-autoconfigure", "spring-context", "spring-core", - "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); + (json) -> json.extractingJsonPathArrayValue("$.artifacts.[*].name") + .contains("spring-beans", "spring-boot", "spring-boot-autoconfigure", "spring-context", + "spring-core", "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json", - (json) -> json.extractingJsonPathArrayValue("$.components.[*].name").contains("spring-beans", - "spring-boot", "spring-boot-autoconfigure", "spring-context", "spring-core", - "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); + (json) -> json.extractingJsonPathArrayValue("$.components.[*].name") + .contains("spring-beans", "spring-boot", "spring-boot-autoconfigure", "spring-context", + "spring-core", "spring-expression", "spring-jcl", "spring-web", "spring-webmvc")); }); } @@ -420,18 +429,23 @@ class PaketoBuilderTests { throws IOException { DigestsCapturingCondition digests = new DigestsCapturingCondition(); ImageAssertions.assertThat(config) - .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(5, digests)); + .lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(5, digests)); LayersIndex layersIndex = LayersIndex.fromArchiveFile(projectArchiveFile()); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(0), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(0), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("dependencies")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(1), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(1), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("spring-boot-loader")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(2), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(2), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("snapshot-dependencies")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(3), (layer) -> layer.entries() + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(3), (layer) -> layer.entries() .allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("application")))); - ImageAssertions.assertThat(imageReference).layer(digests.getDigest(4), - (layer) -> layer.entries().allMatch((entry) -> entry.contains("lib/spring-cloud-bindings-"))); + ImageAssertions.assertThat(imageReference) + .layer(digests.getDigest(4), + (layer) -> layer.entries().allMatch((entry) -> entry.contains("lib/spring-cloud-bindings-"))); } private File projectArchiveFile() { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java index 4e02d45db7..9dfc5cbd4a 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/AbstractLaunchScriptIntegrationTests.java @@ -100,8 +100,8 @@ abstract class AbstractLaunchScriptIntegrationTests { private LaunchScriptTestContainer(String os, String version, String scriptsDir, String testScript) { super(new ImageFromDockerfile("spring-boot-launch-script/" + os.toLowerCase() + "-" + version) - .withFileFromFile("Dockerfile", - new File("src/intTest/resources/conf/" + os + "/" + version + "/Dockerfile"))); + .withFileFromFile("Dockerfile", + new File("src/intTest/resources/conf/" + os + "/" + version + "/Dockerfile"))); withCopyFileToContainer(MountableFile.forHostPath(findApplication().getAbsolutePath()), "/app.jar"); withCopyFileToContainer( MountableFile.forHostPath("src/intTest/resources/scripts/" + scriptsDir + "test-functions.sh"), diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java index cc8fd46a3a..62bd601c5a 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-launch-script-tests/src/intTest/java/org/springframework/boot/launchscript/SysVinitLaunchScriptIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class SysVinitLaunchScriptIntegrationTests extends AbstractLaunchScriptIntegrati String output = doTest(os, version, "status-when-killed.sh"); assertThat(output).contains("Status: 1"); assertThat(output) - .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); + .has(coloredString(AnsiColor.RED, "Not running (process " + extractPid(output) + " not found)")); } @ParameterizedTest(name = "{0} {1}") @@ -133,16 +133,16 @@ class SysVinitLaunchScriptIntegrationTests extends AbstractLaunchScriptIntegrati @MethodSource("parameters") void launchWithMissingLogFolderGeneratesAWarning(String os, String version) throws Exception { String output = doTest(os, version, "launch-with-missing-log-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.YELLOW, "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + assertThat(output) + .has(coloredString(AnsiColor.YELLOW, "LOG_FOLDER /does/not/exist does not exist. Falling back to /tmp")); } @ParameterizedTest(name = "{0} {1}") @MethodSource("parameters") void launchWithMissingPidFolderGeneratesAWarning(String os, String version) throws Exception { String output = doTest(os, version, "launch-with-missing-pid-folder.sh"); - assertThat(output).has( - coloredString(AnsiColor.YELLOW, "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); + assertThat(output) + .has(coloredString(AnsiColor.YELLOW, "PID_FOLDER /does/not/exist does not exist. Falling back to /tmp")); } @ParameterizedTest(name = "{0} {1}") diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java index 0cbf656fc7..740734357b 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-loader-tests/src/intTest/java/org/springframework/boot/loader/LoaderIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -54,16 +54,19 @@ class LoaderIntegrationTests { try (GenericContainer container = createContainer(javaRuntime)) { container.start(); System.out.println(this.output.toUtf8String()); - assertThat(this.output.toUtf8String()).contains(">>>>> 287649 BYTES from").doesNotContain("WARNING:") - .doesNotContain("illegal").doesNotContain("jar written to temp"); + assertThat(this.output.toUtf8String()).contains(">>>>> 287649 BYTES from") + .doesNotContain("WARNING:") + .doesNotContain("illegal") + .doesNotContain("jar written to temp"); } } private GenericContainer createContainer(JavaRuntime javaRuntime) { - return javaRuntime.getContainer().withLogConsumer(this.output) - .withCopyFileToContainer(MountableFile.forHostPath(findApplication().toPath()), "/app.jar") - .withStartupCheckStrategy(new OneShotStartupCheckStrategy().withTimeout(Duration.ofMinutes(5))) - .withCommand("java", "-jar", "app.jar"); + return javaRuntime.getContainer() + .withLogConsumer(this.output) + .withCopyFileToContainer(MountableFile.forHostPath(findApplication().toPath()), "/app.jar") + .withStartupCheckStrategy(new OneShotStartupCheckStrategy().withTimeout(Duration.ofMinutes(5))) + .withCommand("java", "-jar", "app.jar"); } private File findApplication() { @@ -116,7 +119,7 @@ class LoaderIntegrationTests { static JavaRuntime oracleJdk17() { ImageFromDockerfile image = new ImageFromDockerfile("spring-boot-loader/oracle-jdk-17") - .withFileFromFile("Dockerfile", new File("src/intTest/resources/conf/oracle-jdk-17/Dockerfile")); + .withFileFromFile("Dockerfile", new File("src/intTest/resources/conf/oracle-jdk-17/Dockerfile")); return new JavaRuntime("Oracle JDK 17", JavaVersion.SEVENTEEN, () -> new GenericContainer<>(image)); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java index d1c3170384..010f9e07f9 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServerContainerInvocationContextProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -82,16 +82,17 @@ class EmbeddedServerContainerInvocationContextProvider @Override public Stream provideTestTemplateInvocationContexts(ExtensionContext context) { EmbeddedServletContainerTest annotation = context.getRequiredTestClass() - .getAnnotation(EmbeddedServletContainerTest.class); - return CONTAINERS.stream().map((container) -> getApplication(annotation, container)) - .flatMap((builder) -> provideTestTemplateInvocationContexts(annotation, builder)); + .getAnnotation(EmbeddedServletContainerTest.class); + return CONTAINERS.stream() + .map((container) -> getApplication(annotation, container)) + .flatMap((builder) -> provideTestTemplateInvocationContexts(annotation, builder)); } private Stream provideTestTemplateInvocationContexts( EmbeddedServletContainerTest annotation, Application application) { return Stream.of(annotation.launchers()) - .map((launcherClass) -> getAbstractApplicationLauncher(application, launcherClass)) - .map((launcher) -> provideTestTemplateInvocationContext(application, launcher)); + .map((launcherClass) -> getAbstractApplicationLauncher(application, launcherClass)) + .map((launcher) -> provideTestTemplateInvocationContext(application, launcher)); } private EmbeddedServletContainerInvocationContext provideTestTemplateInvocationContext(Application application, @@ -186,8 +187,8 @@ class EmbeddedServerContainerInvocationContextProvider @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory(HttpClients.custom() - .setRetryStrategy(new DefaultHttpRequestRetryStrategy(10, TimeValue.of(1, TimeUnit.SECONDS))) - .build())); + .setRetryStrategy(new DefaultHttpRequestRetryStrategy(10, TimeValue.of(1, TimeUnit.SECONDS))) + .build())); rest.setErrorHandler(new ResponseErrorHandler() { @Override diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java index 04fe90fd5d..9b768e7fea 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerJarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -68,7 +68,7 @@ class EmbeddedServletContainerJarPackagingIntegrationTests { @TestTemplate void applicationClassesAreNotAvailableViaHttp(RestTemplate rest) { ResponseEntity entity = rest - .getForEntity("/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", String.class); + .getForEntity("/BOOT-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java index 517d8f7dd7..01fca8b306 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarDevelopmentIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -76,7 +76,7 @@ class EmbeddedServletContainerWarDevelopmentIntegrationTests { ResponseEntity entity = rest.getForEntity("/resourcePaths", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(readLines(entity.getBody())) - .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); + .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); } private List readLines(String input) { diff --git a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java index 7bf71616c7..a186fe9f09 100644 --- a/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java +++ b/spring-boot-tests/spring-boot-integration-tests/spring-boot-server-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerWarPackagingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -74,7 +74,7 @@ class EmbeddedServletContainerWarPackagingIntegrationTests { @TestTemplate void applicationClassesAreNotAvailableViaHttp(RestTemplate rest) { ResponseEntity entity = rest - .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); + .getForEntity("/WEB-INF/classes/com/example/ResourceHandlingApplication.class", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @@ -98,14 +98,14 @@ class EmbeddedServletContainerWarPackagingIntegrationTests { ResponseEntity entity = rest.getForEntity("/resourcePaths", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(readLines(entity.getBody())) - .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); + .noneMatch((resourcePath) -> resourcePath.startsWith("/org/springframework/boot/loader")); } @TestTemplate void conditionalOnWarDeploymentBeanIsNotAvailableForEmbeddedServer(RestTemplate rest) { assertThat(rest.getForEntity("/always", String.class).getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(rest.getForEntity("/conditionalOnWar", String.class).getStatusCode()) - .isEqualTo(HttpStatus.NOT_FOUND); + .isEqualTo(HttpStatus.NOT_FOUND); } private List readLines(String input) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java index ab476cf12e..9db6c70bea 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/main/java/smoketest/actuator/customsecurity/SecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,7 +59,7 @@ public class SecurityConfiguration { requests.requestMatchers("/actuator/beans").hasRole("BEANS"); requests.requestMatchers(EndpointRequest.to("health")).permitAll(); requests.requestMatchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR"); + .hasRole("ACTUATOR"); requests.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll(); requests.requestMatchers("/foo").permitAll(); requests.requestMatchers("/error").permitAll(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java index 68114a4f71..6f40eb7cf6 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/AbstractSampleActuatorCustomSecurityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -156,21 +156,21 @@ abstract class AbstractSampleActuatorCustomSecurityTests { @Test void actuatorCustomMvcSecureEndpointWithAnonymous() { ResponseEntity entity = restTemplate() - .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); + .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void actuatorCustomMvcSecureEndpointWithUnauthorizedUser() { ResponseEntity entity = userRestTemplate() - .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); + .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test void actuatorCustomMvcSecureEndpointWithAuthorizedUser() { ResponseEntity entity = adminRestTemplate() - .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); + .getForEntity(getManagementPath() + "/actuator/example/echo?text={t}", String.class, "test"); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("test"); assertThat(entity.getHeaders().getFirst("echo")).isEqualTo("test"); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java index 13d44c7d68..d560ab4a1d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/CorsSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -67,7 +67,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestToEndpointShouldReturnOk() throws Exception { RequestEntity envRequest = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:8080") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity exchange = this.testRestTemplate.exchange(envRequest, Map.class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -75,7 +77,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { RequestEntity entity = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:9095").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:9095") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity exchange = this.testRestTemplate.exchange(entity, byte[].class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java index 9c24a32708..29384b280c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortAndPathSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class ManagementPortAndPathSampleActuatorApplicationTests extends AbstractSample @Test void testMissing() { ResponseEntity entity = new TestRestTemplate("admin", "admin") - .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java index ce2fb6f68b..f0253cacc7 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-custom-security/src/test/java/smoketest/actuator/customsecurity/ManagementPortCustomServletPathSampleActuatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -51,7 +51,7 @@ class ManagementPortCustomServletPathSampleActuatorTests extends AbstractSampleA @Test void actuatorPathOnMainPortShouldNotMatch() { ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); + .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java index 03c9be6679..a022ca9389 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-log4j2/src/test/java/smoketest/actuator/log4j2/SampleActuatorLog4J2ApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -59,9 +59,11 @@ class SampleActuatorLog4J2ApplicationTests { @Test void validateLoggersEndpoint() throws Exception { - this.mvc.perform(get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol").header("Authorization", - getBasicAuth())).andExpect(status().isOk()) - .andExpect(content().string("{\"configuredLevel\":\"WARN\",\"effectiveLevel\":\"WARN\"}")); + this.mvc + .perform(get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol").header("Authorization", + getBasicAuth())) + .andExpect(status().isOk()) + .andExpect(content().string("{\"configuredLevel\":\"WARN\",\"effectiveLevel\":\"WARN\"}")); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java index 878c403c4c..d2bd9e6593 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,14 +55,14 @@ class SampleActuatorUiApplicationPortTests { void testMetrics() { @SuppressWarnings("rawtypes") ResponseEntity entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { ResponseEntity entity = new TestRestTemplate().withBasicAuth("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java index 6ca9b19981..a5199c4b0f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator-ui/src/test/java/smoketest/actuator/ui/SampleActuatorUiApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -49,8 +49,8 @@ class SampleActuatorUiApplicationTests { void testHome() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/", - HttpMethod.GET, new HttpEntity(headers), String.class); + ResponseEntity entity = this.restTemplate.withBasicAuth("user", getPassword()) + .exchange("/", HttpMethod.GET, new HttpEntity(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello"); } @@ -73,11 +73,12 @@ class SampleActuatorUiApplicationTests { void testError() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/error", - HttpMethod.GET, new HttpEntity<Void>(headers), String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) + .exchange("/error", HttpMethod.GET, new HttpEntity<Void>(headers), String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); - assertThat(entity.getBody()).contains("<html>").contains("<body>") - .contains("Please contact the operator with the above information"); + assertThat(entity.getBody()).contains("<html>") + .contains("<body>") + .contains("Please contact the operator with the above information"); } private String getPassword() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java index cd2daeabc3..c6d50cc769 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/AbstractManagementPortAndPathSampleActuatorApplicationTests.java @@ -58,14 +58,14 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { void testMetrics() { testHome(); // makes sure some requests have been made ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\",\"groups\":[\"comp\",\"live\",\"ready\"]}"); } @@ -73,7 +73,7 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { @Test void testGroupWithComposite() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/health/comp", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/health/comp", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains( "components\":{\"a\":{\"status\":\"UP\",\"details\":{\"hello\":\"spring-a\"}},\"c\":{\"status\":\"UP\",\"details\":{\"hello\":\"spring-c\"}}"); @@ -83,15 +83,15 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { void testEnvNotFound() { String unknownProperty = "test-does-not-exist"; assertThat(this.environment.containsProperty(unknownProperty)).isFalse(); - ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password").getForEntity( - "http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class); + ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") + .getForEntity("http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test void testMissing() { ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).contains("\"status\":404"); } @@ -99,7 +99,7 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { @Test void testErrorPage() { ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.port + "/error", Map.class)); + .getForEntity("http://localhost:" + this.port + "/error", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); assertThat(entity.getBody()).containsEntry("status", 999); } @@ -107,7 +107,7 @@ abstract class AbstractManagementPortAndPathSampleActuatorApplicationTests { @Test void testManagementErrorPage() { ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).containsEntry("status", 999); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java index 68bc6f9c79..32eab95153 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/CorsSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -67,7 +67,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestToEndpointShouldReturnOk() throws Exception { RequestEntity<?> healthRequest = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:8080") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest, Map.class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK); } @@ -75,7 +77,9 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception { RequestEntity<?> entity = RequestEntity.options(new URI("/actuator/env")) - .header("Origin", "http://localhost:9095").header("Access-Control-Request-Method", "GET").build(); + .header("Origin", "http://localhost:9095") + .header("Access-Control-Request-Method", "GET") + .build(); ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, byte[].class); assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java index 098e498f9b..5518ad7fa4 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/EndpointsPropertiesSampleActuatorApplicationTests.java @@ -55,7 +55,7 @@ class EndpointsPropertiesSampleActuatorApplicationTests { @Test void testCustomContextPath() { ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/admin/health", String.class); + .getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).contains("\"hello\":\"world\""); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java index 6e9a137baa..7f2fcd2043 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementAddressActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -55,7 +55,7 @@ class ManagementAddressActuatorApplicationTests { @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java index 89e0392177..3b2f52f533 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class ManagementDifferentPortAndEndpointWithExceptionHandlerSampleActuatorApplic @Test void testExceptionHandlerRestControllerEndpoint() { ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/exception", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/exception", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.I_AM_A_TEAPOT); assertThat(entity.getBody()).isEqualTo("this is a custom exception body"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java index 4b944a0aa1..24503656d8 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementDifferentPortSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class ManagementDifferentPortSampleActuatorApplicationTests { @Test void linksEndpointShouldBeAvailable() { ResponseEntity<String> entity = new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort, String.class); + .getForEntity("http://localhost:" + this.managementPort, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java index 53767d4b13..ae97c9a256 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPathSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -44,7 +44,7 @@ class ManagementPathSampleActuatorApplicationTests { @Test void testHealth() { ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/admin/health", String.class); + .getForEntity("/admin/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java index 9d69a3510d..0345748d4a 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortSampleActuatorApplicationTests.java @@ -69,14 +69,14 @@ class ManagementPortSampleActuatorApplicationTests { void testMetrics() { testHome(); // makes sure some requests have been made ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate() - .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).contains("\"example\""); @@ -86,7 +86,7 @@ class ManagementPortSampleActuatorApplicationTests { @Test void testErrorPage() { ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/error", Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).containsEntry("status", 999); } @@ -95,7 +95,7 @@ class ManagementPortSampleActuatorApplicationTests { void securityContextIsAvailableToErrorHandling() { this.errorAttributes.securityContext = null; ResponseEntity<Map<String, Object>> entity = asMapEntity(new TestRestTemplate("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/404", Map.class)); + .getForEntity("http://localhost:" + this.managementPort + "/404", Map.class)); assertThat(this.errorAttributes.securityContext.getAuthentication()).isNotNull(); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(entity.getBody()).containsEntry("status", 404); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java index 301befa381..6ab315da4e 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ManagementPortWithLazyInitializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class ManagementPortWithLazyInitializationTests { @Test void testHealth() { ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password") - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperFalseTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperFalseTests.java index 4a77556a88..f4cf9bd4fa 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperFalseTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperFalseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class SampleActuatorApplicationIsolatedObjectMapperFalseTests { @Test void resourceShouldBeAvailableOnMainPort() { ResponseEntity<String> entity = this.testRestTemplate.withBasicAuth("user", "password") - .getForEntity("/actuator/startup", String.class); + .getForEntity("/actuator/startup", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperTrueTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperTrueTests.java index 120da39375..16a5cf503c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperTrueTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationIsolatedObjectMapperTrueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,7 +45,7 @@ class SampleActuatorApplicationIsolatedObjectMapperTrueTests { @Test void resourceShouldBeAvailableOnMainPort() { ResponseEntity<String> entity = this.testRestTemplate.withBasicAuth("user", "password") - .getForEntity("/actuator/startup", String.class); + .getForEntity("/actuator/startup", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"timeline\":"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java index 09c4c5d305..8ddd0cefe6 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/SampleActuatorApplicationTests.java @@ -111,8 +111,8 @@ class SampleActuatorApplicationTests { @Test void testErrorPage() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password").getForEntity("/foo", - String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") + .getForEntity("/foo", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).contains("\"error\":"); @@ -123,8 +123,8 @@ class SampleActuatorApplicationTests { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<?> request = new HttpEntity<Void>(headers); - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password").exchange("/foo", - HttpMethod.GET, request, String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") + .exchange("/foo", HttpMethod.GET, request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).as("Body was null").isNotNull(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java index 2fb7304de9..87e9d3330d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ServletPathSampleActuatorApplicationTests.java @@ -52,7 +52,7 @@ class ServletPathSampleActuatorApplicationTests { @Test void testHealth() { ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", "password") - .getForEntity("/spring/actuator/health", String.class); + .getForEntity("/spring/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java index eb0ade3d06..0cf7efef98 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-actuator/src/test/java/smoketest/actuator/ShutdownSampleActuatorApplicationTests.java @@ -59,7 +59,7 @@ class ShutdownSampleActuatorApplicationTests { @DirtiesContext void testShutdown() { ResponseEntity<Map<String, Object>> entity = asMapEntity(this.restTemplate.withBasicAuth("user", "password") - .postForEntity("/actuator/shutdown", null, Map.class)); + .postForEntity("/actuator/shutdown", null, Map.class)); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(((String) entity.getBody().get("message"))).contains("Shutting down"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java index 15b9c26c9b..9bfcdd1d63 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-ant/src/test/java/smoketest/ant/SampleAntApplicationIT.java @@ -38,8 +38,9 @@ public class SampleAntApplicationIT { @Test void runJar() throws Exception { File libs = new File("build/ant/libs"); - Process process = new JavaExecutable().processBuilder("-jar", "spring-boot-smoke-test-ant.jar").directory(libs) - .start(); + Process process = new JavaExecutable().processBuilder("-jar", "spring-boot-smoke-test-ant.jar") + .directory(libs) + .start(); process.waitFor(5, TimeUnit.MINUTES); assertThat(process.exitValue()).isZero(); String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream())); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java index 19009571b4..6b84c1a4d5 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -52,8 +52,8 @@ class SubversionConfigDataLoader implements ConfigDataLoader<SubversionConfigDat @Override public ConfigData load(ConfigDataLoaderContext context, SubversionConfigDataResource resource) throws IOException, ConfigDataLocationNotFoundException { - context.getBootstrapContext().registerIfAbsent(SubversionServerCertificate.class, - InstanceSupplier.of(resource.getServerCertificate())); + context.getBootstrapContext() + .registerIfAbsent(SubversionServerCertificate.class, InstanceSupplier.of(resource.getServerCertificate())); SubversionClient client = context.getBootstrapContext().get(SubversionClient.class); String loaded = client.load(resource.getLocation()); PropertySource<?> propertySource = new MapPropertySource("svn", Collections.singletonMap("svn", loaded)); @@ -61,8 +61,9 @@ class SubversionConfigDataLoader implements ConfigDataLoader<SubversionConfigDat } private static void onBootstrapContextClosed(BootstrapContextClosedEvent event) { - event.getApplicationContext().getBeanFactory().registerSingleton("subversionClient", - event.getBootstrapContext().get(SubversionClient.class)); + event.getApplicationContext() + .getBeanFactory() + .registerSingleton("subversionClient", event.getBootstrapContext().get(SubversionClient.class)); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java index beac974635..a04b7330ae 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/external/svn/SubversionConfigDataLocationResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -44,8 +44,8 @@ class SubversionConfigDataLocationResolver implements ConfigDataLocationResolver ConfigDataLocation location) throws ConfigDataLocationNotFoundException, ConfigDataResourceNotFoundException { String serverCertificate = context.getBinder().bind("spring.svn.server.certificate", String.class).orElse(null); - return Collections.singletonList( - new SubversionConfigDataResource(location.getNonPrefixedValue(PREFIX), serverCertificate)); + return Collections + .singletonList(new SubversionConfigDataResource(location.getNonPrefixedValue(PREFIX), serverCertificate)); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java index edb750f5e5..c0549aa755 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/test/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,7 +36,7 @@ class SampleBootstrapRegistryApplicationTests { void testBootstrapper(CapturedOutput output) { SampleBootstrapRegistryApplication.main(new String[0]); assertThat(output).contains("svn my-data from svn / example.com[secret]") - .contains("client smoketest.bootstrapregistry.app.MySubversionClient"); + .contains("client smoketest.bootstrapregistry.app.MySubversionClient"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java index 52ee22cd1d..fd17c9947c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jdbc/src/test/java/smoketest/data/jdbc/SampleDataJdbcApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -50,8 +50,9 @@ class SampleDataJdbcApplicationTests { @Test void testCustomers() throws Exception { - this.mvc.perform(get("/").param("name", "merEDith")).andExpect(status().isOk()) - .andExpect(content().string(containsString("Meredith"))); + this.mvc.perform(get("/").param("name", "merEDith")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Meredith"))); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java index db319a3abf..0917738ec8 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SampleDataJpaApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -66,7 +66,7 @@ class SampleDataJpaApplicationTests { @Test void testJmx() throws Exception { assertThat(ManagementFactory.getPlatformMBeanServer() - .queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null)).hasSize(1); + .queryMBeans(new ObjectName("jpa.sample:type=HikariDataSource,*"), null)).hasSize(1); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java index 971768491b..9c082c3f3b 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-flyway/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class CityRepositoryTests { @Container static PostgreSQLContainer<?> postgresql = new PostgreSQLContainer<>(DockerImageNames.postgresql()) - .withDatabaseName("test_flyway"); + .withDatabaseName("test_flyway"); @DynamicPropertySource static void postgresqlProperties(DynamicPropertyRegistry registry) { @@ -59,7 +59,8 @@ class CityRepositoryTests { @Test void databaseHasBeenInitialized() { StepVerifier.create(this.repository.findByState("DC").filter((city) -> city.getName().equals("Washington"))) - .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()).verifyComplete(); + .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()) + .verifyComplete(); } private static String r2dbcUrl() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java index af1ec7a5c2..c0de6abc3f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc-liquibase/src/test/java/smoketest/data/r2dbc/CityRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -39,7 +39,7 @@ class CityRepositoryTests { @Container static PostgreSQLContainer<?> postgresql = new PostgreSQLContainer<>(DockerImageNames.postgresql()) - .withDatabaseName("test_liquibase"); + .withDatabaseName("test_liquibase"); @DynamicPropertySource static void postgresqlProperties(DynamicPropertyRegistry registry) { @@ -59,7 +59,8 @@ class CityRepositoryTests { @Test void databaseHasBeenInitialized() { StepVerifier.create(this.repository.findByState("DC").filter((city) -> city.getName().equals("Washington"))) - .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()).verifyComplete(); + .consumeNextWith((city) -> assertThat(city.getId()).isNotNull()) + .verifyComplete(); } private static String r2dbcUrl() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java index cc414e16c0..9c14f60221 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-r2dbc/src/test/java/smoketest/data/r2dbc/SampleR2dbcApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,12 @@ class SampleR2dbcApplicationTests { @Test void citiesEndpointReturnInitialState() { - this.webClient.get().uri("/cities").exchange().expectBody().jsonPath("$[*].id") - .isEqualTo(new JSONArray().appendElement(2000).appendElement(2001)); + this.webClient.get() + .uri("/cities") + .exchange() + .expectBody() + .jsonPath("$[*].id") + .isEqualTo(new JSONArray().appendElement(2000).appendElement(2001)); } @Test @@ -51,9 +55,16 @@ class SampleR2dbcApplicationTests { @Test void healthEndpointHasR2dbcEntry() { - this.webClient.get().uri("/actuator/health").exchange().expectStatus().isOk().expectBody() - .jsonPath("components.r2dbc.status").isEqualTo("UP").jsonPath("components.r2dbc.details.database") - .isEqualTo("H2"); + this.webClient.get() + .uri("/actuator/health") + .exchange() + .expectStatus() + .isOk() + .expectBody() + .jsonPath("components.r2dbc.status") + .isEqualTo("UP") + .jsonPath("components.r2dbc.details.database") + .isEqualTo("H2"); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java index 57f0456269..c6d5006e2f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-rest/src/test/java/smoketest/data/rest/SampleDataRestApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -61,15 +61,17 @@ class SampleDataRestApplicationTests { @Test void findByNameAndCountry() throws Exception { this.mvc.perform(get("/api/cities/search/findByNameAndCountryAllIgnoringCase?name=Melbourne&country=Australia")) - .andExpect(status().isOk()).andExpect(jsonPath("state", equalTo("Victoria"))) - .andExpect(jsonPath("name", equalTo("Melbourne"))); + .andExpect(status().isOk()) + .andExpect(jsonPath("state", equalTo("Victoria"))) + .andExpect(jsonPath("name", equalTo("Melbourne"))); } @Test void findByContaining() throws Exception { - this.mvc.perform( - get("/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) - .andExpect(status().isOk()).andExpect(jsonPath("_embedded.cities", hasSize(3))); + this.mvc + .perform(get("/api/cities/search/findByNameContainingAndCountryContainingAllIgnoringCase?name=&country=UK")) + .andExpect(status().isOk()) + .andExpect(jsonPath("_embedded.cities", hasSize(3))); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java index 362ebc6ef2..3c0f2a656d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/main/java/smoketest/graphql/SecurityConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,10 +36,11 @@ public class SecurityConfig { @Bean public DefaultSecurityFilterChain springWebFilterChain(HttpSecurity http) throws Exception { return http.csrf((csrf) -> csrf.disable()) - // Demonstrate that method security works - // Best practice to use both for defense in depth - .authorizeHttpRequests((requests) -> requests.anyRequest().permitAll()).httpBasic(withDefaults()) - .build(); + // Demonstrate that method security works + // Best practice to use both for defense in depth + .authorizeHttpRequests((requests) -> requests.anyRequest().permitAll()) + .httpBasic(withDefaults()) + .build(); } @Bean diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java index 27ddea4659..086ab12f83 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/GreetingControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -44,22 +44,29 @@ class GreetingControllerTests { @Test void shouldGreetWithSpecificName() { HttpGraphQlTester authenticated = withAdminCredentials(this.graphQlTester); - authenticated.documentName("greeting").variable("name", "Brian").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Brian!"); + authenticated.documentName("greeting") + .variable("name", "Brian") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Brian!"); } @Test void shouldGreetWithDefaultName() { HttpGraphQlTester authenticated = withAdminCredentials(this.graphQlTester); - authenticated.document("{ greeting }").execute().path("greeting").entity(String.class) - .isEqualTo("Hello, Spring!"); + authenticated.document("{ greeting }") + .execute() + .path("greeting") + .entity(String.class) + .isEqualTo("Hello, Spring!"); } private HttpGraphQlTester withAdminCredentials(HttpGraphQlTester graphQlTester) { return graphQlTester.mutate() - .webTestClient( - (httpClient) -> httpClient.defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin"))) - .build(); + .webTestClient( + (httpClient) -> httpClient.defaultHeaders((headers) -> headers.setBasicAuth("admin", "admin"))) + .build(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java index a9a76eee10..0ad99df70d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-graphql/src/test/java/smoketest/graphql/ProjectControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -30,14 +30,19 @@ class ProjectControllerTests { @Test void shouldFindSpringGraphQl() { - this.graphQlTester.document("{ project(slug: \"spring-graphql\") { name } }").execute().path("project.name") - .entity(String.class).isEqualTo("Spring GraphQL"); + this.graphQlTester.document("{ project(slug: \"spring-graphql\") { name } }") + .execute() + .path("project.name") + .entity(String.class) + .isEqualTo("Spring GraphQL"); } @Test void shouldNotFindUnknownProject() { - this.graphQlTester.document("{ project(slug: \"spring-unknown\") { name } }").execute().path("project.name") - .pathDoesNotExist(); + this.graphQlTester.document("{ project(slug: \"spring-unknown\") { name } }") + .execute() + .path("project.name") + .pathDoesNotExist(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java index dece280815..6b69bf1a52 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/main/java/smoketest/integration/SampleIntegrationApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -63,8 +63,12 @@ public class SampleIntegrationApplication { @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlow.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) - .channel(outputChannel()).handle(fileWriter()).get(); + return IntegrationFlow.from(fileReader(), new FixedRatePoller()) + .channel(inputChannel()) + .handle(endpoint) + .channel(outputChannel()) + .handle(fileWriter()) + .get(); } public static void main(String[] args) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java index 0241aa0c5a..0424c7ee7d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-integration/src/test/java/smoketest/integration/consumer/SampleIntegrationApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -77,8 +77,8 @@ class SampleIntegrationApplicationTests { } private void awaitOutputContaining(File outputDir, String requiredContents) { - Awaitility.waitAtMost(Duration.ofSeconds(30)).until(() -> outputIn(outputDir), - containsString(requiredContents)); + Awaitility.waitAtMost(Duration.ofSeconds(30)) + .until(() -> outputIn(outputDir), containsString(requiredContents)); } private String outputIn(File outputDir) throws IOException { @@ -91,7 +91,7 @@ class SampleIntegrationApplicationTests { private Resource[] findResources(File outputDir) throws IOException { return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) - .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); + .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); } private String readResources(Resource[] resources) throws IOException { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/main/java/smoketest/jersey/SampleJerseyApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/main/java/smoketest/jersey/SampleJerseyApplication.java index d44e50c5d4..f271a73036 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/main/java/smoketest/jersey/SampleJerseyApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/main/java/smoketest/jersey/SampleJerseyApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -25,8 +25,10 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer public class SampleJerseyApplication extends SpringBootServletInitializer { public static void main(String[] args) { - new SampleJerseyApplication().configure(new SpringApplicationBuilder(SampleJerseyApplication.class) - .applicationStartup(new BufferingApplicationStartup(2048))).run(args); + new SampleJerseyApplication() + .configure(new SpringApplicationBuilder(SampleJerseyApplication.class) + .applicationStartup(new BufferingApplicationStartup(2048))) + .run(args); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java index 51bc7481a7..acf6eee79d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/AbstractJerseyManagementPortTests.java @@ -65,21 +65,21 @@ class AbstractJerseyManagementPortTests { @Test void resourceShouldNotBeAvailableOnManagementPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/test", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/test", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test void actuatorShouldBeAvailableOnManagementPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test void actuatorShouldNotBeAvailableOnMainPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java index 466286e4ce..8a78736aef 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperFalseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,10 +53,10 @@ class JerseyActuatorIsolatedObjectMapperFalseTests { @Test void resourceShouldBeAvailableOnMainPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/startup", String.class); + .getForEntity("http://localhost:" + this.port + "/actuator/startup", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(entity.getBody()) - .contains("Java 8 date/time type `java.time.Clock$SystemClock` not supported by default"); + .contains("Java 8 date/time type `java.time.Clock$SystemClock` not supported by default"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java index 3028808f24..8b013a2c74 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyActuatorIsolatedObjectMapperTrueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -53,7 +53,7 @@ class JerseyActuatorIsolatedObjectMapperTrueTests { @Test void resourceShouldBeAvailableOnMainPort() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/startup", String.class); + .getForEntity("http://localhost:" + this.port + "/actuator/startup", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"timeline\":"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java index 5843f0a0fc..8336494fbd 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyApplicationPathAndManagementPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ class JerseyApplicationPathAndManagementPortTests { @Test void applicationPathShouldNotAffectActuators() { ResponseEntity<String> entity = this.testRestTemplate - .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java index e5e332e601..68a59efdff 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-jersey/src/test/java/smoketest/jersey/JerseyDifferentPortSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class JerseyDifferentPortSampleActuatorApplicationTests { @Test void linksEndpointShouldBeAvailable() { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java index a5be7c96d6..8f1a1daff7 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-liquibase/src/test/java/smoketest/liquibase/SampleLiquibaseApplicationTests.java @@ -56,14 +56,14 @@ class SampleLiquibaseApplicationTests { assumeThat(serverNotRunning(ex)).isFalse(); } assertThat(output).contains("Successfully acquired change log lock") - .contains("Creating database history table with name: PUBLIC.DATABASECHANGELOG") - .contains("Table person created") - .contains("ChangeSet classpath:/db/changelog/db.changelog-master.yaml::1::" - + "marceloverdijk ran successfully") - .contains("New row inserted into person") - .contains("ChangeSet classpath:/db/changelog/" - + "db.changelog-master.yaml::2::marceloverdijk ran successfully") - .contains("Successfully released change log lock"); + .contains("Creating database history table with name: PUBLIC.DATABASECHANGELOG") + .contains("Table person created") + .contains("ChangeSet classpath:/db/changelog/db.changelog-master.yaml::1::" + + "marceloverdijk ran successfully") + .contains("New row inserted into person") + .contains("ChangeSet classpath:/db/changelog/" + + "db.changelog-master.yaml::2::marceloverdijk ran successfully") + .contains("Successfully released change log lock"); } private boolean serverNotRunning(IllegalStateException ex) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java index e276fa3308..8a59dfb428 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -100,7 +100,8 @@ class SampleOauth2ResourceServerApplicationTests { + "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq" + "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}"; return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .setResponseCode(200).setBody(body); + .setResponseCode(200) + .setBody(body); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java index a0d424266c..fa3eeefcc0 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/main/java/smoketest/parent/SampleParentContextApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -73,8 +73,12 @@ public class SampleParentContextApplication { @Bean public IntegrationFlow integrationFlow(SampleEndpoint endpoint) { - return IntegrationFlow.from(fileReader(), new FixedRatePoller()).channel(inputChannel()).handle(endpoint) - .channel(outputChannel()).handle(fileWriter()).get(); + return IntegrationFlow.from(fileReader(), new FixedRatePoller()) + .channel(inputChannel()) + .handle(endpoint) + .channel(outputChannel()) + .handle(fileWriter()) + .get(); } private static class FixedRatePoller implements Consumer<SourcePollingChannelAdapterSpec> { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java index b918d093b1..c179e39047 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-parent-context/src/test/java/smoketest/parent/consumer/SampleIntegrationParentApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -59,8 +59,8 @@ class SampleIntegrationParentApplicationTests { } private void awaitOutputContaining(File outputDir, String requiredContents) { - Awaitility.waitAtMost(Duration.ofSeconds(30)).until(() -> outputIn(outputDir), - containsString(requiredContents)); + Awaitility.waitAtMost(Duration.ofSeconds(30)) + .until(() -> outputIn(outputDir), containsString(requiredContents)); } private String outputIn(File outputDir) throws IOException { @@ -73,7 +73,7 @@ class SampleIntegrationParentApplicationTests { private Resource[] findResources(File outputDir) throws IOException { return ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()) - .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); + .getResources("file:" + outputDir.getAbsolutePath() + "/*.txt"); } private String readResources(Resource[] resources) throws IOException { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java index 4ddb619d11..11c453eb84 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-property-validation/src/test/java/smoketest/propertyvalidation/SamplePropertyValidationApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,15 +57,17 @@ class SamplePropertyValidationApplicationTests { void bindInvalidHost() { this.context.register(SamplePropertyValidationApplication.class); TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090").applyTo(this.context); - assertThatExceptionOfType(BeanCreationException.class).isThrownBy(this.context::refresh).havingRootCause() - .isInstanceOf(BindValidationException.class); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(this.context::refresh) + .havingRootCause() + .isInstanceOf(BindValidationException.class); } @Test void bindNullHost() { this.context.register(SamplePropertyValidationApplication.class); - assertThatExceptionOfType(BeanCreationException.class).isThrownBy(this.context::refresh).havingRootCause() - .isInstanceOf(BindValidationException.class); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(this.context::refresh) + .havingRootCause() + .isInstanceOf(BindValidationException.class); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java index 221cde31f8..3013acc99d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleQuartzApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -42,49 +42,69 @@ public class SampleQuartzApplication { @Bean public JobDetail helloJobDetail() { - return JobBuilder.newJob(SampleJob.class).withIdentity("helloJob", "samples").usingJobData("name", "World") - .storeDurably().build(); + return JobBuilder.newJob(SampleJob.class) + .withIdentity("helloJob", "samples") + .usingJobData("name", "World") + .storeDurably() + .build(); } @Bean public JobDetail anotherJobDetail() { - return JobBuilder.newJob(SampleJob.class).withIdentity("anotherJob", "samples").usingJobData("name", "Everyone") - .storeDurably().build(); + return JobBuilder.newJob(SampleJob.class) + .withIdentity("anotherJob", "samples") + .usingJobData("name", "Everyone") + .storeDurably() + .build(); } @Bean public Trigger everyTwoSecTrigger() { - return TriggerBuilder.newTrigger().forJob("helloJob", "samples").withIdentity("sampleTrigger") - .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build(); + return TriggerBuilder.newTrigger() + .forJob("helloJob", "samples") + .withIdentity("sampleTrigger") + .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()) + .build(); } @Bean public Trigger everyDayTrigger() { - return TriggerBuilder.newTrigger().forJob("helloJob", "samples").withIdentity("every-day", "samples") - .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)).build(); + return TriggerBuilder.newTrigger() + .forJob("helloJob", "samples") + .withIdentity("every-day", "samples") + .withSchedule(SimpleScheduleBuilder.repeatHourlyForever(24)) + .build(); } @Bean public Trigger threeAmWeekdaysTrigger() { - return TriggerBuilder.newTrigger().forJob("anotherJob", "samples").withIdentity("3am-weekdays", "samples") - .withSchedule(CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5)).build(); + return TriggerBuilder.newTrigger() + .forJob("anotherJob", "samples") + .withIdentity("3am-weekdays", "samples") + .withSchedule(CronScheduleBuilder.atHourAndMinuteOnGivenDaysOfWeek(3, 0, 1, 2, 3, 4, 5)) + .build(); } @Bean public Trigger onceAWeekTrigger() { - return TriggerBuilder.newTrigger().forJob("anotherJob", "samples").withIdentity("once-a-week", "samples") - .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) - .build(); + return TriggerBuilder.newTrigger() + .forJob("anotherJob", "samples") + .withIdentity("once-a-week", "samples") + .withSchedule(CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(1)) + .build(); } @Bean public Trigger everyHourWorkingHourTuesdayAndThursdayTrigger() { - return TriggerBuilder.newTrigger().forJob("helloJob", "samples").withIdentity("every-hour-tue-thu", "samples") - .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() - .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) - .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) - .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)).withInterval(1, IntervalUnit.HOUR)) - .build(); + return TriggerBuilder.newTrigger() + .forJob("helloJob", "samples") + .withIdentity("every-hour-tue-thu", "samples") + .withSchedule(DailyTimeIntervalScheduleBuilder.dailyTimeIntervalSchedule() + .onDaysOfTheWeek(Calendar.TUESDAY, Calendar.THURSDAY) + .startingDailyAt(TimeOfDay.hourAndMinuteOfDay(9, 0)) + .endingDailyAt(TimeOfDay.hourAndMinuteOfDay(18, 0)) + .withInterval(1, IntervalUnit.HOUR)) + .build(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java index 8cd28f34b4..80dafc706e 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-quartz/src/test/java/smoketest/quartz/SampleQuartzApplicationWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -87,7 +87,7 @@ class SampleQuartzApplicationWebTests { @Test void quartzTriggerDetailWhenNameDoesNotExistReturns404() { ResponseEntity<String> response = this.restTemplate - .getForEntity("/actuator/quartz/triggers/samples/does-not-exist", String.class); + .getForEntity("/actuator/quartz/triggers/samples/does-not-exist", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java index 2b170de1ba..20e777f81b 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-client/src/test/java/smoketest/oauth2/client/SampleReactiveOAuth2ClientApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -34,14 +34,24 @@ class SampleReactiveOAuth2ClientApplicationTests { @Test void everythingShouldRedirectToLogin() { - this.webTestClient.get().uri("/").exchange().expectStatus().isFound().expectHeader().valueEquals("Location", - "/login"); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .isFound() + .expectHeader() + .valueEquals("Location", "/login"); } @Test void loginShouldHaveBothOAuthClientsToChooseFrom() { - byte[] body = this.webTestClient.get().uri("/login").exchange().expectStatus().isOk().returnResult(String.class) - .getResponseBodyContent(); + byte[] body = this.webTestClient.get() + .uri("/login") + .exchange() + .expectStatus() + .isOk() + .returnResult(String.class) + .getResponseBodyContent(); String bodyString = new String(body); assertThat(bodyString).contains("/oauth2/authorization/yahoo"); assertThat(bodyString).contains("/oauth2/authorization/github-client-1"); @@ -50,8 +60,13 @@ class SampleReactiveOAuth2ClientApplicationTests { @Test void actuatorShouldBeSecuredByOAuth() { - this.webTestClient.get().uri("/actuator/health").exchange().expectStatus().isFound().expectHeader() - .valueEquals("Location", "/login"); + this.webTestClient.get() + .uri("/actuator/health") + .exchange() + .expectStatus() + .isFound() + .expectHeader() + .valueEquals("Location", "/login"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java index a0e64e4e16..f6f7e1bad5 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,14 +58,25 @@ class SampleReactiveOAuth2ResourceServerApplicationTests { @Test void getWhenValidTokenShouldBeOk() { - this.webTestClient.get().uri("/").headers((headers) -> headers.setBearerAuth(VALID_TOKEN)).exchange() - .expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, subject!"); + this.webTestClient.get() + .uri("/") + .headers((headers) -> headers.setBearerAuth(VALID_TOKEN)) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Hello, subject!"); } @Test void getWhenNoTokenShouldBeUnauthorized() { - this.webTestClient.get().uri("/").exchange().expectStatus().isUnauthorized().expectHeader() - .valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); + this.webTestClient.get() + .uri("/") + .exchange() + .expectStatus() + .isUnauthorized() + .expectHeader() + .valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); } private static MockResponse mockResponse() { @@ -87,7 +98,8 @@ class SampleReactiveOAuth2ResourceServerApplicationTests { + "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq" + "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}"; return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .setResponseCode(200).setBody(body); + .setResponseCode(200) + .setBody(body); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java index c526f89d5e..370a64d84a 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-rsocket/src/test/java/smoketest/rsocket/SampleRSocketApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,13 +50,14 @@ class SampleRSocketApplicationTests { @Test void rSocketEndpoint() { RSocketRequester requester = this.builder - .rsocketStrategies((builder) -> builder.encoder(new SimpleAuthenticationEncoder())) - .setupMetadata(new UsernamePasswordMetadata("user", "password"), - MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString())) - .tcp("localhost", this.port); + .rsocketStrategies((builder) -> builder.encoder(new SimpleAuthenticationEncoder())) + .setupMetadata(new UsernamePasswordMetadata("user", "password"), + MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString())) + .tcp("localhost", this.port); Mono<Project> result = requester.route("find.project.spring-boot").retrieveMono(Project.class); - StepVerifier.create(result).assertNext((project) -> assertThat(project.getName()).isEqualTo("spring-boot")) - .verifyComplete(); + StepVerifier.create(result) + .assertNext((project) -> assertThat(project.getName()).isEqualTo("spring-boot")) + .verifyComplete(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java index 1612b9d294..365e617c14 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/main/java/smoketest/secure/jersey/SecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -32,10 +32,16 @@ public class SecurityConfiguration { @Bean public InMemoryUserDetailsManager inMemoryUserDetailsManager() { return new InMemoryUserDetailsManager( - User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER") - .build(), - User.withDefaultPasswordEncoder().username("admin").password("admin") - .authorities("ROLE_ACTUATOR", "ROLE_USER").build()); + User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .authorities("ROLE_USER") + .build(), + User.withDefaultPasswordEncoder() + .username("admin") + .password("admin") + .authorities("ROLE_ACTUATOR", "ROLE_USER") + .build()); } @Bean @@ -43,7 +49,7 @@ public class SecurityConfiguration { http.authorizeHttpRequests((requests) -> { requests.requestMatchers(EndpointRequest.to("health")).permitAll(); requests.requestMatchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR"); + .hasRole("ACTUATOR"); requests.requestMatchers("/**").hasRole("USER"); }); http.httpBasic(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java index 633f48ac03..c412a5c561 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortAndPathJerseyApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class ManagementPortAndPathJerseyApplicationTests extends AbstractJerseySecureTe @Test void testMissing() { ResponseEntity<String> entity = new TestRestTemplate("admin", "admin") - .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java index 355f12b98d..5c4676f884 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-jersey/src/test/java/smoketest/secure/jersey/ManagementPortCustomApplicationPathJerseyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -46,7 +46,7 @@ class ManagementPortCustomApplicationPathJerseyTests extends AbstractJerseySecur @Test void actuatorPathOnMainPortShouldNotMatch() { ResponseEntity<String> entity = new TestRestTemplate() - .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); + .getForEntity("http://localhost:" + this.port + "/example/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java index f898c6f2fd..837efbc0b1 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/CorsSampleActuatorApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,14 +42,24 @@ class CorsSampleActuatorApplicationTests { @Test void preflightRequestToEndpointShouldReturnOk() { - this.webClient.options().uri("/actuator/env").header("Origin", "http://localhost:8080") - .header("Access-Control-Request-Method", "GET").exchange().expectStatus().isOk(); + this.webClient.options() + .uri("/actuator/env") + .header("Origin", "http://localhost:8080") + .header("Access-Control-Request-Method", "GET") + .exchange() + .expectStatus() + .isOk(); } @Test void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() { - this.webClient.options().uri("/actuator/env").header("Origin", "http://localhost:9095") - .header("Access-Control-Request-Method", "GET").exchange().expectStatus().isForbidden(); + this.webClient.options() + .uri("/actuator/env") + .header("Origin", "http://localhost:9095") + .header("Access-Control-Request-Method", "GET") + .exchange() + .expectStatus() + .isForbidden(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java index a0cebf047d..0274529374 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/ManagementPortSampleSecureWebFluxTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -56,29 +56,49 @@ class ManagementPortSampleSecureWebFluxTests { @Test void testHome() { - this.webClient.get().uri("http://localhost:" + this.port, String.class).header("Authorization", getBasicAuth()) - .exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello user"); + this.webClient.get() + .uri("http://localhost:" + this.port, String.class) + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Hello user"); } @Test void actuatorPathOnMainPortShouldNotMatch() { - this.webClient.get().uri("http://localhost:" + this.port + "/actuator", String.class).exchange().expectStatus() - .isUnauthorized(); - this.webClient.get().uri("http://localhost:" + this.port + "/actuator/health", String.class).exchange() - .expectStatus().isUnauthorized(); + this.webClient.get() + .uri("http://localhost:" + this.port + "/actuator", String.class) + .exchange() + .expectStatus() + .isUnauthorized(); + this.webClient.get() + .uri("http://localhost:" + this.port + "/actuator/health", String.class) + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testSecureActuator() { - this.webClient.get().uri("http://localhost:" + this.managementPort + "/actuator/env", String.class).exchange() - .expectStatus().isUnauthorized(); + this.webClient.get() + .uri("http://localhost:" + this.managementPort + "/actuator/env", String.class) + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void testInsecureActuator() { String responseBody = this.webClient.get() - .uri("http://localhost:" + this.managementPort + "/actuator/health", String.class).exchange() - .expectStatus().isOk().expectBody(String.class).returnResult().getResponseBody(); + .uri("http://localhost:" + this.managementPort + "/actuator/health", String.class) + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .returnResult() + .getResponseBody(); assertThat(responseBody).contains("\"status\":\"UP\""); } @@ -94,7 +114,7 @@ class ManagementPortSampleSecureWebFluxTests { http.authorizeExchange((exchanges) -> { exchanges.matchers(EndpointRequest.to("health")).permitAll(); exchanges.matchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR"); + .hasRole("ACTUATOR"); exchanges.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll(); exchanges.pathMatchers("/login").permitAll(); exchanges.anyExchange().authenticated(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java index 287acc91f0..c1b329214f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -40,33 +40,54 @@ class SampleSecureWebFluxApplicationTests { @Test void userDefinedMappingsSecureByDefault() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isEqualTo(HttpStatus.UNAUTHORIZED); + this.webClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void healthInsecureByDefault() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk(); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk(); } @Test void otherActuatorsSecureByDefault() { - this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isUnauthorized(); + this.webClient.get() + .uri("/actuator/env") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized(); } @Test void userDefinedMappingsAccessibleOnLogin() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).header("Authorization", getBasicAuth()) - .exchange().expectBody(String.class).isEqualTo("Hello user"); + this.webClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectBody(String.class) + .isEqualTo("Hello user"); } @Test void actuatorsAccessibleOnLogin() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuth()).exchange().expectBody(String.class) - .isEqualTo("{\"status\":\"UP\"}"); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectBody(String.class) + .isEqualTo("{\"status\":\"UP\"}"); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java index 58ba49ad82..cd3d820e33 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure-webflux/src/test/java/smoketest/secure/webflux/SampleSecureWebFluxCustomSecurityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -50,46 +50,82 @@ class SampleSecureWebFluxCustomSecurityTests { @Test void userDefinedMappingsSecure() { - this.webClient.get().uri("/").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isEqualTo(HttpStatus.UNAUTHORIZED); + this.webClient.get() + .uri("/") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void healthDoesNotRequireAuthentication() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk(); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk(); } @Test void actuatorsSecuredByRole() { - this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuth()).exchange().expectStatus().isForbidden(); + this.webClient.get() + .uri("/actuator/env") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isForbidden(); } @Test void actuatorsAccessibleOnCorrectLogin() { - this.webClient.get().uri("/actuator/env").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuthForAdmin()).exchange().expectStatus().isOk(); + this.webClient.get() + .uri("/actuator/env") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuthForAdmin()) + .exchange() + .expectStatus() + .isOk(); } @Test void actuatorExcludedFromEndpointRequestMatcher() { - this.webClient.get().uri("/actuator/mappings").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuth()).exchange().expectStatus().isOk(); + this.webClient.get() + .uri("/actuator/mappings") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuth()) + .exchange() + .expectStatus() + .isOk(); } @Test void staticResourceShouldBeAccessible() { - this.webClient.get().uri("/css/bootstrap.min.css").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk(); + this.webClient.get() + .uri("/css/bootstrap.min.css") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk(); } @Test void actuatorLinksIsSecure() { - this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isUnauthorized(); - this.webClient.get().uri("/actuator").accept(MediaType.APPLICATION_JSON) - .header("Authorization", getBasicAuthForAdmin()).exchange().expectStatus().isOk(); + this.webClient.get() + .uri("/actuator") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isUnauthorized(); + this.webClient.get() + .uri("/actuator") + .accept(MediaType.APPLICATION_JSON) + .header("Authorization", getBasicAuthForAdmin()) + .exchange() + .expectStatus() + .isOk(); } private String getBasicAuth() { @@ -107,10 +143,16 @@ class SampleSecureWebFluxCustomSecurityTests { @Bean MapReactiveUserDetailsService userDetailsService() { return new MapReactiveUserDetailsService( - User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER") - .build(), - User.withDefaultPasswordEncoder().username("admin").password("admin") - .authorities("ROLE_ACTUATOR", "ROLE_USER").build()); + User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .authorities("ROLE_USER") + .build(), + User.withDefaultPasswordEncoder() + .username("admin") + .password("admin") + .authorities("ROLE_ACTUATOR", "ROLE_USER") + .build()); } @Bean @@ -118,7 +160,7 @@ class SampleSecureWebFluxCustomSecurityTests { http.authorizeExchange((exchanges) -> { exchanges.matchers(EndpointRequest.to("health")).permitAll(); exchanges.matchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)) - .hasRole("ACTUATOR"); + .hasRole("ACTUATOR"); exchanges.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll(); exchanges.pathMatchers("/login").permitAll(); exchanges.anyExchange().authenticated(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java index b537ed2a32..c43f79d31f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/main/java/smoketest/secure/SampleSecureApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -36,8 +36,9 @@ public class SampleSecureApplication implements CommandLineRunner { @Override public void run(String... args) throws Exception { - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", - AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); + SecurityContextHolder.getContext() + .setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", + AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); try { System.out.println(this.service.secure()); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java index 0ec91663d2..eb9f779caa 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-secure/src/test/java/smoketest/secure/SampleSecureApplicationTests.java @@ -58,13 +58,14 @@ class SampleSecureApplicationTests { @Test void secure() { assertThatExceptionOfType(AuthenticationException.class) - .isThrownBy(() -> SampleSecureApplicationTests.this.service.secure()); + .isThrownBy(() -> SampleSecureApplicationTests.this.service.secure()); } @Test void authenticated() { - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", - AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); + SecurityContextHolder.getContext() + .setAuthentication(new UsernamePasswordAuthenticationToken("user", "N/A", + AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))); assertThat(this.service.secure()).isEqualTo("Hello Security"); } @@ -78,7 +79,7 @@ class SampleSecureApplicationTests { void denied() { SecurityContextHolder.getContext().setAuthentication(this.authentication); assertThatExceptionOfType(AccessDeniedException.class) - .isThrownBy(() -> SampleSecureApplicationTests.this.service.denied()); + .isThrownBy(() -> SampleSecureApplicationTests.this.service.denied()); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java index 516bb92635..b1ad40bf0d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-servlet/src/test/java/smoketest/servlet/SampleServletApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -55,8 +55,8 @@ class SampleServletApplicationTests { @Test void testHome() { - ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/", - String.class); + ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()) + .getForEntity("/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("Hello World"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java index 90375a4e1d..a268333c24 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-mongo/src/test/java/smoketest/session/mongodb/SampleSessionMongoApplicationTests.java @@ -64,7 +64,7 @@ class SampleSessionMongoApplicationTests { @Container static MongoDBContainer mongo = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(3) - .withStartupTimeout(Duration.ofMinutes(2)); + .withStartupTimeout(Duration.ofMinutes(2)); @DynamicPropertySource static void applicationProperties(DynamicPropertyRegistry registry) { @@ -85,7 +85,7 @@ class SampleSessionMongoApplicationTests { @Test void health() { ResponseEntity<String> entity = this.restTemplate - .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); + .getForEntity("http://localhost:" + this.port + "/actuator/health", String.class); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).contains("maxWireVersion"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java index 438ea6839a..c7ccd4cb02 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-mongo/src/test/java/smoketest/session/SampleSessionWebFluxMongoApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -48,7 +48,7 @@ class SampleSessionWebFluxMongoApplicationTests { @Container private static final MongoDBContainer mongo = new MongoDBContainer(DockerImageNames.mongo()).withStartupAttempts(3) - .withStartupTimeout(Duration.ofMinutes(2)); + .withStartupTimeout(Duration.ofMinutes(2)); @LocalServerPort private int port; @@ -67,20 +67,22 @@ class SampleSessionWebFluxMongoApplicationTests { client.get().header("Authorization", getBasicAuth()).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); + .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); }).flatMap((tuple) -> { String sessionCookie = tuple.getT1(); return client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) - .thenReturn(sessionCookie); + .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) + .thenReturn(sessionCookie); }); - }).delayElement(Duration.ofSeconds(10)) - .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { - assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - return response.releaseBody(); - })).block(Duration.ofSeconds(30)); + }) + .delayElement(Duration.ofSeconds(10)) + .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { + assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + return response.releaseBody(); + })) + .block(Duration.ofSeconds(30)); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java index 9b50b5d3da..62aba02ab6 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-session-webflux-redis/src/test/java/smoketest/session/SampleSessionWebFluxRedisApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -66,20 +66,22 @@ class SampleSessionWebFluxRedisApplicationTests { client.get().header("Authorization", getBasicAuth()).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); + .map((sessionId) -> Tuples.of(response.cookies().getFirst("SESSION").getValue(), sessionId)); }).flatMap((tuple) -> { String sessionCookie = tuple.getT1(); return client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); return response.bodyToMono(String.class) - .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) - .thenReturn(sessionCookie); + .doOnNext((sessionId) -> assertThat(sessionId).isEqualTo(tuple.getT2())) + .thenReturn(sessionCookie); }); - }).delayElement(Duration.ofSeconds(10)) - .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { - assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); - return response.releaseBody(); - })).block(Duration.ofSeconds(30)); + }) + .delayElement(Duration.ofSeconds(10)) + .flatMap((sessionCookie) -> client.get().cookie("SESSION", sessionCookie).exchangeToMono((response) -> { + assertThat(response.statusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + return response.releaseBody(); + })) + .block(Duration.ofSeconds(30)); } private String getBasicAuth() { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java index 832b43d6ef..28e8030511 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -59,7 +59,7 @@ class SampleTestApplicationWebIntegrationTests { @Test void test() { assertThat(this.restTemplate.getForEntity("/{username}/vehicle", String.class, "sframework").getStatusCode()) - .isEqualTo(HttpStatus.OK); + .isEqualTo(HttpStatus.OK); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java index 4ba858a629..939b7ff6fb 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/UserEntityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -41,19 +41,19 @@ class UserEntityTests { @Test void createWhenUsernameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new User(null, VIN)) - .withMessage("Username must not be empty"); + .withMessage("Username must not be empty"); } @Test void createWhenUsernameIsEmptyShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new User("", VIN)) - .withMessage("Username must not be empty"); + .withMessage("Username must not be empty"); } @Test void createWhenVinIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new User("sboot", null)) - .withMessage("VIN must not be null"); + .withMessage("VIN must not be null"); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java index 6807862c36..100cdef266 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/domain/VehicleIdentificationNumberTests.java @@ -36,19 +36,19 @@ class VehicleIdentificationNumberTests { @Test void createWhenVinIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber(null)) - .withMessage("VIN must not be null"); + .withMessage("VIN must not be null"); } @Test void createWhenVinIsMoreThan17CharsShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber("012345678901234567")) - .withMessage("VIN must be exactly 17 characters"); + .withMessage("VIN must be exactly 17 characters"); } @Test void createWhenVinIsLessThan17CharsShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> new VehicleIdentificationNumber("0123456789012345")) - .withMessage("VIN must be exactly 17 characters"); + .withMessage("VIN must be exactly 17 characters"); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java index ebd4baf9c2..876faf60fe 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/service/RemoteVehicleDetailsServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -54,13 +54,13 @@ class RemoteVehicleDetailsServiceTests { @Test void getVehicleDetailsWhenVinIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.service.getVehicleDetails(null)) - .withMessage("VIN must not be null"); + .withMessage("VIN must not be null"); } @Test void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")) - .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), MediaType.APPLICATION_JSON)); + .andRespond(withSuccess(getClassPathResource("vehicledetails.json"), MediaType.APPLICATION_JSON)); VehicleDetails details = this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); assertThat(details.getMake()).isEqualTo("Honda"); assertThat(details.getModel()).isEqualTo("Civic"); @@ -70,14 +70,14 @@ class RemoteVehicleDetailsServiceTests { void getVehicleDetailsWhenResultIsNotFoundShouldThrowException() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withStatus(HttpStatus.NOT_FOUND)); assertThatExceptionOfType(VehicleIdentificationNumberNotFoundException.class) - .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); + .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); } @Test void getVehicleDetailsWhenResultIServerErrorShouldThrowException() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")).andRespond(withServerError()); assertThatExceptionOfType(HttpServerErrorException.class) - .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); + .isThrownBy(() -> this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN))); } private ClassPathResource getClassPathResource(String path) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java index 55e3f0158d..6f73fdcbb8 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -57,8 +57,9 @@ class UserVehicleControllerApplicationTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) - .andExpect(content().string("Honda Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java index be22aab13a..e3f2840e3e 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -59,22 +59,25 @@ class UserVehicleControllerTests { @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).andExpect(status().isOk()) - .andExpect(content().string("Honda Civic")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) + .andExpect(status().isOk()) + .andExpect(content().string("Honda Civic")); } @Test void getVehicleWhenRequestingJsonShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) - .andExpect(content().json("{'make':'Honda','model':'Civic'}")); + this.mvc.perform(get("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json("{'make':'Honda','model':'Civic'}")); } @Test void getVehicleWhenRequestingHtmlShouldReturnMakeAndModel() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); - this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) - .andExpect(content().string(containsString("<h1>Honda Civic</h1>"))); + this.mvc.perform(get("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("<h1>Honda Civic</h1>"))); } @Test @@ -86,7 +89,7 @@ class UserVehicleControllerTests { @Test void getVehicleWhenVinNotFoundShouldReturnNotFound() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) - .willThrow(new VehicleIdentificationNumberNotFoundException(VIN)); + .willThrow(new VehicleIdentificationNumberNotFoundException(VIN)); this.mvc.perform(get("/sboot/vehicle")).andExpect(status().isNotFound()); } @@ -94,7 +97,7 @@ class UserVehicleControllerTests { void welcomeCommandLineRunnerShouldNotBeAvailable() { // Since we're a @WebMvcTest WelcomeCommandLineRunner should not be available. Assertions.assertThatThrownBy(() -> this.applicationContext.getBean(WelcomeCommandLineRunner.class)) - .isInstanceOf(NoSuchBeanDefinitionException.class); + .isInstanceOf(NoSuchBeanDefinitionException.class); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java index 649f7feaed..33fd031573 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-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. @@ -59,14 +59,14 @@ class UserVehicleServiceTests { @Test void getVehicleDetailsWhenUsernameIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> this.service.getVehicleDetails(null)) - .withMessage("Username must not be null"); + .withMessage("Username must not be null"); } @Test void getVehicleDetailsWhenUsernameNotFoundShouldThrowException() { given(this.userRepository.findByUsername(anyString())).willReturn(null); assertThatExceptionOfType(UserNameNotFoundException.class) - .isThrownBy(() -> this.service.getVehicleDetails("sboot")); + .isThrownBy(() -> this.service.getVehicleDetails("sboot")); } @Test diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java index 590bddf823..9e429a9321 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-tomcat-multi-connectors/src/test/java/smoketest/tomcat/multiconnector/SampleTomcatTwoConnectorsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -69,7 +69,7 @@ class SampleTomcatTwoConnectorsApplicationTests { assertThat(this.ports.getHttpsPort()).isEqualTo(this.port); assertThat(this.ports.getHttpPort()).isNotEqualTo(this.port); ResponseEntity<String> entity = this.restTemplate - .getForEntity("http://localhost:" + this.ports.getHttpPort() + "/hello", String.class); + .getForEntity("http://localhost:" + this.ports.getHttpPort() + "/hello", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).isEqualTo("hello"); ResponseEntity<String> httpsEntity = this.restTemplate.getForEntity("https://localhost:" + this.port + "/hello", diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java index 377d67eaf8..5be52ecb82 100755 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-groovy-templates/src/test/java/smoketest/groovytemplates/MessageControllerWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,20 +57,23 @@ class MessageControllerWebTests { @Test void testHome() throws Exception { - this.mockMvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string(containsString("<title>Messages"))); + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("<title>Messages"))); } @Test void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) - .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) + .andExpect(status().isFound()) + .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) - .andExpect(content().string(containsString("is required"))); + this.mockMvc.perform(post("/").param("text", "").param("summary", "")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("is required"))); } private static class RegexMatcher extends TypeSafeMatcher<String> { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java index 52b380dfe6..6698caa1b8 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-method-security/src/main/java/smoketest/security/method/SampleMethodSecurityApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -58,8 +58,11 @@ public class SampleMethodSecurityApplication implements WebMvcConfigurer { @Bean public InMemoryUserDetailsManager inMemoryUserDetailsManager() { return new InMemoryUserDetailsManager( - User.withDefaultPasswordEncoder().username("admin").password("admin") - .roles("ADMIN", "USER", "ACTUATOR").build(), + User.withDefaultPasswordEncoder() + .username("admin") + .password("admin") + .roles("ADMIN", "USER", "ACTUATOR") + .build(), User.withDefaultPasswordEncoder().username("user").password("user").roles("USER").build()); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java index a51d82e5db..a112a08d2f 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractErrorPageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -50,7 +50,7 @@ abstract class AbstractErrorPageTests { @Test void testBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrongpassword") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse).isNull(); @@ -68,7 +68,7 @@ abstract class AbstractErrorPageTests { @Test void testPublicNotFoundPageWithCorrectCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Not Found"); @@ -77,7 +77,7 @@ abstract class AbstractErrorPageTests { @Test void testPublicNotFoundPageWithBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrong") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse).isNull(); @@ -86,7 +86,7 @@ abstract class AbstractErrorPageTests { @Test void testCorrectCredentialsWithControllerException() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Internal Server Error"); @@ -95,7 +95,7 @@ abstract class AbstractErrorPageTests { @Test void testCorrectCredentials() { final ResponseEntity<String> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); + .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); response.getBody(); assertThat(response.getBody()).isEqualTo("test"); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java index fe15a379bc..3bf1e9d926 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/AbstractUnauthenticatedErrorPageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -47,7 +47,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrongpassword") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Unauthorized"); @@ -74,7 +74,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testPublicNotFoundPageWithCorrectCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Not Found"); @@ -83,7 +83,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testPublicNotFoundPageWithBadCredentials() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "wrong") - .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/public/notfound", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Unauthorized"); @@ -92,7 +92,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testCorrectCredentialsWithControllerException() { final ResponseEntity<JsonNode> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); + .exchange(this.pathPrefix + "/fail", HttpMethod.GET, null, JsonNode.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); JsonNode jsonResponse = response.getBody(); assertThat(jsonResponse.get("error").asText()).isEqualTo("Internal Server Error"); @@ -101,7 +101,7 @@ abstract class AbstractUnauthenticatedErrorPageTests { @Test void testCorrectCredentials() { final ResponseEntity<String> response = this.testRestTemplate.withBasicAuth("username", "password") - .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); + .exchange(this.pathPrefix + "/test", HttpMethod.GET, null, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()).isEqualTo("test"); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java index 242a2ce226..b3ce51683a 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-secure/src/test/java/smoketest/web/secure/NoSessionErrorPageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,10 +45,10 @@ class NoSessionErrorPageTests extends AbstractErrorPageTests { @Bean SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .authorizeHttpRequests((requests) -> { - requests.requestMatchers("/public/**").permitAll(); - requests.anyRequest().authenticated(); - }); + .authorizeHttpRequests((requests) -> { + requests.requestMatchers("/public/**").permitAll(); + requests.anyRequest().authenticated(); + }); http.httpBasic(); return http.build(); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java index 72f070d63c..3f34b60f8c 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-web-thymeleaf/src/test/java/smoketest/web/thymeleaf/MessageControllerWebTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -57,20 +57,23 @@ class MessageControllerWebTests { @Test void testHome() throws Exception { - this.mockMvc.perform(get("/")).andExpect(status().isOk()) - .andExpect(content().string(containsString("<title>Messages"))); + this.mockMvc.perform(get("/")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("<title>Messages"))); } @Test void testCreate() throws Exception { - this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")).andExpect(status().isFound()) - .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); + this.mockMvc.perform(post("/").param("text", "FOO text").param("summary", "FOO")) + .andExpect(status().isFound()) + .andExpect(header().string("location", RegexMatcher.matches("/[0-9]+"))); } @Test void testCreateValidation() throws Exception { - this.mockMvc.perform(post("/").param("text", "").param("summary", "")).andExpect(status().isOk()) - .andExpect(content().string(containsString("is required"))); + this.mockMvc.perform(post("/").param("text", "").param("summary", "")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("is required"))); } private static class RegexMatcher extends TypeSafeMatcher<String> { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java index 74b09a6dda..f0134cd838 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorDifferentPortTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -42,7 +42,7 @@ class SampleWebFluxApplicationActuatorDifferentPortTests { @Test void linksEndpointShouldBeAvailable() { ResponseEntity<String> entity = new TestRestTemplate("user", getPassword()) - .getForEntity("http://localhost:" + this.managementPort + "/", String.class); + .getForEntity("http://localhost:" + this.managementPort + "/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"_links\""); } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperFalseTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperFalseTests.java index 5db1210165..272a74d548 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperFalseTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperFalseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -40,8 +40,12 @@ class SampleWebFluxApplicationActuatorIsolatedObjectMapperFalseTests { @Test void linksEndpointShouldBeAvailable() { - this.webClient.get().uri("/actuator/startup").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .is5xxServerError(); + this.webClient.get() + .uri("/actuator/startup") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .is5xxServerError(); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperTrueTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperTrueTests.java index 567d5703ec..53ca544608 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperTrueTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationActuatorIsolatedObjectMapperTrueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2022 the original author or authors. + * Copyright 2012-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. @@ -45,8 +45,14 @@ class SampleWebFluxApplicationActuatorIsolatedObjectMapperTrueTests { @Test void linksEndpointShouldBeAvailable() { - this.webClient.get().uri("/actuator/startup").accept(MediaType.APPLICATION_JSON).exchange().expectStatus() - .isOk().expectBody().consumeWith(this::assertExpectedJson); + this.webClient.get() + .uri("/actuator/startup") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .consumeWith(this::assertExpectedJson); } private void assertExpectedJson(EntityExchangeResult<byte[]> result) { diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java index 33722d16d9..50627a0438 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webflux/src/test/java/smoketest/webflux/SampleWebFluxApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-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. @@ -38,21 +38,36 @@ class SampleWebFluxApplicationTests { @Test void testWelcome() { - this.webClient.get().uri("/").accept(MediaType.TEXT_PLAIN).exchange().expectBody(String.class) - .isEqualTo("Hello World"); + this.webClient.get() + .uri("/") + .accept(MediaType.TEXT_PLAIN) + .exchange() + .expectBody(String.class) + .isEqualTo("Hello World"); } @Test void testEcho() { - this.webClient.post().uri("/echo").contentType(MediaType.TEXT_PLAIN).accept(MediaType.TEXT_PLAIN) - .body(Mono.just("Hello WebFlux!"), String.class).exchange().expectBody(String.class) - .isEqualTo("Hello WebFlux!"); + this.webClient.post() + .uri("/echo") + .contentType(MediaType.TEXT_PLAIN) + .accept(MediaType.TEXT_PLAIN) + .body(Mono.just("Hello WebFlux!"), String.class) + .exchange() + .expectBody(String.class) + .isEqualTo("Hello WebFlux!"); } @Test void testActuatorStatus() { - this.webClient.get().uri("/actuator/health").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() - .expectBody().json("{\"status\":\"UP\"}"); + this.webClient.get() + .uri("/actuator/health") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody() + .json("{\"status\":\"UP\"}"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java index 35879f5b0d..22adb1b021 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-webservices/src/test/java/smoketest/webservices/WebServiceServerTestSampleWsApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-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. @@ -64,8 +64,8 @@ class WebServiceServerTestSampleWsApplicationTests { StreamSource source = new StreamSource(new StringReader(request)); this.client.sendRequest(RequestCreators.withPayload(source)).andExpect(ResponseMatchers.noFault()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - then(this.service).should().bookHoliday(dateFormat.parse("2013-10-20"), dateFormat.parse("2013-11-22"), - "John Doe"); + then(this.service).should() + .bookHoliday(dateFormat.parse("2013-10-20"), dateFormat.parse("2013-11-22"), "John Doe"); } } diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java index 94025c34ed..692c87d7e1 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/SampleWebSocketsApplicationTests.java @@ -54,8 +54,8 @@ class SampleWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -67,8 +67,8 @@ class SampleWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java index ebfe8f4428..0f4670c14d 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-jetty/src/test/java/smoketest/websocket/jetty/echo/CustomContainerWebSocketsApplicationTests.java @@ -59,8 +59,8 @@ class CustomContainerWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -72,8 +72,8 @@ class CustomContainerWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java index 689ab81713..47c416eff3 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/SampleWebSocketsApplicationTests.java @@ -54,8 +54,8 @@ class SampleWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -67,8 +67,8 @@ class SampleWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java index 3fe386b496..ccc90761d2 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-tomcat/src/test/java/smoketest/websocket/tomcat/echo/CustomContainerWebSocketsApplicationTests.java @@ -59,8 +59,8 @@ class CustomContainerWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -72,8 +72,8 @@ class CustomContainerWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java index ee66ad9ca3..b7956ce999 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/SampleWebSocketsApplicationTests.java @@ -54,8 +54,8 @@ class SampleWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -67,8 +67,8 @@ class SampleWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java index 515821900d..7869d4cfea 100644 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java +++ b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-websocket-undertow/src/test/java/smoketest/websocket/undertow/echo/CustomContainerWebSocketsApplicationTests.java @@ -59,8 +59,8 @@ class CustomContainerWebSocketsApplicationTests { void echoEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/echo/websocket") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close(); @@ -72,8 +72,8 @@ class CustomContainerWebSocketsApplicationTests { void reverseEndpoint() { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) - .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") - .run("--spring.main.web-application-type=none"); + .properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse") + .run("--spring.main.web-application-type=none"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close();