diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b38bef2f6..a3b32ad0f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -26,7 +26,7 @@ jobs: - name: Set up Java uses: actions/setup-java@v5 with: - java-version: 11 + java-version: 21 distribution: 'temurin' - name: Setup Gradle diff --git a/.github/workflows/early-access.yml b/.github/workflows/early-access.yml index ddf6aaf6d..460dcd09c 100644 --- a/.github/workflows/early-access.yml +++ b/.github/workflows/early-access.yml @@ -19,7 +19,7 @@ jobs: - name: Set up Java uses: actions/setup-java@v5 with: - java-version: 11 + java-version: 21 distribution: 'temurin' - name: Setup Gradle diff --git a/.travis.yml b/.travis.yml index b37531a29..0d8f20a36 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,6 +19,8 @@ script: jobs: include: + - jdk: openjdk21 + - jdk: openjdk17 - jdk: openjdk11 diff --git a/build.gradle b/build.gradle index 9a3787aa2..248290743 100644 --- a/build.gradle +++ b/build.gradle @@ -1,16 +1,11 @@ -import java.time.format.DateTimeFormatter - plugins { id "io.github.gradle-nexus.publish-plugin" version "$nexusPublishPluginVersion" id 'com.github.ben-manes.versions' version "$versionsPluginVersion" - id 'org.ajoberstar.grgit' version "$grgitVersion" id 'org.jreleaser' version "$jreleaserVersion" apply false id "eclipse" id "idea" } -def buildTimeAndDate = grgit.head().dateTime - // common variables ext { isTravis = (System.getenv("TRAVIS") == "true") @@ -23,8 +18,6 @@ ext { sonarDefaultProjectKey = "org.jbake:jbake-base:jbake-core" sonarURL = System.getenv("SONARHOST") ?: sonarDefaultURL sonarProjectKey = System.getenv("SONARPROJECTKEY") ?: sonarDefaultProjectKey - buildDate = buildTimeAndDate.format(DateTimeFormatter.ofPattern('yyyy-MM-dd')) - buildTime = buildTimeAndDate.format(DateTimeFormatter.ofPattern('HH:mm:ss.SSSZ')) isReleaseVersion = !version.endsWith("SNAPSHOT") } diff --git a/buildSrc/src/main/groovy/org/jbake/convention/org.jbake.convention.java-common.gradle b/buildSrc/src/main/groovy/org/jbake/convention/org.jbake.convention.java-common.gradle index 0b91690b6..cfce84fac 100644 --- a/buildSrc/src/main/groovy/org/jbake/convention/org.jbake.convention.java-common.gradle +++ b/buildSrc/src/main/groovy/org/jbake/convention/org.jbake.convention.java-common.gradle @@ -1,3 +1,6 @@ +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter + plugins { id 'java' id 'jacoco' @@ -15,26 +18,22 @@ dependencies { implementation "ch.qos.logback:logback-classic:$logbackVersion" implementation "ch.qos.logback:logback-core:$logbackVersion" - testImplementation "org.junit-pioneer:junit-pioneer:$junitPioneer" - testImplementation "org.junit.jupiter:junit-jupiter-api:$junit5Version" - testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junit5Version" - // compatibility for Junit 4 test - testCompileOnly "junit:junit:$junit4Version" - testRuntimeOnly "org.junit.vintage:junit-vintage-engine:$junit5Version" + testImplementation(platform("org.junit:junit-bom:$junit5Version")) + testImplementation('org.junit.jupiter:junit-jupiter') + testRuntimeOnly('org.junit.platform:junit-platform-launcher') testImplementation "org.assertj:assertj-core:$assertjCoreVersion" testImplementation "org.mockito:mockito-core:$mockitoVersion" testImplementation "org.mockito:mockito-junit-jupiter:$mockitoVersion" - testImplementation "org.itsallcode:junit5-system-extensions:$junit5SystemExtVersion" } -tasks.withType(JavaCompile) { - sourceCompatibility = 1.8 - targetCompatibility = 1.8 +tasks.withType(JavaCompile).configureEach { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } //set jvm for all Test tasks (like test and smokeTest) -tasks.withType(Test) { +tasks.withType(Test).configureEach { def args = ['-Xms512m', '-Xmx3g', '-Dorientdb.installCustomFormatter=false=false', '-Djna.nosys=true'] @@ -45,30 +44,73 @@ tasks.withType(Test) { if (JavaVersion.current().java9Compatible) { args << '-XX:MaxDirectMemorySize=2g' } - jvmArgs args + jvmArgs = args } -task javadocJar(type: Jar) { +tasks.register("javadocJar", Jar) { archiveClassifier.set('javadoc') from javadoc } -task sourcesJar(type: Jar) { - archiveClassifier.set('sources') +tasks.register("sourcesJar", Jar) { + + it.archiveClassifier.set('sources') from sourceSets.main.allSource } -tasks.withType(AbstractArchiveTask) { +tasks.withType(AbstractArchiveTask).configureEach { preserveFileTimestamps = false reproducibleFileOrder = true } +tasks.register("commitBuildAndDate", Exec) { + group = "build" + description = "determine build date and time from last commit" + + executable "git" + args "show", "-s", "--format=%cI", "HEAD" + + standardOutput = new ByteArrayOutputStream() + + ext.commitDate = { + def zonedDateTime = ZonedDateTime.parse(standardOutput.toString().trim()) + return zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss'['VV']'")) + } + + ext.date = { + def zonedDateTime = ZonedDateTime.parse(standardOutput.toString().trim()) + return zonedDateTime.format(DateTimeFormatter.ofPattern('yyyy-MM-dd')) + } + + ext.time = { + def zonedDateTime = ZonedDateTime.parse(standardOutput.toString().trim()) + return zonedDateTime.format(DateTimeFormatter.ofPattern('HH:mm:ss.SSSZ')) + } +} + +tasks.register("commitHash", Exec) { + group = "build" + description = "determine build commit hash for last commit" + + executable "git" + args "show", "-s", "--format=%h", "HEAD" + + standardOutput = new ByteArrayOutputStream() + + ext.abbreviated = { + return standardOutput.toString().trim() + } +} + +processResources.dependsOn(tasks.commitBuildAndDate) +processResources.dependsOn(tasks.commitHash) + test { useJUnitPlatform() testLogging { events "passed", "skipped", "failed" - exceptionFormat "full" + exceptionFormat = "full" } jacoco { @@ -89,7 +131,7 @@ jacocoTestReport { jacocoTestReport.dependsOn test -tasks.withType(Checkstyle) { +tasks.withType(Checkstyle).configureEach { reports { xml.required.set false html.required.set true diff --git a/gradle.properties b/gradle.properties index b1554c042..f9e6b4357 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,55 +7,48 @@ issues = https://github.com/jbake-org/jbake/issues vcs = https://github.com/jbake-org/jbake/ # runtime dependencies -asciidoctorjVersion = 2.5.7 -asciidoctorjDiagramVersion = 2.2.1 +asciidoctorjVersion = 3.0.1 +asciidoctorjDiagramVersion = 3.0.1 args4jVersion = 2.33 -commonsIoVersion = 2.11.0 -commonsConfigurationVersion = 2.7 -commonsBeanutilsVersion = 1.9.4 -commonsLangVersion = 3.12.0 -commonsVfs2Version = 2.9.0 -freemarkerVersion = 2.3.31 -flexmarkVersion = 0.62.2 -groovyVersion = 3.0.9 -jettyServerVersion = 9.4.44.v20210927 +commonsIoVersion = 2.21.0 +commonsConfigurationVersion = 2.12.0 +commonsBeanutilsVersion = 1.11.0 +commonsLangVersion = 3.19.0 +commonsVfs2Version = 2.10.0 +freemarkerVersion = 2.3.34 +flexmarkVersion = 0.64.8 +groovyVersion = 3.0.25 +jettyServerVersion = 11.0.26 jsonSimpleVersion = 1.1.1 jade4jVersion = 1.3.2 -jsoupVersion = 1.14.3 -jgitVersion = 6.0.0.202111291000-r -logbackVersion = 1.2.10 +jsoupVersion = 1.21.2 +jgitVersion = 7.4.0.202509020913-r +logbackVersion = 1.5.21 orientDbVersion = 3.1.20 -pebbleVersion = 3.1.5 -slf4jVersion = 1.7.32 -snakeYamlVersion = 1.30 -thymeleafVersion = 3.0.14.RELEASE -picocli = 4.6.2 +pebbleVersion = 3.2.4 +slf4jVersion = 2.0.17 +snakeYamlVersion = 2.5 +thymeleafVersion = 3.1.3.RELEASE +picocli = 4.7.7 # testing dependencies -junit4Version = 4.13.2 -junit5Version = 5.8.2 -junit5SystemExtVersion = 1.2.0 -junitPioneer = 1.5.0 -assertjCoreVersion = 3.21.0 -mockitoVersion = 4.2.0 +junit5Version = 5.14.1 +assertjCoreVersion = 3.27.6 +mockitoVersion = 5.20.0 # build dependencies -jacocoVersion = 0.8.7 -grgitVersion = 4.1.1 -nexusPublishPluginVersion = 1.1.0 -versionsPluginVersion = 0.40.0 -optionalBaseVersion = 7.0.0 -jreleaserVersion = 0.10.0 -mavenPluginDevVersion = 0.3.1 +jacocoVersion = 0.8.13 +nexusPublishPluginVersion = 2.0.0 +versionsPluginVersion = 0.53.0 +optionalBaseVersion = 10.0.1 +jreleaserVersion = 1.21.0 +mavenPluginDevVersion = 1.0.3 # jbake-maven-plugin dependencies -mavenVersion = 3.8.4 -mavenAnnotationsVersion = 3.6.2 -sparkVersion = 2.9.3 +mavenVersion = 3.9.11 +mavenAnnotationsVersion = 3.15.2 +sparkVersion = 2.9.4 org.gradle.caching=true -org.gradle.parallel=true -org.gradle.configureondemand = true org.gradle.vfs.watch = true - diff --git a/gradle/application.gradle b/gradle/application.gradle index 165c9bb04..714a77f92 100644 --- a/gradle/application.gradle +++ b/gradle/application.gradle @@ -1,7 +1,7 @@ -mainClassName = "org.jbake.launcher.Main" -applicationName = "jbake" - -def examplesBase = "$project.buildDir/examples" +application { + mainClass = "org.jbake.launcher.Main" + applicationName = "jbake" +} def exampleRepositories = [ "example_project_freemarker": "https://github.com/jbake-org/jbake-example-project-freemarker.git", @@ -14,27 +14,24 @@ def exampleRepositories = [ //create clone and Zip Task for each repository exampleRepositories.each { name, repository -> - task "clone_${name}Repository"() { + tasks.register("clone_${name}Repository", Exec) { group = "distribution" - description "Clone jbake ${name} example project repository" - - def repositoryName = "$examplesBase/$name" + description = "Clone jbake ${name} example project repository" + def repositoryName = "${project.layout.buildDirectory.asFile.get()}/examples/$name" - outputs.dir repositoryName + outputs.dir(repositoryName) - doLast { - grgit.clone(dir: repositoryName, uri: repository) - } + executable "git" + args "clone", "$repository", "$repositoryName" } - task "${name}Zip"(type: Zip) { - group "distribution" - description "Zip $name repository" + tasks.register("${name}Zip", Zip) { + group = "distribution" + description = "Zip $name repository" - archiveBaseName = name - archiveFileName = "${archiveBaseName.get()}.zip" + archiveFileName = "${name}.zip" - from project.tasks.getByName("clone_${name}Repository").outputs + from project.tasks.named("clone_${name}Repository").get().outputs exclude 'README.md' exclude 'LICENSE' exclude '.git' diff --git a/gradle/maven-publishing.gradle b/gradle/maven-publishing.gradle index f5fb4f554..e0bb12f09 100644 --- a/gradle/maven-publishing.gradle +++ b/gradle/maven-publishing.gradle @@ -69,19 +69,17 @@ publishing { jar { manifest { - attributes( - 'Built-By': System.properties['user.name'], - 'Created-By': "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})".toString(), - 'Build-Date': buildDate, - 'Build-Time': buildTime, - 'Specification-Title': project.name, - 'Specification-Version': project.version, - 'Specification-Vendor': project.name, - 'Implementation-Title': project.name, - 'Implementation-Version': project.version, - 'Implementation-Vendor': project.name - ) + attributes.putIfAbsent('Built-By', System.properties['user.name']) + attributes.putIfAbsent('Created-By', "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})") + attributes.putIfAbsent('Specification-Title', project.name) + attributes.putIfAbsent('Specification-Version', project.version) + attributes.putIfAbsent('Specification-Vendor', project.name) + attributes.putIfAbsent('Implementation-Title', project.name) + attributes.putIfAbsent('Implementation-Version', project.version) + attributes.putIfAbsent('Implementation-Vendor', project.name) + } + doFirst { + manifest.attributes.putIfAbsent('Build-Date',commitBuildAndDate.date()) + manifest.attributes.putIfAbsent('Build-Time',commitBuildAndDate.time()) } } - - diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c02..8bdaf60c7 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2e6e5897b..bad7c2462 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c8..ef07e0162 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,81 +15,115 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar +CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd32c..5eed7ee84 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,89 +1,94 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/jbake-core/build.gradle b/jbake-core/build.gradle index 626a11a6b..789e84417 100644 --- a/jbake-core/build.gradle +++ b/jbake-core/build.gradle @@ -1,9 +1,6 @@ -import java.time.format.DateTimeFormatter - plugins { id "org.jbake.convention.java-common" id 'java-library' - id 'nebula.optional-base' version "$optionalBaseVersion" } apply from: "$rootDir/gradle/maven-publishing.gradle" @@ -33,34 +30,35 @@ dependencies { api "commons-io:commons-io:$commonsIoVersion" api "org.apache.commons:commons-configuration2:$commonsConfigurationVersion" implementation "commons-beanutils:commons-beanutils:$commonsBeanutilsVersion" - implementation "org.apache.commons:commons-vfs2:$commonsVfs2Version", optional + implementation "org.apache.commons:commons-vfs2:$commonsVfs2Version" implementation "org.apache.commons:commons-lang3:$commonsLangVersion" implementation("com.googlecode.json-simple:json-simple:$jsonSimpleVersion") { exclude group: "junit", module: "junit" } implementation "com.orientechnologies:orientdb-core:$orientDbVersion" - api "org.asciidoctor:asciidoctorj:$asciidoctorjVersion", optional - api "org.codehaus.groovy:groovy:$groovyVersion", optional - api "org.codehaus.groovy:groovy-templates:$groovyVersion", optional - api "org.codehaus.groovy:groovy-dateutil:$groovyVersion", optional - api "org.freemarker:freemarker:$freemarkerVersion", optional - api "org.thymeleaf:thymeleaf:$thymeleafVersion", optional - api "de.neuland-bfi:jade4j:$jade4jVersion", optional - api "com.vladsch.flexmark:flexmark:$flexmarkVersion", optional - api "com.vladsch.flexmark:flexmark-profile-pegdown:$flexmarkVersion", optional - api "io.pebbletemplates:pebble:$pebbleVersion", optional + api "org.asciidoctor:asciidoctorj:$asciidoctorjVersion" + api "org.codehaus.groovy:groovy:$groovyVersion" + api "org.codehaus.groovy:groovy-templates:$groovyVersion" + api "org.codehaus.groovy:groovy-dateutil:$groovyVersion" + api "org.freemarker:freemarker:$freemarkerVersion" + api "org.thymeleaf:thymeleaf:$thymeleafVersion" + api "de.neuland-bfi:jade4j:$jade4jVersion" + api "com.vladsch.flexmark:flexmark:$flexmarkVersion" + api "com.vladsch.flexmark:flexmark-profile-pegdown:$flexmarkVersion" + api "io.pebbletemplates:pebble:$pebbleVersion" implementation "org.jsoup:jsoup:$jsoupVersion" - implementation "org.yaml:snakeyaml:$snakeYamlVersion", optional + implementation "org.yaml:snakeyaml:$snakeYamlVersion" // cli specific dependencies - implementation "org.eclipse.jetty:jetty-server:$jettyServerVersion", optional - implementation "info.picocli:picocli:$picocli", optional + implementation "org.eclipse.jetty:jetty-server:$jettyServerVersion" + implementation "info.picocli:picocli:$picocli" } processResources { - filesMatching("default.properties") { - expand jbakeVersion: project.version, - timestamp: grgit.head().dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss'['VV']'")), - gitHash: grgit.head().abbreviatedId - } + inputs.property("jbake.version", project.version) + filesMatching("default.properties") { + expand jbakeVersion: inputs.properties.get("jbake.version"), + timestamp: () -> commitBuildAndDate.date(), + gitHash: () -> commitHash.abbreviated() + } } diff --git a/jbake-core/src/main/java/org/jbake/launcher/BakeOff.java b/jbake-core/src/main/java/org/jbake/launcher/BakeOff.java new file mode 100644 index 000000000..29bd60a29 --- /dev/null +++ b/jbake-core/src/main/java/org/jbake/launcher/BakeOff.java @@ -0,0 +1,10 @@ +package org.jbake.launcher; + +public final class BakeOff { + + private BakeOff() {} + + public static void exit(int status) { + System.exit(status); + } +} diff --git a/jbake-core/src/main/java/org/jbake/launcher/Main.java b/jbake-core/src/main/java/org/jbake/launcher/Main.java index c244848f7..30ee9beb9 100644 --- a/jbake-core/src/main/java/org/jbake/launcher/Main.java +++ b/jbake-core/src/main/java/org/jbake/launcher/Main.java @@ -1,6 +1,5 @@ package org.jbake.launcher; -import org.apache.commons.configuration2.ex.ConfigurationException; import org.jbake.app.FileUtil; import org.jbake.app.JBakeException; import org.jbake.app.configuration.JBakeConfiguration; @@ -21,8 +20,6 @@ */ public class Main { - private static final String USAGE_PREFIX = "Usage: jbake"; - private static final String ALT_USAGE_PREFIX = " or jbake"; private final Baker baker; private final JettyServer jettyServer; private final BakeWatcher watcher; @@ -64,7 +61,7 @@ public static void main(final String[] args) { if (e.getCause() instanceof MissingParameterException) { Main.printUsage(); } - System.exit(e.getExit()); + BakeOff.exit(e.getExit()); } } diff --git a/jbake-core/src/main/java/org/jbake/model/DocumentModel.java b/jbake-core/src/main/java/org/jbake/model/DocumentModel.java index 99fd559cb..295f8c170 100644 --- a/jbake-core/src/main/java/org/jbake/model/DocumentModel.java +++ b/jbake-core/src/main/java/org/jbake/model/DocumentModel.java @@ -14,7 +14,7 @@ public static DocumentModel createDefaultDocumentModel() { } public String getBody() { - return (String) get(ModelAttributes.BODY); + return get(ModelAttributes.BODY).toString(); } public void setBody(String body) { diff --git a/jbake-core/src/main/java/org/jbake/parser/AsciidoctorEngine.java b/jbake-core/src/main/java/org/jbake/parser/AsciidoctorEngine.java index a5b106895..4ffc00234 100644 --- a/jbake-core/src/main/java/org/jbake/parser/AsciidoctorEngine.java +++ b/jbake-core/src/main/java/org/jbake/parser/AsciidoctorEngine.java @@ -1,23 +1,30 @@ package org.jbake.parser; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.ReentrantReadWriteLock; + import org.asciidoctor.Asciidoctor; -import org.asciidoctor.AttributesBuilder; +import org.asciidoctor.Attributes; import org.asciidoctor.Options; -import org.asciidoctor.ast.DocumentHeader; +import org.asciidoctor.ast.Document; import org.asciidoctor.jruby.AsciidoctorJRuby; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.model.DocumentModel; +import org.jruby.RubyArray; +import org.jruby.RubyBasicObject; +import org.jruby.RubyString; +import org.jruby.RubySymbol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import static org.asciidoctor.AttributesBuilder.attributes; -import static org.asciidoctor.OptionsBuilder.options; import static org.asciidoctor.SafeMode.UNSAFE; /** @@ -84,15 +91,16 @@ private Asciidoctor getEngine(Options options) { public void processHeader(final ParserContext context) { Options options = getAsciiDocOptionsAndAttributes(context); final Asciidoctor asciidoctor = getEngine(options); - DocumentHeader header = asciidoctor.readDocumentHeader(context.getFile()); + Document header = asciidoctor.loadFile(context.getFile(), options); DocumentModel documentModel = context.getDocumentModel(); - if (header.getDocumentTitle() != null) { - documentModel.setTitle(header.getDocumentTitle().getCombined()); + if (header.getDoctitle() != null) { + documentModel.setTitle(header.getDoctitle()); } Map attributes = header.getAttributes(); for (Map.Entry attribute : attributes.entrySet()) { String key = attribute.getKey(); - Object value = attribute.getValue(); + Object value = rubyAsJavaOrValue(attribute.getValue()); + if (hasJBakePrefix(key)) { String pKey = key.substring(6); @@ -120,7 +128,7 @@ public void processHeader(final ParserContext context) { LOGGER.error("Wrong value of 'jbake-tags'. Expected a String got '{}'", getValueClassName(value)); } } else { - documentModel.put(key, attributes.get(key)); + documentModel.put(key, value); } } } @@ -129,6 +137,18 @@ private boolean canCastToString(Object value) { return value instanceof String; } + private Object rubyAsJavaOrValue(Object value) { + if (value instanceof RubyString) { + return ((RubyString) value).asJavaString(); + } else if (value instanceof RubySymbol) { + return ((RubySymbol) value).asJavaString(); + } else if (value instanceof RubyArray) { + return ((RubyArray) value).toArray(); + } else { + return value; + } + } + private String getValueClassName(Object value) { return (value == null) ? "null" : value.getClass().getCanonicalName(); } @@ -144,8 +164,8 @@ private boolean hasJBakePrefix(String key) { // TODO: write tests with options and attributes @Override public void processBody(ParserContext context) { - StringBuilder body = new StringBuilder(context.getBody().length()); if (!context.hasHeader()) { + StringBuilder body = new StringBuilder(context.getBody().length()); for (String line : context.getFileLines()) { body.append(line).append("\n"); } @@ -163,20 +183,22 @@ private void processAsciiDoc(ParserContext context) { private Options getAsciiDocOptionsAndAttributes(ParserContext context) { JBakeConfiguration config = context.getConfig(); List asciidoctorAttributes = config.getAsciidoctorAttributes(); - final AttributesBuilder attributes = attributes(asciidoctorAttributes.toArray(new String[0])); + Attributes attributes = Attributes.builder().build(); + attributes.setAttributes(asciidoctorAttributes.toArray(new String[0])); if (config.getExportAsciidoctorAttributes()) { final String prefix = config.getAttributesExportPrefixForAsciidoctor(); for (final Iterator it = config.getKeys(); it.hasNext(); ) { final String key = it.next(); if (!key.startsWith("asciidoctor")) { - attributes.attribute(prefix + key.replace(".", "_"), config.get(key)); + attributes.setAttribute(prefix + key.replace(".", "_"), config.get(key)); } } } final List optionsSubset = config.getAsciidoctorOptionKeys(); - final Options options = options().attributes(attributes.get()).get(); + + final Options options = Options.builder().attributes(attributes).build(); for (final String optionKey : optionsSubset) { Object optionValue = config.getAsciidoctorOption(optionKey); diff --git a/jbake-core/src/main/java/org/jbake/template/JadeTemplateEngine.java b/jbake-core/src/main/java/org/jbake/template/JadeTemplateEngine.java index bbbff0bfb..f9187c905 100644 --- a/jbake-core/src/main/java/org/jbake/template/JadeTemplateEngine.java +++ b/jbake-core/src/main/java/org/jbake/template/JadeTemplateEngine.java @@ -11,7 +11,7 @@ import de.neuland.jade4j.template.JadeTemplate; import de.neuland.jade4j.template.TemplateLoader; import org.apache.commons.configuration2.CompositeConfiguration; -import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.text.StringEscapeUtils; import org.jbake.app.ContentStore; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.model.TemplateModel; @@ -105,7 +105,7 @@ public String format(Date date, String pattern) { } public String escape(String s) { - return StringEscapeUtils.escapeHtml(s); + return StringEscapeUtils.escapeHtml4(s); } } } diff --git a/jbake-core/src/main/java/org/jbake/template/PebbleTemplateEngine.java b/jbake-core/src/main/java/org/jbake/template/PebbleTemplateEngine.java index 7a850043c..427625f0e 100644 --- a/jbake-core/src/main/java/org/jbake/template/PebbleTemplateEngine.java +++ b/jbake-core/src/main/java/org/jbake/template/PebbleTemplateEngine.java @@ -1,18 +1,18 @@ package org.jbake.template; -import com.mitchellbosecke.pebble.PebbleEngine; -import com.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.extension.escaper.EscaperExtension; -import com.mitchellbosecke.pebble.loader.FileLoader; -import com.mitchellbosecke.pebble.loader.Loader; -import com.mitchellbosecke.pebble.template.PebbleTemplate; import org.jbake.app.ContentStore; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.model.TemplateModel; import java.io.IOException; import java.io.Writer; -import java.util.Map; + +import io.pebbletemplates.pebble.PebbleEngine; +import io.pebbletemplates.pebble.error.PebbleException; +import io.pebbletemplates.pebble.extension.escaper.EscaperExtension; +import io.pebbletemplates.pebble.loader.FileLoader; +import io.pebbletemplates.pebble.loader.Loader; +import io.pebbletemplates.pebble.template.PebbleTemplate; /** * Renders pages using the Pebble template engine. @@ -28,7 +28,7 @@ public PebbleTemplateEngine(final JBakeConfiguration config, final ContentStore } private void initializeTemplateEngine() { - Loader loader = new FileLoader(); + Loader loader = new FileLoader(); loader.setPrefix(config.getTemplateFolder().getAbsolutePath()); /* diff --git a/jbake-core/src/main/java/org/jbake/template/ThymeleafTemplateEngine.java b/jbake-core/src/main/java/org/jbake/template/ThymeleafTemplateEngine.java index c6cc99dc2..a90c63e54 100644 --- a/jbake-core/src/main/java/org/jbake/template/ThymeleafTemplateEngine.java +++ b/jbake-core/src/main/java/org/jbake/template/ThymeleafTemplateEngine.java @@ -1,7 +1,7 @@ package org.jbake.template; import org.apache.commons.configuration2.CompositeConfiguration; -import org.apache.commons.lang.LocaleUtils; +import org.apache.commons.lang3.LocaleUtils; import org.jbake.app.ContentStore; import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.app.configuration.JBakeConfiguration; diff --git a/jbake-core/src/test/java/org/jbake/app/AsciidocParserTest.java b/jbake-core/src/test/java/org/jbake/app/AsciidocParserTest.java index 7382044f7..ab6e361f3 100644 --- a/jbake-core/src/test/java/org/jbake/app/AsciidocParserTest.java +++ b/jbake-core/src/test/java/org/jbake/app/AsciidocParserTest.java @@ -1,27 +1,27 @@ package org.jbake.app; +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Path; + import org.jbake.TestUtils; import org.jbake.app.configuration.ConfigUtil; import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.model.DocumentModel; -import org.jbake.app.configuration.PropertyList; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.PrintWriter; -import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.jbake.app.configuration.PropertyList.ASCIIDOCTOR_ATTRIBUTES; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; -public class AsciidocParserTest { +class AsciidocParserTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private Path folder; private DefaultJBakeConfiguration config; private Parser parser; @@ -38,13 +38,13 @@ public class AsciidocParserTest { private String validHeader = "title=This is a Title = This is a valid Title\nstatus=draft\ntype=post\ndate=2013-09-02\n~~~~~~"; private String invalidHeader = "title=This is a Title\n~~~~~~"; - @Before - public void createSampleFile() throws Exception { + @BeforeEach + void createSampleFile() throws Exception { rootPath = TestUtils.getTestResourcesAsSourceFolder(); config = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(rootPath); parser = new Parser(config); - asciidocWithSource = folder.newFile("asciidoc-with-source.ad"); + asciidocWithSource = folder.resolve("asciidoc-with-source.ad").toFile(); PrintWriter out = new PrintWriter(asciidocWithSource); out.println(validHeader); out.println("= Hello, AsciiDoc!"); @@ -62,7 +62,7 @@ public void createSampleFile() throws Exception { out.close(); - validAsciidocFile = folder.newFile("valid.ad"); + validAsciidocFile = folder.resolve("valid.ad").toFile(); out = new PrintWriter(validAsciidocFile); out.println(validHeader); out.println("= Hello, AsciiDoc!"); @@ -71,7 +71,7 @@ public void createSampleFile() throws Exception { out.println("JBake now supports AsciiDoc."); out.close(); - invalidAsciiDocFile = folder.newFile("invalid.ad"); + invalidAsciiDocFile = folder.resolve("invalid.ad").toFile(); out = new PrintWriter(invalidAsciiDocFile); out.println(invalidHeader); out.println("= Hello, AsciiDoc!"); @@ -80,7 +80,7 @@ public void createSampleFile() throws Exception { out.println("JBake now supports AsciiDoc."); out.close(); - validAsciiDocFileWithoutHeader = folder.newFile("validwoheader.ad"); + validAsciiDocFileWithoutHeader = folder.resolve("validwoheader.ad").toFile(); out = new PrintWriter(validAsciiDocFileWithoutHeader); out.println("= Hello: AsciiDoc!"); out.println("Test User "); @@ -91,7 +91,7 @@ public void createSampleFile() throws Exception { out.println("JBake now supports AsciiDoc."); out.close(); - invalidAsciiDocFileWithoutHeader = folder.newFile("invalidwoheader.ad"); + invalidAsciiDocFileWithoutHeader = folder.resolve("invalidwoheader.ad").toFile(); out = new PrintWriter(invalidAsciiDocFileWithoutHeader); out.println("= Hello, AsciiDoc!"); out.println("Test User "); @@ -101,7 +101,7 @@ public void createSampleFile() throws Exception { out.println("JBake now supports AsciiDoc."); out.close(); - validAsciiDocFileWithHeaderInContent = folder.newFile("validheaderincontent.ad"); + validAsciiDocFileWithHeaderInContent = folder.resolve("validheaderincontent.ad").toFile(); out = new PrintWriter(validAsciiDocFileWithHeaderInContent); out.println("= Hello, AsciiDoc!"); out.println("Test User "); @@ -121,7 +121,7 @@ public void createSampleFile() throws Exception { out.println("----"); out.close(); - validAsciiDocFileWithoutJBakeMetaData = folder.newFile("validwojbakemetadata.ad"); + validAsciiDocFileWithoutJBakeMetaData = folder.resolve("validwojbakemetadata.ad").toFile(); out = new PrintWriter(validAsciiDocFileWithoutJBakeMetaData); out.println("= Hello: AsciiDoc!"); out.println("Test User "); @@ -133,78 +133,78 @@ public void createSampleFile() throws Exception { @Test - public void parseAsciidocFileWithPrettifyAttribute() { + void parseAsciidocFileWithPrettifyAttribute() { - config.setProperty(ASCIIDOCTOR_ATTRIBUTES.getKey(),"source-highlighter=prettify"); + config.setProperty(ASCIIDOCTOR_ATTRIBUTES.getKey(), "source-highlighter=prettify"); DocumentModel map = parser.processFile(asciidocWithSource); - Assert.assertNotNull(map); - Assert.assertEquals("draft", map.getStatus()); - Assert.assertEquals("post", map.getType()); + assertNotNull(map); + assertEquals("draft", map.getStatus()); + assertEquals("post", map.getType()); assertThat(map.getBody()) - .contains("class=\"paragraph\"") - .contains("

JBake now supports AsciiDoc.

") - .contains("class=\"prettyprint highlight\""); + .contains("class=\"paragraph\"") + .contains("

JBake now supports AsciiDoc.

") + .contains("class=\"prettyprint highlight\""); assertThat(map.getBody()).doesNotContain("I Love Jbake"); System.out.println(map.getBody()); } @Test - public void parseAsciidocFileWithCustomAttribute() { + void parseAsciidocFileWithCustomAttribute() { - config.setProperty(ASCIIDOCTOR_ATTRIBUTES.getKey(),"source-highlighter=prettify,testattribute=I Love Jbake"); + config.setProperty(ASCIIDOCTOR_ATTRIBUTES.getKey(), "source-highlighter=prettify,testattribute=I Love Jbake"); DocumentModel map = parser.processFile(asciidocWithSource); - Assert.assertNotNull(map); - Assert.assertEquals("draft", map.getStatus()); - Assert.assertEquals("post", map.getType()); + assertNotNull(map); + assertEquals("draft", map.getStatus()); + assertEquals("post", map.getType()); assertThat(map.getBody()) - .contains("I Love Jbake") - .contains("class=\"prettyprint highlight\""); + .contains("I Love Jbake") + .contains("class=\"prettyprint highlight\""); System.out.println(map.getBody()); } @Test - public void parseValidAsciiDocFile() { + void parseValidAsciiDocFile() { DocumentModel map = parser.processFile(validAsciidocFile); - Assert.assertNotNull(map); - Assert.assertEquals("draft", map.getStatus()); - Assert.assertEquals("post", map.getType()); + assertNotNull(map); + assertEquals("draft", map.getStatus()); + assertEquals("post", map.getType()); assertThat(map.getBody()) .contains("class=\"paragraph\"") .contains("

JBake now supports AsciiDoc.

"); } @Test - public void parseInvalidAsciiDocFile() { + void parseInvalidAsciiDocFile() { DocumentModel map = parser.processFile(invalidAsciiDocFile); - Assert.assertNull(map); + assertNull(map); } @Test - public void parseValidAsciiDocFileWithoutHeader() { + void parseValidAsciiDocFileWithoutHeader() { DocumentModel map = parser.processFile(validAsciiDocFileWithoutHeader); - Assert.assertNotNull(map); - Assert.assertEquals("Hello: AsciiDoc!", map.get("title")); - Assert.assertEquals("published", map.getStatus()); - Assert.assertEquals("page", map.getType()); + assertNotNull(map); + assertEquals("Hello: AsciiDoc!", map.get("title")); + assertEquals("published", map.getStatus()); + assertEquals("page", map.getType()); assertThat(map.getBody()) .contains("class=\"paragraph\"") .contains("

JBake now supports AsciiDoc.

"); } @Test - public void parseInvalidAsciiDocFileWithoutHeader() { + void parseInvalidAsciiDocFileWithoutHeader() { DocumentModel map = parser.processFile(invalidAsciiDocFileWithoutHeader); - Assert.assertNull(map); + assertNull(map); } @Test - public void parseValidAsciiDocFileWithExampleHeaderInContent() { + void parseValidAsciiDocFileWithExampleHeaderInContent() { DocumentModel map = parser.processFile(validAsciiDocFileWithHeaderInContent); - Assert.assertNotNull(map); - Assert.assertEquals("published", map.getStatus()); - Assert.assertEquals("page", map.getType()); + assertNotNull(map); + assertEquals("published", map.getStatus()); + assertEquals("page", map.getType()); assertThat(map.getBody()) .contains("class=\"paragraph\"") .contains("

JBake now supports AsciiDoc.

") @@ -217,14 +217,14 @@ public void parseValidAsciiDocFileWithExampleHeaderInContent() { } @Test - public void parseValidAsciiDocFileWithoutJBakeMetaDataUsingDefaultTypeAndStatus() { + void parseValidAsciiDocFileWithoutJBakeMetaDataUsingDefaultTypeAndStatus() { config.setDefaultStatus("published"); config.setDefaultType("page"); Parser parser = new Parser(config); DocumentModel map = parser.processFile(validAsciiDocFileWithoutJBakeMetaData); - Assert.assertNotNull(map); - Assert.assertEquals("published", map.getStatus()); - Assert.assertEquals("page", map.getType()); + assertNotNull(map); + assertEquals("published", map.getStatus()); + assertEquals("page", map.getType()); assertThat(map.getBody()) .contains("

JBake now supports AsciiDoc documents without JBake meta data.

"); } diff --git a/jbake-core/src/test/java/org/jbake/app/AssetTest.java b/jbake-core/src/test/java/org/jbake/app/AssetTest.java index 1f718d706..69f00746a 100644 --- a/jbake-core/src/test/java/org/jbake/app/AssetTest.java +++ b/jbake-core/src/test/java/org/jbake/app/AssetTest.java @@ -1,6 +1,13 @@ package org.jbake.app; -import ch.qos.logback.classic.spi.LoggingEvent; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; + import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.jbake.TestUtils; @@ -10,20 +17,19 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Path; +import ch.qos.logback.classic.spi.LoggingEvent; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class AssetTest extends LoggingTest { +class AssetTest extends LoggingTest { public Path folder; private DefaultJBakeConfiguration config; @@ -31,7 +37,7 @@ public class AssetTest extends LoggingTest { @BeforeEach - public void setup(@TempDir Path folder) throws Exception { + void setup(@TempDir Path folder) throws Exception { fixtureDir = new File(this.getClass().getResource("/fixture").getFile()); this.folder = folder; config = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(fixtureDir); @@ -41,7 +47,7 @@ public void setup(@TempDir Path folder) throws Exception { @Test - public void testCopy() throws Exception { + void testCopy() throws Exception { Asset asset = new Asset(config); asset.copy(); File cssFile = new File(folder.toString() + File.separatorChar + "css" + File.separatorChar + "bootstrap.min.css"); @@ -55,7 +61,7 @@ public void testCopy() throws Exception { } @Test - public void testCopySingleFile() throws Exception { + void testCopySingleFile() throws Exception { Asset asset = new Asset(config); String cssSubPath = File.separatorChar + "css" + File.separatorChar + "bootstrap.min.css"; String contentImgPath = File.separatorChar + "blog" + File.separatorChar + "2013" + File.separatorChar @@ -77,7 +83,7 @@ public void testCopySingleFile() throws Exception { } @Test - public void shouldSkipCopyingSingleFileIfDirectory() throws IOException { + void shouldSkipCopyingSingleFileIfDirectory() throws IOException { Asset asset = new Asset(config); @@ -91,7 +97,7 @@ public void shouldSkipCopyingSingleFileIfDirectory() throws IOException { } @Test - public void shouldLogSkipCopyingSingleFileIfDirectory() throws IOException { + void shouldLogSkipCopyingSingleFileIfDirectory() throws IOException { Asset asset = new Asset(config); File emptyDir = new File(folder.toFile(),"emptyDir"); @@ -107,7 +113,7 @@ public void shouldLogSkipCopyingSingleFileIfDirectory() throws IOException { } @Test - public void testCopyCustomFolder() throws Exception { + void testCopyCustomFolder() throws Exception { config.setAssetFolder(new File(config.getSourceFolder(), "/media")); Asset asset = new Asset(config); asset.copy(); @@ -119,7 +125,7 @@ public void testCopyCustomFolder() throws Exception { } @Test - public void testCopyIgnore() throws Exception { + void testCopyIgnore() throws Exception { File assetFolder = new File(folder.toFile(), "ignoredAssets"); assetFolder.mkdirs(); FileUtils.copyDirectory(new File(this.getClass().getResource("/fixture/ignorables").getFile()), assetFolder); @@ -138,43 +144,57 @@ public void testCopyIgnore() throws Exception { } - /** - * Primary intention is to extend test cases to increase coverage. - * - * @throws Exception - */ @Test - public void testWriteProtected() throws Exception { - File assets = new File(config.getSourceFolder(), "assets"); - File css = new File(folder.toFile(),"css"); - css.mkdir(); - final File cssFile = new File(css, "bootstrap.min.css"); + @DisabledOnOs(OS.WINDOWS) + void testWriteProtectedNotWindows() throws Exception { + File assets = config.getSourceFolder().toPath().resolve("assets").toFile(); + Path css = folder.resolve("css"); + Files.createDirectory(css); + + File cssFile = css.resolve("bootstrap.min.css").toFile(); + FileUtils.touch(cssFile); + + Files.setPosixFilePermissions(css, PosixFilePermissions.fromString("r-xr-xr-x")); + + config.setAssetFolder(assets); + config.setDestinationFolder(folder.toFile()); + Asset asset = new Asset(config); + + asset.copy(); + + Assertions.assertFalse(asset.getErrors().isEmpty(), "At least one error during copy expected"); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void testWriteProtectedOnWindows() throws Exception { + File assets = config.getSourceFolder().toPath().resolve("assets").toFile(); + Path css = folder.resolve("css"); + Files.createDirectory(css); + + File cssFile = css.resolve("bootstrap.min.css").toFile(); FileUtils.touch(cssFile); - cssFile.setReadOnly(); + + Files.setAttribute(cssFile.toPath(), "dos:readonly", true); config.setAssetFolder(assets); config.setDestinationFolder(folder.toFile()); Asset asset = new Asset(config); + asset.copy(); - cssFile.setWritable(true); Assertions.assertFalse(asset.getErrors().isEmpty(), "At least one error during copy expected"); } - /** - * Primary intention is to extend test cases to increase coverage. - * - * @throws Exception - */ @Test - public void testUnlistable() throws Exception { + void testUnlistable() throws Exception { config.setAssetFolder(new File(config.getSourceFolder(), "non-exsitent")); Asset asset = new Asset(config); asset.copy(); } @Test - public void testJBakeIgnoredFolder() { + void testJBakeIgnoredFolder() { URL assetsUrl = this.getClass().getResource("/fixture/assets"); File assets = new File(assetsUrl.getFile()); Asset asset = new Asset(config); @@ -195,7 +215,7 @@ public void testJBakeIgnoredFolder() { } @Test - public void testFooIgnoredFolder() { + void testFooIgnoredFolder() { config.setProperty(PropertyList.IGNORE_FILE.getKey(), ".fooignore"); URL assetsUrl = this.getClass().getResource("/fixture/assets"); @@ -218,7 +238,7 @@ public void testFooIgnoredFolder() { } @Test - public void testCopyAssetsFromContent() { + void testCopyAssetsFromContent() { URL contentUrl = this.getClass().getResource("/fixture/content"); File contents = new File(contentUrl.getFile()); Asset asset = new Asset(config); @@ -242,7 +262,7 @@ public void testCopyAssetsFromContent() { } @Test - public void testIsFileAsset() { + void testIsFileAsset() { File cssAsset = new File(config.getAssetFolder().getAbsolutePath() + File.separatorChar + "css" + File.separatorChar + "bootstrap.min.css"); Assertions.assertTrue(cssAsset.exists()); File contentFile = new File(config.getContentFolder().getAbsolutePath() + File.separatorChar + "about.html"); @@ -259,7 +279,6 @@ private Integer countFiles(File path) { FileFilter filesOnly = FileFilterUtils.fileFileFilter(); FileFilter dirsOnly = FileFilterUtils.directoryFileFilter(); File[] files = path.listFiles(filesOnly); - System.out.println(files); total += files.length; for (File file : path.listFiles(dirsOnly)) { total += countFiles(file); diff --git a/jbake-core/src/test/java/org/jbake/app/ContentStoreIntegrationTest.java b/jbake-core/src/test/java/org/jbake/app/ContentStoreIntegrationTest.java index 06e27877d..15156b77d 100644 --- a/jbake-core/src/test/java/org/jbake/app/ContentStoreIntegrationTest.java +++ b/jbake-core/src/test/java/org/jbake/app/ContentStoreIntegrationTest.java @@ -1,64 +1,66 @@ package org.jbake.app; -import org.apache.commons.vfs2.util.Os; +import java.io.File; +import java.nio.file.Path; + import org.jbake.TestUtils; import org.jbake.app.configuration.ConfigUtil; import org.jbake.app.configuration.DefaultJBakeConfiguration; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; -import java.io.File; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public abstract class ContentStoreIntegrationTest { - @ClassRule - public static TemporaryFolder folder = new TemporaryFolder(); + @TempDir + protected static Path folder; protected static ContentStore db; protected static DefaultJBakeConfiguration config; protected static StorageType storageType = StorageType.MEMORY; protected static File sourceFolder; - @BeforeClass - public static void setUpClass() throws Exception { + @BeforeAll + static void setUpClass() throws Exception { sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); - Assert.assertTrue("Cannot find sample data structure!", sourceFolder.exists()); + assertTrue(sourceFolder.exists(), "Cannot find sample data structure!"); config = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(sourceFolder); config.setSourceFolder(sourceFolder); - Assert.assertEquals(".html", config.getOutputExtension()); + assertEquals(".html", config.getOutputExtension()); config.setDatabaseStore(storageType.toString()); // OrientDB v3.1.x doesn't allow DB name to be a path even though docs say it's allowed - String dbPath = folder.newFolder("documents" + System.currentTimeMillis()).getName(); + String dbPath = folder.resolve("documents" + System.currentTimeMillis()).toFile().getName(); // setting the database path with a colon creates an invalid url for OrientDB. // only one colon is expected. there is no documentation about proper url path for windows available :( - if (Os.isFamily(Os.OS_FAMILY_WINDOWS)) { - dbPath = dbPath.replace(":",""); + if (OS.current() == OS.WINDOWS) { + dbPath = dbPath.replace(":", ""); } config.setDatabasePath(dbPath); db = DBUtil.createDataStore(config); } - @AfterClass - public static void cleanUpClass() { + @AfterAll + static void cleanUpClass() { db.close(); db.shutdown(); } - @Before - public void setUp() { + @BeforeEach + void setUp() { db.startup(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { db.drop(); } diff --git a/jbake-core/src/test/java/org/jbake/app/ContentStoreTest.java b/jbake-core/src/test/java/org/jbake/app/ContentStoreTest.java index 567ced0c0..ad573091b 100644 --- a/jbake-core/src/test/java/org/jbake/app/ContentStoreTest.java +++ b/jbake-core/src/test/java/org/jbake/app/ContentStoreTest.java @@ -1,24 +1,24 @@ package org.jbake.app; +import java.util.Collections; +import java.util.Date; +import java.util.Set; + import org.jbake.FakeDocumentBuilder; import org.jbake.model.DocumentModel; import org.jbake.model.DocumentTypes; import org.jbake.model.ModelAttributes.Status; -import org.junit.Test; - -import java.util.Collections; -import java.util.Date; -import java.util.Set; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ContentStoreTest extends ContentStoreIntegrationTest { +class ContentStoreTest extends ContentStoreIntegrationTest { - public static final String DOC_TYPE_POST = "post"; + private static final String DOC_TYPE_POST = "post"; @Test - public void shouldGetCountForPublishedDocuments() throws Exception { + void shouldGetCountForPublishedDocuments() throws Exception { for (int i = 0; i < 5; i++) { FakeDocumentBuilder builder = new FakeDocumentBuilder(DOC_TYPE_POST); @@ -37,7 +37,7 @@ public void shouldGetCountForPublishedDocuments() throws Exception { } @Test - public void testStoreTypeWithSpecialCharacters() { + void testStoreTypeWithSpecialCharacters() { final String typeWithHyphen = "type-with-hyphen"; DocumentTypes.addDocumentType(typeWithHyphen); diff --git a/jbake-core/src/test/java/org/jbake/app/CrawlerTest.java b/jbake-core/src/test/java/org/jbake/app/CrawlerTest.java index 326f001a0..f8f4aabb2 100644 --- a/jbake-core/src/test/java/org/jbake/app/CrawlerTest.java +++ b/jbake-core/src/test/java/org/jbake/app/CrawlerTest.java @@ -1,34 +1,31 @@ package org.jbake.app; -import com.orientechnologies.orient.core.db.record.OTrackedMap; +import java.util.HashMap; +import java.util.Map; + import org.apache.commons.io.FilenameUtils; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; import org.jbake.model.DocumentModel; -import org.jbake.model.ModelAttributes; import org.jbake.model.DocumentTypes; +import org.jbake.model.ModelAttributes; import org.jbake.util.DataFileUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; +import com.orientechnologies.orient.core.db.record.OTrackedMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class CrawlerTest extends ContentStoreIntegrationTest { +class CrawlerTest extends ContentStoreIntegrationTest { @Test - public void crawl() { + void crawl() { Crawler crawler = new Crawler(db, config); crawler.crawl(); - Assert.assertEquals(4, db.getDocumentCount("post")); - Assert.assertEquals(3, db.getDocumentCount("page")); + assertEquals(4, db.getDocumentCount("post")); + assertEquals(3, db.getDocumentCount("page")); DocumentList results = db.getPublishedPosts(); @@ -52,26 +49,26 @@ public void crawl() { // covers bug #213 DocumentList publishedPostsByTag = db.getPublishedPostsByTag("blog"); - Assert.assertEquals(3, publishedPostsByTag.size()); + assertEquals(3, publishedPostsByTag.size()); } @Test - public void crawlDataFiles() { + void crawlDataFiles() { Crawler crawler = new Crawler(db, config); // manually register data doctype DocumentTypes.addDocumentType(config.getDataFileDocType()); db.updateSchema(); crawler.crawlDataFiles(); - Assert.assertEquals(2, db.getDocumentCount("data")); + assertEquals(2, db.getDocumentCount("data")); DataFileUtil dataFileUtil = new DataFileUtil(db, "data"); Map videos = dataFileUtil.get("videos.yaml"); - Assert.assertFalse(videos.isEmpty()); - Assert.assertNotNull(videos.get("data")); + assertFalse(videos.isEmpty()); + assertNotNull(videos.get("data")); // regression test for issue 747 Map authorsFileContents = dataFileUtil.get("authors.yaml"); - Assert.assertFalse(authorsFileContents.isEmpty()); + assertFalse(authorsFileContents.isEmpty()); Object authorsList = authorsFileContents.get("authors"); assertThat(authorsList).isNotInstanceOf(OTrackedMap.class); assertThat(authorsList).isInstanceOf(HashMap.class); @@ -80,7 +77,7 @@ public void crawlDataFiles() { } @Test - public void renderWithPrettyUrls() { + void renderWithPrettyUrls() { config.setUriWithoutExtension(true); config.setPrefixForUriWithoutExtension("/blog"); @@ -88,40 +85,17 @@ public void renderWithPrettyUrls() { Crawler crawler = new Crawler(db, config); crawler.crawl(); - Assert.assertEquals(4, db.getDocumentCount("post")); - Assert.assertEquals(3, db.getDocumentCount("page")); + assertEquals(4, db.getDocumentCount("post")); + assertEquals(3, db.getDocumentCount("page")); DocumentList documents = db.getPublishedPosts(); for (DocumentModel model : documents) { String noExtensionUri = "blog/\\d{4}/" + FilenameUtils.getBaseName(model.getFile()) + "/"; - Assert.assertThat(model.getNoExtensionUri(), RegexMatcher.matches(noExtensionUri)); - Assert.assertThat(model.getUri(), RegexMatcher.matches(noExtensionUri + "index\\.html")); - Assert.assertThat(model.getRootPath(), is("../../../")); - } - } - - private static class RegexMatcher extends BaseMatcher { - private final String regex; - - public RegexMatcher(String regex) { - this.regex = regex; - } - - public static RegexMatcher matches(String regex) { - return new RegexMatcher(regex); - } - - @Override - public boolean matches(Object o) { - return ((String) o).matches(regex); - - } - - @Override - public void describeTo(Description description) { - description.appendText("matches regex: " + regex); + assertThat(model.getNoExtensionUri()).matches(noExtensionUri); + assertThat(model.getUri()).matches(noExtensionUri + "index\\.html"); + assertThat(model.getRootPath()).isEqualTo("../../../"); } } } diff --git a/jbake-core/src/test/java/org/jbake/app/DebugUtilTest.java b/jbake-core/src/test/java/org/jbake/app/DebugUtilTest.java index e6cfde31d..b291b92ef 100644 --- a/jbake-core/src/test/java/org/jbake/app/DebugUtilTest.java +++ b/jbake-core/src/test/java/org/jbake/app/DebugUtilTest.java @@ -1,19 +1,20 @@ package org.jbake.app; -import org.jbake.util.DebugUtil; -import org.junit.Assert; -import org.junit.Test; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.HashMap; -public class DebugUtilTest { +import org.jbake.util.DebugUtil; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DebugUtilTest { @Test - public void printMap() throws UnsupportedEncodingException { + void printMap() throws UnsupportedEncodingException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (PrintStream ps = new PrintStream(baos, true, "UTF-8")) { HashMap map = new HashMap(); @@ -28,10 +29,10 @@ public void printMap() throws UnsupportedEncodingException { String printed = new String(baos.toByteArray(), StandardCharsets.UTF_8); System.out.println(printed); - Assert.assertTrue(printed.contains("stringKey :: stringVal")); - Assert.assertTrue(printed.contains("null :: forNullKey")); - Assert.assertTrue(printed.contains("forNullVal :: null")); - Assert.assertTrue(printed.contains("forCharset :: UTF-8")); - Assert.assertTrue(printed.contains("forNonSerializableVal :: java.lang.Exception: nonSerializableVal")); + assertTrue(printed.contains("stringKey :: stringVal")); + assertTrue(printed.contains("null :: forNullKey")); + assertTrue(printed.contains("forNullVal :: null")); + assertTrue(printed.contains("forCharset :: UTF-8")); + assertTrue(printed.contains("forNonSerializableVal :: java.lang.Exception: nonSerializableVal")); } } diff --git a/jbake-core/src/test/java/org/jbake/app/FileUtilTest.java b/jbake-core/src/test/java/org/jbake/app/FileUtilTest.java index 359d75dc9..668a53ea5 100644 --- a/jbake-core/src/test/java/org/jbake/app/FileUtilTest.java +++ b/jbake-core/src/test/java/org/jbake/app/FileUtilTest.java @@ -1,44 +1,44 @@ package org.jbake.app; +import java.io.File; + import org.jbake.TestUtils; import org.jbake.app.configuration.ConfigUtil; import org.jbake.app.configuration.DefaultJBakeConfiguration; -import org.junit.Test; - -import java.io.File; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Created by frank on 28.03.16. */ -public class FileUtilTest { +class FileUtilTest { @Test - public void testGetRunningLocation() throws Exception { + void testGetRunningLocation() throws Exception { File path = FileUtil.getRunningLocation(); assertEquals(new File("build/classes").getAbsolutePath(), path.getPath()); } @Test - public void testIsFileInDirectory() throws Exception { + void testIsFileInDirectory() throws Exception { File fixtureDir = new File(this.getClass().getResource("/fixture").getFile()); File jbakeFile = new File(fixtureDir.getCanonicalPath() + File.separatorChar + "jbake.properties"); - assertTrue("jbake.properties expected to be in /fixture directory", FileUtil.isFileInDirectory(jbakeFile, fixtureDir)); + assertTrue(FileUtil.isFileInDirectory(jbakeFile, fixtureDir), "jbake.properties expected to be in /fixture directory"); File contentFile = new File(fixtureDir.getCanonicalPath() + File.separatorChar + "content" + File.separatorChar + "projects.html"); - assertTrue("projects.html expected to be nested in the /fixture directory", FileUtil.isFileInDirectory(contentFile, fixtureDir)); + assertTrue(FileUtil.isFileInDirectory(contentFile, fixtureDir), "projects.html expected to be nested in the /fixture directory"); File contentDir = contentFile.getParentFile(); - assertFalse("jbake.properties file should not be in the /fixture/content directory", FileUtil.isFileInDirectory(jbakeFile, contentDir)); + assertFalse(FileUtil.isFileInDirectory(jbakeFile, contentDir), "jbake.properties file should not be in the /fixture/content directory"); } @Test - public void testGetContentRoothPath() throws Exception { + void testGetContentRoothPath() throws Exception { File source = TestUtils.getTestResourcesAsSourceFolder(); ConfigUtil util = new ConfigUtil(); diff --git a/jbake-core/src/test/java/org/jbake/app/InitTest.java b/jbake-core/src/test/java/org/jbake/app/InitTest.java index 3c98f556e..ca4acd088 100644 --- a/jbake-core/src/test/java/org/jbake/app/InitTest.java +++ b/jbake-core/src/test/java/org/jbake/app/InitTest.java @@ -1,30 +1,31 @@ package org.jbake.app; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + import org.jbake.TestUtils; import org.jbake.app.configuration.ConfigUtil; import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.launcher.Init; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.IOException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -public class InitTest { +class InitTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private Path folder; - public DefaultJBakeConfiguration config; + private DefaultJBakeConfiguration config; private File rootPath; - @Before - public void setup() throws Exception { + @BeforeEach + void setup() throws Exception { rootPath = TestUtils.getTestResourcesAsSourceFolder(); if (!rootPath.exists()) { @@ -36,18 +37,19 @@ public void setup() throws Exception { } @Test - public void initOK() throws Exception { + void initOK() throws Exception { Init init = new Init(config); - File initPath = folder.newFolder("init"); + File initPath = folder.resolve("init").toFile(); + Files.createDirectories(initPath.toPath()); init.run(initPath, rootPath, "freemarker"); File testFile = new File(initPath, "testfile.txt"); assertThat(testFile).exists(); } @Test - public void initFailDestinationContainsContent() throws IOException { + void initFailDestinationContainsContent() throws IOException { Init init = new Init(config); - File initPath = folder.newFolder("init"); + File initPath = folder.resolve("init").toFile(); File contentFolder = new File(initPath.getPath(), config.getContentFolderName()); contentFolder.mkdir(); try { @@ -61,9 +63,9 @@ public void initFailDestinationContainsContent() throws IOException { } @Test - public void initFailInvalidTemplateType() throws IOException { + void initFailInvalidTemplateType() throws IOException { Init init = new Init(config); - File initPath = folder.newFolder("init"); + File initPath = folder.resolve("init").toFile(); try { init.run(initPath, rootPath, "invalid"); fail("Shouldn't be able to initialise folder with invalid template type"); diff --git a/jbake-core/src/test/java/org/jbake/app/MdParserTest.java b/jbake-core/src/test/java/org/jbake/app/MdParserTest.java index 1b1dceb53..ec5c2c1c0 100644 --- a/jbake-core/src/test/java/org/jbake/app/MdParserTest.java +++ b/jbake-core/src/test/java/org/jbake/app/MdParserTest.java @@ -1,19 +1,21 @@ package org.jbake.app; +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Path; + import org.jbake.TestUtils; import org.jbake.app.configuration.ConfigUtil; import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.model.DocumentModel; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.PrintWriter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Tests basic Markdown syntax and the extensions supported by the Markdown @@ -22,12 +24,12 @@ * @author Jonathan Bullock * @author Kevin S. Clarke */ -public class MdParserTest { +class MdParserTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private Path folder; - public DefaultJBakeConfiguration config; + private DefaultJBakeConfiguration config; private File validMdFileBasic; @@ -73,52 +75,52 @@ public class MdParserTest { private String invalidHeader = "title=Title\n~~~~~~"; - @Before - public void createSampleFile() throws Exception { + @BeforeEach + void createSampleFile() throws Exception { File configFile = TestUtils.getTestResourcesAsSourceFolder(); config = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(configFile); - validMdFileBasic = folder.newFile("validBasic.md"); + validMdFileBasic = folder.resolve("validBasic.md").toFile(); PrintWriter out = new PrintWriter(validMdFileBasic); out.println(validHeader); out.println("# This is a test"); out.close(); - invalidMdFileBasic = folder.newFile("invalidBasic.md"); + invalidMdFileBasic = folder.resolve("invalidBasic.md").toFile(); out = new PrintWriter(invalidMdFileBasic); out.println(invalidHeader); out.println("# This is a test"); out.close(); - mdFileHardWraps = folder.newFile("hardWraps.md"); + mdFileHardWraps = folder.resolve("hardWraps.md").toFile(); out = new PrintWriter(mdFileHardWraps); out.println(validHeader); out.println("First line"); out.println("Second line"); out.close(); - mdFileAbbreviations = folder.newFile("abbreviations.md"); + mdFileAbbreviations = folder.resolve("abbreviations.md").toFile(); out = new PrintWriter(mdFileAbbreviations); out.println(validHeader); out.println("*[HTML]: Hyper Text Markup Language"); out.println("HTML"); out.close(); - mdFileAutolinks = folder.newFile("autolinks.md"); + mdFileAutolinks = folder.resolve("autolinks.md").toFile(); out = new PrintWriter(mdFileAutolinks); out.println(validHeader); out.println("http://github.com"); out.close(); - mdFileDefinitions = folder.newFile("definitions.md"); + mdFileDefinitions = folder.resolve("definitions.md").toFile(); out = new PrintWriter(mdFileDefinitions); out.println(validHeader); out.println("Apple"); out.println(": Pomaceous fruit"); out.close(); - mdFileFencedCodeBlocks = folder.newFile("fencedCodeBlocks.md"); + mdFileFencedCodeBlocks = folder.resolve("fencedCodeBlocks.md").toFile(); out = new PrintWriter(mdFileFencedCodeBlocks); out.println(validHeader); out.println("```"); @@ -128,43 +130,43 @@ public void createSampleFile() throws Exception { out.println("```"); out.close(); - mdFileQuotes = folder.newFile("quotes.md"); + mdFileQuotes = folder.resolve("quotes.md").toFile(); out = new PrintWriter(mdFileQuotes); out.println(validHeader); out.println("\"quotes\""); out.close(); - mdFileSmarts = folder.newFile("smarts.md"); + mdFileSmarts = folder.resolve("smarts.md").toFile(); out = new PrintWriter(mdFileSmarts); out.println(validHeader); out.println("..."); out.close(); - mdFileSmartypants = folder.newFile("smartypants.md"); + mdFileSmartypants = folder.resolve("smartypants.md").toFile(); out = new PrintWriter(mdFileSmartypants); out.println(validHeader); out.println("\"...\""); out.close(); - mdFileSuppressAllHTML = folder.newFile("suppressAllHTML.md"); + mdFileSuppressAllHTML = folder.resolve("suppressAllHTML.md").toFile(); out = new PrintWriter(mdFileSuppressAllHTML); out.println(validHeader); out.println("
!
!"); out.close(); - mdFileSuppressHTMLBlocks = folder.newFile("suppressHTMLBlocks.md"); + mdFileSuppressHTMLBlocks = folder.resolve("suppressHTMLBlocks.md").toFile(); out = new PrintWriter(mdFileSuppressHTMLBlocks); out.println(validHeader); out.println("
!
!"); out.close(); - mdFileSuppressInlineHTML = folder.newFile("suppressInlineHTML.md"); + mdFileSuppressInlineHTML = folder.resolve("suppressInlineHTML.md").toFile(); out = new PrintWriter(mdFileSuppressInlineHTML); out.println(validHeader); out.println("This is the first paragraph. with inline html"); out.close(); - mdFileTables = folder.newFile("tables.md"); + mdFileTables = folder.resolve("tables.md").toFile(); out = new PrintWriter(mdFileTables); out.println(validHeader); out.println("First Header|Second Header"); @@ -173,19 +175,19 @@ public void createSampleFile() throws Exception { out.println("Content Cell|Content Cell"); out.close(); - mdFileWikilinks = folder.newFile("wikilinks.md"); + mdFileWikilinks = folder.resolve("wikilinks.md").toFile(); out = new PrintWriter(mdFileWikilinks); out.println(validHeader); out.println("[[Wiki-style links]]"); out.close(); - mdFileAtxheaderspace = folder.newFile("atxheaderspace.md"); + mdFileAtxheaderspace = folder.resolve("atxheaderspace.md").toFile(); out = new PrintWriter(mdFileAtxheaderspace); out.println(validHeader); out.println("#Test"); out.close(); - mdFileForcelistitempara = folder.newFile("forcelistitempara.md"); + mdFileForcelistitempara = folder.resolve("forcelistitempara.md").toFile(); out = new PrintWriter(mdFileForcelistitempara); out.println(validHeader); out.println("1. Item 1"); @@ -196,7 +198,7 @@ public void createSampleFile() throws Exception { out.println(" Item 1 paragraph 1 continuation"); out.close(); - mdFileRelaxedhrules = folder.newFile("releaxedhrules.md"); + mdFileRelaxedhrules = folder.resolve("releaxedhrules.md").toFile(); out = new PrintWriter(mdFileRelaxedhrules); out.println(validHeader); out.println("Hello World"); @@ -215,7 +217,7 @@ public void createSampleFile() throws Exception { out.println("***"); out.close(); - mdTasklistitems = folder.newFile("tasklistsitem.md"); + mdTasklistitems = folder.resolve("tasklistsitem.md").toFile(); out = new PrintWriter(mdTasklistitems); out.println(validHeader); out.println("* loose bullet item 3"); @@ -223,7 +225,7 @@ public void createSampleFile() throws Exception { out.println("* [x] closed task item"); out.close(); - mdExtanchorlinks = folder.newFile("mdExtanchorlinks.md"); + mdExtanchorlinks = folder.resolve("mdExtanchorlinks.md").toFile(); out = new PrintWriter(mdExtanchorlinks); out.println(validHeader); out.println("# header & some *formatting* ~~chars~~"); @@ -231,59 +233,59 @@ public void createSampleFile() throws Exception { } @Test - public void parseValidMarkdownFileBasic() { + void parseValidMarkdownFileBasic() { Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(validMdFileBasic); - Assert.assertNotNull(documentModel); - Assert.assertEquals("draft", documentModel.getStatus()); - Assert.assertEquals("post", documentModel.getType()); - Assert.assertEquals("

This is a test

\n", documentModel.getBody()); + assertNotNull(documentModel); + assertEquals("draft", documentModel.getStatus()); + assertEquals("post", documentModel.getType()); + assertEquals("

This is a test

\n", documentModel.getBody()); } @Test - public void parseInvalidMarkdownFileBasic() { + void parseInvalidMarkdownFileBasic() { Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(invalidMdFileBasic); - Assert.assertNull(documentModel); + assertNull(documentModel); } @Test - public void parseValidMdFileHardWraps() { + void parseValidMdFileHardWraps() { config.setMarkdownExtensions("HARDWRAPS"); // Test with HARDWRAPS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileHardWraps); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

First line
\nSecond line

\n"); // Test without HARDWRAPS config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileHardWraps); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

First line Second line

"); } @Test - public void parseWithInvalidExtension() { + void parseWithInvalidExtension() { config.setMarkdownExtensions("HARDWRAPS,UNDEFINED_EXTENSION"); // Test with HARDWRAPS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileHardWraps); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

First line
\nSecond line

\n"); } @Test - public void parseValidMdFileAbbreviations() { + void parseValidMdFileAbbreviations() { config.setMarkdownExtensions("ABBREVIATIONS"); // Test with ABBREVIATIONS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileAbbreviations); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

HTML

" ); @@ -292,19 +294,19 @@ public void parseValidMdFileAbbreviations() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileAbbreviations); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

*[HTML]: Hyper Text Markup Language HTML

"); } @Test - public void parseValidMdFileAutolinks() { + void parseValidMdFileAutolinks() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("AUTOLINKS"); // Test with AUTOLINKS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileAutolinks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

http://github.com

" ); @@ -313,19 +315,19 @@ public void parseValidMdFileAutolinks() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileAutolinks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

http://github.com

"); } @Test - public void parseValidMdFileDefinitions() { + void parseValidMdFileDefinitions() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("DEFINITIONS"); // Test with DEFINITIONS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileDefinitions); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "
\n
Apple
\n
Pomaceous fruit
\n
" ); @@ -334,19 +336,19 @@ public void parseValidMdFileDefinitions() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileDefinitions); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

Apple : Pomaceous fruit

"); } @Test - public void parseValidMdFileFencedCodeBlocks() { + void parseValidMdFileFencedCodeBlocks() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("FENCED_CODE_BLOCKS"); // Test with FENCED_CODE_BLOCKS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileFencedCodeBlocks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "
function test() {\n  console.log("!");\n}\n
" ); @@ -355,135 +357,135 @@ public void parseValidMdFileFencedCodeBlocks() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileFencedCodeBlocks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

function test() { console.log("!"); }

" ); } @Test - public void parseValidMdFileQuotes() { + void parseValidMdFileQuotes() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("QUOTES"); // Test with QUOTES Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileQuotes); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

“quotes”

"); // Test without QUOTES config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileQuotes); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

"quotes"

"); } @Test - public void parseValidMdFileSmarts() { + void parseValidMdFileSmarts() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("SMARTS"); // Test with SMARTS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileSmarts); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

"); // Test without SMARTS config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileSmarts); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

...

"); } @Test - public void parseValidMdFileSmartypants() { + void parseValidMdFileSmartypants() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("SMARTYPANTS"); // Test with SMARTYPANTS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileSmartypants); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

“…”

"); // Test without SMARTYPANTS config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileSmartypants); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

"..."

"); } @Test - public void parseValidMdFileSuppressAllHTML() { + void parseValidMdFileSuppressAllHTML() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("SUPPRESS_ALL_HTML"); // Test with SUPPRESS_ALL_HTML Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileSuppressAllHTML); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains(""); // Test without SUPPRESS_ALL_HTML config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileSuppressAllHTML); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("
!
!"); } @Test - public void parseValidMdFileSuppressHTMLBlocks() { + void parseValidMdFileSuppressHTMLBlocks() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("SUPPRESS_HTML_BLOCKS"); // Test with SUPPRESS_HTML_BLOCKS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileSuppressHTMLBlocks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains(""); // Test without SUPPRESS_HTML_BLOCKS config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileSuppressHTMLBlocks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("
!
!"); } @Test - public void parseValidMdFileSuppressInlineHTML() { + void parseValidMdFileSuppressInlineHTML() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("SUPPRESS_INLINE_HTML"); // Test with SUPPRESS_INLINE_HTML Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileSuppressInlineHTML); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

This is the first paragraph. with inline html

"); // Test without SUPPRESS_INLINE_HTML config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileSuppressInlineHTML); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

This is the first paragraph. with inline html

"); } @Test - public void parseValidMdFileTables() { + void parseValidMdFileTables() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("TABLES"); // Test with TABLES Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileTables); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "\n" + "\n" + @@ -500,21 +502,21 @@ public void parseValidMdFileTables() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileTables); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

First Header|Second Header -------------|------------- Content Cell|Content Cell Content Cell|Content Cell

" ); } @Test - public void parseValidMdFileWikilinks() { + void parseValidMdFileWikilinks() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("WIKILINKS"); // Test with WIKILINKS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileWikilinks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

Wiki-style links

" ); @@ -523,38 +525,38 @@ public void parseValidMdFileWikilinks() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileWikilinks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

[[Wiki-style links]]

"); } @Test - public void parseValidMdFileAtxheaderspace() { + void parseValidMdFileAtxheaderspace() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("ATXHEADERSPACE"); // Test with ATXHEADERSPACE Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileAtxheaderspace); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

#Test

"); // Test without ATXHEADERSPACE config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileAtxheaderspace); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

Test

"); } @Test - public void parseValidMdFileForcelistitempara() { + void parseValidMdFileForcelistitempara() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("FORCELISTITEMPARA"); // Test with FORCELISTITEMPARA Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileForcelistitempara); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "
    \n" + "
  1. \n" + @@ -567,7 +569,7 @@ public void parseValidMdFileForcelistitempara() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileForcelistitempara); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "
      \n" + "
    1. Item 1 Item 1 lazy continuation\n" + @@ -578,14 +580,14 @@ public void parseValidMdFileForcelistitempara() { } @Test - public void parseValidMdFileRelaxedhrules() { + void parseValidMdFileRelaxedhrules() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("RELAXEDHRULES"); // Test with RELAXEDHRULES Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdFileRelaxedhrules); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

      Hello World

      \n" + "
      \n" + @@ -604,7 +606,7 @@ public void parseValidMdFileRelaxedhrules() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdFileRelaxedhrules); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

      Hello World

      \n" + "
      \n" + @@ -617,14 +619,14 @@ public void parseValidMdFileRelaxedhrules() { } @Test - public void parseValidMdFileTasklistitems() { + void parseValidMdFileTasklistitems() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("TASKLISTITEMS"); // Test with TASKLISTITEMS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdTasklistitems); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "
        \n" + "
      • loose bullet item 3
      • \n" + @@ -637,7 +639,7 @@ public void parseValidMdFileTasklistitems() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdTasklistitems); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "
          \n" + "
        • loose bullet item 3
        • \n" + @@ -647,14 +649,14 @@ public void parseValidMdFileTasklistitems() { } @Test - public void parseValidMdFileExtanchorlinks() { + void parseValidMdFileExtanchorlinks() { config.setMarkdownExtensions(""); config.setMarkdownExtensions("EXTANCHORLINKS"); // Test with EXTANCHORLINKS Parser parser = new Parser(config); DocumentModel documentModel = parser.processFile(mdExtanchorlinks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains( "

          header & some formatting ~~chars~~

          " ); @@ -663,9 +665,8 @@ public void parseValidMdFileExtanchorlinks() { config.setMarkdownExtensions(""); parser = new Parser(config); documentModel = parser.processFile(mdExtanchorlinks); - Assert.assertNotNull(documentModel); + assertNotNull(documentModel); assertThat(documentModel.getBody()).contains("

          header & some formatting ~~chars~~

          "); } - } diff --git a/jbake-core/src/test/java/org/jbake/app/OvenTest.java b/jbake-core/src/test/java/org/jbake/app/OvenTest.java index a59e84aec..e94222dc6 100644 --- a/jbake-core/src/test/java/org/jbake/app/OvenTest.java +++ b/jbake-core/src/test/java/org/jbake/app/OvenTest.java @@ -1,5 +1,11 @@ package org.jbake.app; +import java.io.BufferedWriter; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Locale; + import org.apache.commons.io.FileUtils; import org.jbake.TestUtils; import org.jbake.app.configuration.ConfigUtil; @@ -11,17 +17,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Locale; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; @@ -31,17 +26,17 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class OvenTest { +class OvenTest { @TempDir - Path root; + private Path root; private DefaultJBakeConfiguration configuration; private File sourceFolder; private ContentStore contentStore; @BeforeEach - public void setUp() throws Exception { + void setUp() throws Exception { // reset values to known state otherwise previous test case runs can affect the success of this test case DocumentTypes.resetDocumentTypes(); File output = root.resolve("output").toFile(); @@ -53,7 +48,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() { + void tearDown() { if (contentStore != null && contentStore.isActive()) { contentStore.close(); contentStore.shutdown(); @@ -61,7 +56,7 @@ public void tearDown() { } @Test - public void bakeWithAbsolutePaths() { + void bakeWithAbsolutePaths() { configuration.setTemplateFolder(new File(sourceFolder, "groovyMarkupTemplates")); configuration.setContentFolder(new File(sourceFolder, "content")); configuration.setAssetFolder(new File(sourceFolder, "assets")); @@ -73,7 +68,7 @@ public void bakeWithAbsolutePaths() { } @Test - public void shouldBakeWithRelativeCustomPaths() throws Exception { + void shouldBakeWithRelativeCustomPaths() throws Exception { sourceFolder = TestUtils.getTestResourcesAsSourceFolder("/fixture-custom-relative"); configuration = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(sourceFolder); File assetFolder = new File(configuration.getDestinationFolder(), "css"); @@ -93,7 +88,7 @@ public void shouldBakeWithRelativeCustomPaths() throws Exception { } @Test - public void shouldBakeWithAbsoluteCustomPaths() throws Exception { + void shouldBakeWithAbsoluteCustomPaths() throws Exception { // given Path source = root.resolve("source"); @@ -140,14 +135,14 @@ public void shouldBakeWithAbsoluteCustomPaths() throws Exception { @Test - public void shouldThrowExceptionIfSourceFolderDoesNotExist() { + void shouldThrowExceptionIfSourceFolderDoesNotExist() { configuration.setSourceFolder(root.resolve("none").toFile()); assertThrows(JBakeException.class, () -> new Oven(configuration)); } @Test - public void shouldInstantiateNeededUtensils() throws Exception { + void shouldInstantiateNeededUtensils() throws Exception { File template = TestUtils.newFolder(root.toFile(), "template"); File content = TestUtils.newFolder(root.toFile(), "content"); @@ -167,7 +162,7 @@ public void shouldInstantiateNeededUtensils() throws Exception { } @Test() - public void shouldInspectConfigurationDuringInstantiationFromUtils() { + void shouldInspectConfigurationDuringInstantiationFromUtils() { configuration.setSourceFolder(root.resolve("none").toFile()); Utensils utensils = new Utensils(); @@ -177,7 +172,7 @@ public void shouldInspectConfigurationDuringInstantiationFromUtils() { } @Test - public void shouldCrawlRenderAndCopyAssets() throws Exception { + void shouldCrawlRenderAndCopyAssets() throws Exception { File template = TestUtils.newFolder(root.toFile(), "template"); File content = TestUtils.newFolder(root.toFile(), "content"); File assets = TestUtils.newFolder(root.toFile(), "assets"); @@ -210,23 +205,23 @@ public void shouldCrawlRenderAndCopyAssets() throws Exception { } @Test - public void localeConfiguration() throws Exception { + void localeConfiguration() throws Exception { String language = configuration.getJvmLocale(); final Oven oven = new Oven(configuration); oven.bake(); - assertThat(Locale.getDefault(), is(new Locale(language))); + assertThat(Locale.getDefault()).isEqualTo(new Locale(language)); } @Test - public void noLocaleConfiguration() throws Exception { + void noLocaleConfiguration() throws Exception { configuration.setProperty(PropertyList.JVM_LOCALE.getKey(), null); String language = Locale.getDefault().getLanguage(); final Oven oven = new Oven(configuration); oven.bake(); - assertThat(Locale.getDefault(), is(new Locale(language))); + assertThat(Locale.getDefault()).isEqualTo(new Locale(language)); } } diff --git a/jbake-core/src/test/java/org/jbake/app/PaginationTest.java b/jbake-core/src/test/java/org/jbake/app/PaginationTest.java index 70fefa86a..63ca1f762 100644 --- a/jbake-core/src/test/java/org/jbake/app/PaginationTest.java +++ b/jbake-core/src/test/java/org/jbake/app/PaginationTest.java @@ -23,26 +23,25 @@ */ package org.jbake.app; +import java.util.Calendar; +import java.util.Locale; + import org.jbake.FakeDocumentBuilder; import org.jbake.model.DocumentModel; import org.jbake.model.DocumentTypes; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.BeforeClass; - -import java.util.Calendar; -import java.util.Locale; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author jdlee */ -public class PaginationTest extends ContentStoreIntegrationTest { +class PaginationTest extends ContentStoreIntegrationTest { - @Before - public void setUpOwn() { + @BeforeEach + void setUpOwn() { for (String docType : DocumentTypes.getDocumentTypes()) { String fileBaseName = docType; if (docType.equals("masterindex")) { @@ -56,7 +55,7 @@ public void setUpOwn() { } @Test - public void testPagination() { + void testPagination() { final int TOTAL_POSTS = 5; final int PER_PAGE = 2; Calendar cal = Calendar.getInstance(Locale.ENGLISH); @@ -89,6 +88,6 @@ public void testPagination() { pageCount++; start += PER_PAGE; } - Assert.assertEquals(4, pageCount); + assertEquals(4, pageCount); } } diff --git a/jbake-core/src/test/java/org/jbake/app/ParserTest.java b/jbake-core/src/test/java/org/jbake/app/ParserTest.java index ef9f1000b..7cef2fb90 100644 --- a/jbake-core/src/test/java/org/jbake/app/ParserTest.java +++ b/jbake-core/src/test/java/org/jbake/app/ParserTest.java @@ -1,31 +1,32 @@ package org.jbake.app; +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.util.AbstractMap.SimpleEntry; +import java.util.Arrays; +import java.util.Calendar; + import org.jbake.TestUtils; import org.jbake.app.configuration.ConfigUtil; import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.model.DocumentModel; -import org.jbake.app.configuration.PropertyList; import org.json.simple.JSONArray; import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.PrintWriter; -import java.util.AbstractMap.SimpleEntry; -import java.util.Arrays; -import java.util.Calendar; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; import static org.jbake.app.configuration.PropertyList.TAG_SANITIZE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; -public class ParserTest { +class ParserTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private Path folder; private DefaultJBakeConfiguration config; private Parser parser; @@ -53,24 +54,24 @@ public class ParserTest { private String customHeaderSeparator; - @Before - public void createSampleFile() throws Exception { + @BeforeEach + void createSampleFile() throws Exception { rootPath = TestUtils.getTestResourcesAsSourceFolder(); config = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(rootPath); parser = new Parser(config); - validHTMLFile = folder.newFile("valid.html"); + validHTMLFile = folder.resolve("valid.html").toFile(); PrintWriter out = new PrintWriter(validHTMLFile); out.println(validHeader); out.println("

          This is a test.

          "); out.close(); - invalidHTMLFile = folder.newFile("invalid.html"); + invalidHTMLFile = folder.resolve("invalid.html").toFile(); out = new PrintWriter(invalidHTMLFile); out.println(invalidHeader); out.close(); - validMarkdownFileWithCustomHeader = folder.newFile("validMdCustomHeader.md"); + validMarkdownFileWithCustomHeader = folder.resolve("validMdCustomHeader.md").toFile(); customHeaderSeparator = "---------------------------------------"; out = new PrintWriter(validMarkdownFileWithCustomHeader); @@ -87,7 +88,7 @@ public void createSampleFile() throws Exception { out.println("* List"); out.close(); - validMarkdownFileWithDefaultStatus = folder.newFile("validMdDefaultStatus.md"); + validMarkdownFileWithDefaultStatus = folder.resolve("validMdDefaultStatus.md").toFile(); out = new PrintWriter(validMarkdownFileWithDefaultStatus); out.println("title=Custom Header separator"); @@ -102,7 +103,7 @@ public void createSampleFile() throws Exception { out.println("* List"); out.close(); - validMarkdownFileWithDefaultTypeAndStatus = folder.newFile("validMdDefaultTypeAndStatus.md"); + validMarkdownFileWithDefaultTypeAndStatus = folder.resolve("validMdDefaultTypeAndStatus.md").toFile(); out = new PrintWriter(validMarkdownFileWithDefaultTypeAndStatus); out.println("title=Custom Header separator"); @@ -117,7 +118,7 @@ public void createSampleFile() throws Exception { out.println("* List"); out.close(); - invalidMarkdownFileWithoutDefaultStatus = folder.newFile("invalidMdWithoutDefaultStatus.md"); + invalidMarkdownFileWithoutDefaultStatus = folder.resolve("invalidMdWithoutDefaultStatus.md").toFile(); out = new PrintWriter(invalidMarkdownFileWithoutDefaultStatus); out.println("title=Custom Header separator"); @@ -132,7 +133,7 @@ public void createSampleFile() throws Exception { out.println("* List"); out.close(); - invalidMDFile = folder.newFile("invalidMd.md"); + invalidMDFile = folder.resolve("invalidMd.md").toFile(); out = new PrintWriter(invalidMDFile); out.println(invalidHeader); @@ -145,12 +146,12 @@ public void createSampleFile() throws Exception { out.println("* List"); out.close(); - invalidExtensionFile = folder.newFile("invalid.invalid"); + invalidExtensionFile = folder.resolve("invalid.invalid").toFile(); out = new PrintWriter(invalidExtensionFile); out.println("invalid content"); out.close(); - validHTMLWithJSONFile = folder.newFile("validHTMLWithJSONFile.html"); + validHTMLWithJSONFile = folder.resolve("validHTMLWithJSONFile.html").toFile(); out = new PrintWriter(validHTMLWithJSONFile); out.println("title=This is a Title = This is a valid Title"); out.println("status=draft"); @@ -162,7 +163,7 @@ public void createSampleFile() throws Exception { out.println("Sample Body"); out.close(); - validAsciiDocWithJSONFile = folder.newFile("validAsciiDocWithJSONFile.ad"); + validAsciiDocWithJSONFile = folder.resolve("validAsciiDocWithJSONFile.ad").toFile(); out = new PrintWriter(validAsciiDocWithJSONFile); out.println("title=This is a Title = This is a valid Title"); out.println("status=draft"); @@ -177,7 +178,7 @@ public void createSampleFile() throws Exception { out.println("JBake now supports AsciiDoc."); out.close(); - validAsciiDocWithADHeaderJSONFile = folder.newFile("validAsciiDocWithADHeaderJSONFile.ad"); + validAsciiDocWithADHeaderJSONFile = folder.resolve("validAsciiDocWithADHeaderJSONFile.ad").toFile(); out = new PrintWriter(validAsciiDocWithADHeaderJSONFile); out.println("= Hello: AsciiDoc!"); out.println("Test User "); @@ -190,7 +191,7 @@ public void createSampleFile() throws Exception { out.println("JBake now supports AsciiDoc."); out.close(); - validaAsciidocWithUnsanitizedHeader = folder.newFile("validAsciidocWithUnsanitizedHeader.adoc"); + validaAsciidocWithUnsanitizedHeader = folder.resolve("validAsciidocWithUnsanitizedHeader.adoc").toFile(); out = new PrintWriter(validaAsciidocWithUnsanitizedHeader, "UTF-8"); // Simulating a \uFEFF Byte order Marker in utf-8 out.print("\uFEFF"); @@ -209,95 +210,95 @@ public void createSampleFile() throws Exception { } @Test - public void parseValidHTMLFile() { + void parseValidHTMLFile() { DocumentModel documentModel = parser.processFile(validHTMLFile); - Assert.assertNotNull(documentModel); - Assert.assertEquals("draft", documentModel.getStatus()); - Assert.assertEquals("post", documentModel.getType()); - Assert.assertEquals("This is a Title = This is a valid Title", documentModel.getTitle()); - Assert.assertNotNull(documentModel.getDate()); + assertNotNull(documentModel); + assertEquals("draft", documentModel.getStatus()); + assertEquals("post", documentModel.getType()); + assertEquals("This is a Title = This is a valid Title", documentModel.getTitle()); + assertNotNull(documentModel.getDate()); Calendar cal = Calendar.getInstance(); cal.setTime(documentModel.getDate()); - Assert.assertEquals(8, cal.get(Calendar.MONTH)); - Assert.assertEquals(2, cal.get(Calendar.DAY_OF_MONTH)); - Assert.assertEquals(2013, cal.get(Calendar.YEAR)); + assertEquals(8, cal.get(Calendar.MONTH)); + assertEquals(2, cal.get(Calendar.DAY_OF_MONTH)); + assertEquals(2013, cal.get(Calendar.YEAR)); } @Test - public void parseInvalidHTMLFile() { + void parseInvalidHTMLFile() { DocumentModel documentModel = parser.processFile(invalidHTMLFile); - Assert.assertNull(documentModel); + assertNull(documentModel); } @Test - public void parseInvalidExtension(){ + void parseInvalidExtension(){ DocumentModel documentModel = parser.processFile(invalidExtensionFile); - Assert.assertNull(documentModel); + assertNull(documentModel); } @Test - public void parseMarkdownFileWithCustomHeaderSeparator() { + void parseMarkdownFileWithCustomHeaderSeparator() { config.setHeaderSeparator(customHeaderSeparator); DocumentModel documentModel = parser.processFile(validMarkdownFileWithCustomHeader); - Assert.assertNotNull(documentModel); - Assert.assertEquals("draft", documentModel.getStatus()); - Assert.assertEquals("post", documentModel.getType()); + assertNotNull(documentModel); + assertEquals("draft", documentModel.getStatus()); + assertEquals("post", documentModel.getType()); assertThat(documentModel.getBody()) .contains("

          A paragraph

          "); } @Test - public void parseMarkdownFileWithDefaultStatus() { + void parseMarkdownFileWithDefaultStatus() { config.setDefaultStatus("published"); DocumentModel documentModel = parser.processFile(validMarkdownFileWithDefaultStatus); - Assert.assertNotNull(documentModel); - Assert.assertEquals("published", documentModel.getStatus()); - Assert.assertEquals("post", documentModel.getType()); - Assert.assertEquals(true, documentModel.getCached()); + assertNotNull(documentModel); + assertEquals("published", documentModel.getStatus()); + assertEquals("post", documentModel.getType()); + assertEquals(true, documentModel.getCached()); } @Test - public void parseMarkdownFileWithDefaultTypeAndStatus() { + void parseMarkdownFileWithDefaultTypeAndStatus() { config.setDefaultStatus("published"); config.setDefaultType("page"); DocumentModel documentModel = parser.processFile(validMarkdownFileWithDefaultTypeAndStatus); - Assert.assertNotNull(documentModel); - Assert.assertEquals("published", documentModel.getStatus()); - Assert.assertEquals("page", documentModel.getType()); + assertNotNull(documentModel); + assertEquals("published", documentModel.getStatus()); + assertEquals("page", documentModel.getType()); } @Test - public void parseMarkdownFileWithDisabledCache() { + void parseMarkdownFileWithDisabledCache() { config.setDefaultStatus("published"); config.setDefaultType("page"); DocumentModel documentModel = parser.processFile(validMarkdownFileWithDefaultTypeAndStatus); - Assert.assertEquals(false, documentModel.getCached()); + assertEquals(false, documentModel.getCached()); } @Test - public void parseInvalidMarkdownFileWithoutDefaultStatus() { + void parseInvalidMarkdownFileWithoutDefaultStatus() { config.setDefaultStatus(""); config.setDefaultType("page"); DocumentModel documentModel = parser.processFile(invalidMarkdownFileWithoutDefaultStatus); - Assert.assertNull(documentModel); + assertNull(documentModel); } @Test - public void parseInvalidMarkdownFile() { + void parseInvalidMarkdownFile() { DocumentModel documentModel = parser.processFile(invalidMDFile); - Assert.assertNull(documentModel); + assertNull(documentModel); } @Test - public void sanitizeKeysAndValues() { + void sanitizeKeysAndValues() { DocumentModel map = parser.processFile(validaAsciidocWithUnsanitizedHeader); assertThat(map.getStatus()).isEqualTo("draft"); @@ -308,7 +309,7 @@ public void sanitizeKeysAndValues() { } @Test - public void sanitizeTags() { + void sanitizeTags() { config.setProperty(TAG_SANITIZE.getKey(), true); DocumentModel map = parser.processFile(validaAsciidocWithUnsanitizedHeader); @@ -317,19 +318,19 @@ public void sanitizeTags() { @Test - public void parseValidHTMLWithJSONFile() { + void parseValidHTMLWithJSONFile() { DocumentModel documentModel = parser.processFile(validHTMLWithJSONFile); assertJSONExtracted(documentModel.get("jsondata")); } @Test - public void parseValidAsciiDocWithJSONFile() { + void parseValidAsciiDocWithJSONFile() { DocumentModel documentModel = parser.processFile(validAsciiDocWithJSONFile); assertJSONExtracted(documentModel.get("jsondata")); } @Test - public void testValidAsciiDocWithADHeaderJSONFile() { + void testValidAsciiDocWithADHeaderJSONFile() { DocumentModel documentModel = parser.processFile(validAsciiDocWithADHeaderJSONFile); assertJSONExtracted(documentModel.get("jsondata")); } diff --git a/jbake-core/src/test/java/org/jbake/app/configuration/ConfigUtilTest.java b/jbake-core/src/test/java/org/jbake/app/configuration/ConfigUtilTest.java index e0863e45f..9e47da372 100644 --- a/jbake-core/src/test/java/org/jbake/app/configuration/ConfigUtilTest.java +++ b/jbake-core/src/test/java/org/jbake/app/configuration/ConfigUtilTest.java @@ -1,6 +1,13 @@ package org.jbake.app.configuration; -import ch.qos.logback.classic.spi.LoggingEvent; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + import org.apache.commons.io.FileUtils; import org.jbake.TestUtils; import org.jbake.app.JBakeException; @@ -9,52 +16,41 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.lang.reflect.Field; -import java.nio.file.Files; -import java.nio.file.OpenOption; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.util.List; +import ch.qos.logback.classic.spi.LoggingEvent; import static ch.qos.logback.classic.Level.WARN; import static org.assertj.core.api.Assertions.assertThat; -import static org.jbake.TestUtils.getTestResourcesAsSourceFolder; -import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class ConfigUtilTest extends LoggingTest { +class ConfigUtilTest extends LoggingTest { private Path sourceFolder; private ConfigUtil util; @BeforeEach - public void setup(@TempDir Path folder) { + void setup(@TempDir Path folder) { this.sourceFolder = folder; this.util = new ConfigUtil(); } @Test - public void shouldLoadSiteHost() throws Exception { + void shouldLoadSiteHost() throws Exception { JBakeConfiguration config = util.loadConfig(TestUtils.getTestResourcesAsSourceFolder()); assertThat(config.getSiteHost()).isEqualTo("http://www.jbake.org"); } @Test - public void shouldLoadADefaultConfiguration() throws Exception { + void shouldLoadADefaultConfiguration() throws Exception { JBakeConfiguration config = util.loadConfig(TestUtils.getTestResourcesAsSourceFolder()); assertDefaultPropertiesPresent(config); } @Test - public void shouldLoadACustomConfiguration() throws Exception { + void shouldLoadACustomConfiguration() throws Exception { File customConfigFile = new File(sourceFolder.toFile(), "jbake.properties"); BufferedWriter writer = new BufferedWriter(new FileWriter(customConfigFile)); @@ -68,7 +64,7 @@ public void shouldLoadACustomConfiguration() throws Exception { } @Test - public void shouldThrowAnExceptionIfSourcefolderDoesNotExist() throws Exception { + void shouldThrowAnExceptionIfSourcefolderDoesNotExist() throws Exception { File nonExistentSourceFolder = mock(File.class); when(nonExistentSourceFolder.getAbsolutePath()).thenReturn("/tmp/nonexistent"); when(nonExistentSourceFolder.exists()).thenReturn(false); @@ -78,7 +74,7 @@ public void shouldThrowAnExceptionIfSourcefolderDoesNotExist() throws Exception } @Test - public void shouldAddSourcefolderToConfiguration() throws Exception { + void shouldAddSourcefolderToConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -87,7 +83,7 @@ public void shouldAddSourcefolderToConfiguration() throws Exception { } @Test - public void shouldThrowAnExceptionIfSourcefolderIsNotADirectory() throws Exception { + void shouldThrowAnExceptionIfSourcefolderIsNotADirectory() throws Exception { File sourceFolder = mock(File.class); when(sourceFolder.exists()).thenReturn(true); @@ -98,7 +94,7 @@ public void shouldThrowAnExceptionIfSourcefolderIsNotADirectory() throws Excepti } @Test - public void shouldReturnDestinationFolderFromConfiguration() throws Exception { + void shouldReturnDestinationFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "output"); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -107,7 +103,7 @@ public void shouldReturnDestinationFolderFromConfiguration() throws Exception { } @Test - public void shouldReturnAssetFolderFromConfiguration() throws Exception { + void shouldReturnAssetFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "assets"); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -116,7 +112,7 @@ public void shouldReturnAssetFolderFromConfiguration() throws Exception { } @Test - public void shouldReturnTemplateFolderFromConfiguration() throws Exception { + void shouldReturnTemplateFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "templates"); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -125,7 +121,7 @@ public void shouldReturnTemplateFolderFromConfiguration() throws Exception { } @Test - public void shouldReturnContentFolderFromConfiguration() throws Exception { + void shouldReturnContentFolderFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedDestinationFolder = new File(sourceFolder, "content"); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -134,7 +130,7 @@ public void shouldReturnContentFolderFromConfiguration() throws Exception { } @Test - public void shouldGetTemplateFileDoctype() throws Exception { + void shouldGetTemplateFileDoctype() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); File expectedTemplateFile = new File(sourceFolder, "templates/index.ftl"); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -147,7 +143,7 @@ public void shouldGetTemplateFileDoctype() throws Exception { } @Test - public void shouldLogWarningIfDocumentTypeNotFound() throws Exception { + void shouldLogWarningIfDocumentTypeNotFound() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -162,7 +158,7 @@ public void shouldLogWarningIfDocumentTypeNotFound() throws Exception { } @Test - public void shouldGetTemplateOutputExtension() throws Exception { + void shouldGetTemplateOutputExtension() throws Exception { String docType = "masterindex"; File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); @@ -175,7 +171,7 @@ public void shouldGetTemplateOutputExtension() throws Exception { } @Test - public void shouldGetMarkdownExtensionsAsList() throws Exception { + void shouldGetMarkdownExtensionsAsList() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); @@ -185,7 +181,7 @@ public void shouldGetMarkdownExtensionsAsList() throws Exception { } @Test - public void shouldReturnConfiguredDocTypes() throws Exception { + void shouldReturnConfiguredDocTypes() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); @@ -197,7 +193,7 @@ public void shouldReturnConfiguredDocTypes() throws Exception { } @Test - public void shouldReturnAListOfAsciidoctorOptionsKeys() throws Exception { + void shouldReturnAListOfAsciidoctorOptionsKeys() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.setProperty("asciidoctor.option.requires", "asciidoctor-diagram"); @@ -209,7 +205,7 @@ public void shouldReturnAListOfAsciidoctorOptionsKeys() throws Exception { } @Test - public void shouldReturnAnAsciidoctorOption() throws Exception { + void shouldReturnAnAsciidoctorOption() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.setProperty("asciidoctor.option.requires", "asciidoctor-diagram"); @@ -221,7 +217,7 @@ public void shouldReturnAnAsciidoctorOption() throws Exception { } @Test - public void shouldReturnAnAsciidoctorOptionWithAListValue() throws Exception { + void shouldReturnAnAsciidoctorOptionWithAListValue() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); config.setProperty("asciidoctor.option.requires", "asciidoctor-diagram"); @@ -233,7 +229,7 @@ public void shouldReturnAnAsciidoctorOptionWithAListValue() throws Exception { } @Test - public void shouldReturnEmptyListIfOptionNotAvailable() throws Exception { + void shouldReturnEmptyListIfOptionNotAvailable() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); @@ -243,7 +239,7 @@ public void shouldReturnEmptyListIfOptionNotAvailable() throws Exception { } @Test - public void shouldLogAWarningIfAsciidocOptionCouldNotBeFound() throws Exception { + void shouldLogAWarningIfAsciidocOptionCouldNotBeFound() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); DefaultJBakeConfiguration config = (DefaultJBakeConfiguration) util.loadConfig(sourceFolder); @@ -257,7 +253,7 @@ public void shouldLogAWarningIfAsciidocOptionCouldNotBeFound() throws Exception } @Test - public void shouldHandleNonExistingFiles() throws Exception { + void shouldHandleNonExistingFiles() throws Exception { File source = TestUtils.getTestResourcesAsSourceFolder(); File expectedTemplateFolder = new File(source, "templates"); @@ -330,7 +326,7 @@ void shouldSetCustomFoldersWithAbsolutePaths() throws Exception { } @Test - public void shouldUseUtf8EncodingAsDefault() throws Exception{ + void shouldUseUtf8EncodingAsDefault() throws Exception { String unicodeString = "中文属性使用默认Properties编码"; JBakeConfiguration config = util.loadConfig(TestUtils.getTestResourcesAsSourceFolder()); @@ -340,7 +336,7 @@ public void shouldUseUtf8EncodingAsDefault() throws Exception{ } @Test - public void shouldBePossibleToSetCustomEncoding() throws Exception { + void shouldBePossibleToSetCustomEncoding() throws Exception { String expected = "Latin1 encoded file äöü"; JBakeConfiguration config = util.setEncoding("ISO8859_1").loadConfig(TestUtils.getTestResourcesAsSourceFolder("/fixtureLatin1")); @@ -349,7 +345,7 @@ public void shouldBePossibleToSetCustomEncoding() throws Exception { } @Test - public void shouldLogAWarningAndFallbackToUTF8IfEncodingIsNotSupported() throws Exception { + void shouldLogAWarningAndFallbackToUTF8IfEncodingIsNotSupported() throws Exception { JBakeConfiguration config = util.setEncoding("UNSUPPORTED_ENCODING").loadConfig(TestUtils.getTestResourcesAsSourceFolder("/fixtureLatin1")); verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture()); @@ -361,7 +357,7 @@ public void shouldLogAWarningAndFallbackToUTF8IfEncodingIsNotSupported() throws @Test - public void shouldReturnIgnoreFileFromConfiguration() throws Exception { + void shouldReturnIgnoreFileFromConfiguration() throws Exception { File sourceFolder = TestUtils.getTestResourcesAsSourceFolder(); JBakeConfiguration config = util.loadConfig(sourceFolder); @@ -370,12 +366,9 @@ public void shouldReturnIgnoreFileFromConfiguration() throws Exception { private void assertDefaultPropertiesPresent(JBakeConfiguration config) throws IllegalAccessException { for (Field field : JBakeConfiguration.class.getFields()) { - - if (field.isAccessible()) { - String key = (String) field.get(""); - System.out.println("Key: " + key); - assertThat(config.get(key)).isNotNull(); - } + String key = (String) field.get(""); + System.out.println("Key: " + key); + assertThat(config.get(key)).isNotNull(); } } diff --git a/jbake-core/src/test/java/org/jbake/app/configuration/PropertyListTest.java b/jbake-core/src/test/java/org/jbake/app/configuration/PropertyListTest.java index 10190307e..9329a0523 100644 --- a/jbake-core/src/test/java/org/jbake/app/configuration/PropertyListTest.java +++ b/jbake-core/src/test/java/org/jbake/app/configuration/PropertyListTest.java @@ -1,20 +1,20 @@ package org.jbake.app.configuration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class PropertyListTest { +class PropertyListTest { @Test - public void getPropertyByKey() { + void getPropertyByKey() { Property property = PropertyList.getPropertyByKey("archive.file"); assertThat(property).isEqualTo(PropertyList.ARCHIVE_FILE); } @Test - public void getCustomProperty() { + void getCustomProperty() { Property property = PropertyList.getPropertyByKey("unknown.option"); assertThat(property.getKey()).isEqualTo("unknown.option"); diff --git a/jbake-core/src/test/java/org/jbake/app/template/AbstractTemplateEngineRenderingTest.java b/jbake-core/src/test/java/org/jbake/app/template/AbstractTemplateEngineRenderingTest.java index 69ee1cab4..e60e21d49 100644 --- a/jbake-core/src/test/java/org/jbake/app/template/AbstractTemplateEngineRenderingTest.java +++ b/jbake-core/src/test/java/org/jbake/app/template/AbstractTemplateEngineRenderingTest.java @@ -23,6 +23,14 @@ */ package org.jbake.app.template; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + import org.apache.commons.io.FileUtils; import org.jbake.app.ContentStoreIntegrationTest; import org.jbake.app.Crawler; @@ -32,23 +40,18 @@ import org.jbake.model.DocumentTypes; import org.jbake.template.ModelExtractors; import org.jbake.template.ModelExtractorsDocumentTypeListener; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; - -import java.io.File; -import java.nio.charset.Charset; -import java.util.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author jdlee */ -public abstract class AbstractTemplateEngineRenderingTest extends ContentStoreIntegrationTest { +abstract class AbstractTemplateEngineRenderingTest extends ContentStoreIntegrationTest { protected final String templateDir; protected final String templateExtension; @@ -65,8 +68,8 @@ public AbstractTemplateEngineRenderingTest(String templateDir, String templateEx this.templateExtension = templateExtension; } - @Before - public void setup() throws Exception { + @BeforeEach + void setup() throws Exception { currentLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); @@ -78,7 +81,7 @@ public void setup() throws Exception { throw new Exception("Cannot find template folder!"); } - destinationFolder = folder.getRoot(); + destinationFolder = folder.resolve("output").toFile(); config.setDestinationFolder(destinationFolder); config.setTemplateFolder(templateFolder); @@ -97,7 +100,7 @@ public void setup() throws Exception { DocumentTypes.addDocumentType("paper"); db.updateSchema(); - Assert.assertEquals(".html", config.getOutputExtension()); + assertEquals(".html", config.getOutputExtension()); Crawler crawler = new Crawler(db, config); crawler.crawl(); @@ -150,15 +153,15 @@ private void setupExpectedOutputStrings() { } - @After - public void cleanup() { + @AfterEach + void cleanup() { DocumentTypes.resetDocumentTypes(); ModelExtractors.getInstance().reset(); Locale.setDefault(currentLocale); } @Test - public void renderPost() throws Exception { + void renderPost() throws Exception { // setup String filename = "second-post.html"; @@ -168,7 +171,7 @@ public void renderPost() throws Exception { content.setUri("/" + filename); renderer.render(content); File outputFile = new File(destinationFolder, filename); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); @@ -178,7 +181,7 @@ public void renderPost() throws Exception { } @Test - public void renderPage() throws Exception { + void renderPage() throws Exception { // setup String filename = "about.html"; @@ -187,7 +190,7 @@ public void renderPage() throws Exception { content.setUri("/" + filename); renderer.render(content); File outputFile = new File(destinationFolder, filename); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); @@ -197,13 +200,13 @@ public void renderPage() throws Exception { } @Test - public void renderIndex() throws Exception { + void renderIndex() throws Exception { //exec renderer.renderIndex("index.html"); //validate File outputFile = new File(destinationFolder, "index.html"); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); @@ -213,10 +216,10 @@ public void renderIndex() throws Exception { } @Test - public void renderFeed() throws Exception { + void renderFeed() throws Exception { renderer.renderFeed("feed.xml"); File outputFile = new File(destinationFolder, "feed.xml"); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); @@ -226,10 +229,10 @@ public void renderFeed() throws Exception { } @Test - public void renderArchive() throws Exception { + void renderArchive() throws Exception { renderer.renderArchive("archive.html"); File outputFile = new File(destinationFolder, "archive.html"); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); @@ -239,12 +242,12 @@ public void renderArchive() throws Exception { } @Test - public void renderTags() throws Exception { + void renderTags() throws Exception { renderer.renderTags("tags"); // verify File outputFile = new File(destinationFolder + File.separator + "tags" + File.separator + "blog.html"); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); for (String string : getOutputStrings("tags")) { assertThat(output).contains(string); @@ -252,27 +255,26 @@ public void renderTags() throws Exception { } @Test - public void renderTagsIndex() throws Exception { + void renderTagsIndex() throws Exception { config.setRenderTagsIndex(true); renderer.renderTags("tags"); File outputFile = new File(destinationFolder + File.separator + "tags" + File.separator + "index.html"); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); for (String string : getOutputStrings("tags-index")) { assertThat(output).contains(string); } - } @Test - public void renderSitemap() throws Exception { + void renderSitemap() throws Exception { DocumentTypes.addDocumentType("paper"); db.updateSchema(); renderer.renderSitemap("sitemap.xml"); File outputFile = new File(destinationFolder, "sitemap.xml"); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); @@ -282,13 +284,8 @@ public void renderSitemap() throws Exception { assertThat(output).doesNotContain("draft-paper.html"); } - protected List getOutputStrings(String type) { - return outputStrings.get(type); - - } - @Test - public void checkDbTemplateModelIsPopulated() throws Exception { + void checkDbTemplateModelIsPopulated() throws Exception { config.setPaginateIndex(true); config.setPostsPerPage(1); @@ -307,4 +304,9 @@ public void checkDbTemplateModelIsPopulated() throws Exception { } } + + protected List getOutputStrings(String type) { + return outputStrings.get(type); + + } } diff --git a/jbake-core/src/test/java/org/jbake/app/template/FreemarkerTemplateEngineRenderingTest.java b/jbake-core/src/test/java/org/jbake/app/template/FreemarkerTemplateEngineRenderingTest.java index de138b8c7..126a2aede 100644 --- a/jbake-core/src/test/java/org/jbake/app/template/FreemarkerTemplateEngineRenderingTest.java +++ b/jbake-core/src/test/java/org/jbake/app/template/FreemarkerTemplateEngineRenderingTest.java @@ -23,28 +23,28 @@ */ package org.jbake.app.template; -import org.apache.commons.io.FileUtils; -import org.junit.Test; - import java.io.File; import java.nio.charset.Charset; import java.util.Arrays; +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.Test; + import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author jdlee */ -public class FreemarkerTemplateEngineRenderingTest extends AbstractTemplateEngineRenderingTest { +class FreemarkerTemplateEngineRenderingTest extends AbstractTemplateEngineRenderingTest { - public FreemarkerTemplateEngineRenderingTest() { + FreemarkerTemplateEngineRenderingTest() { super("freemarkerTemplates", "ftl"); } @Test - public void renderPaginatedIndex() throws Exception { + void renderPaginatedIndex() throws Exception { config.setPaginateIndex(true); config.setPostsPerPage(1); @@ -67,7 +67,7 @@ public void renderPaginatedIndex() throws Exception { } @Test - public void shouldFallbackToRenderSingleIndexIfNoPostArePresent() throws Exception { + void shouldFallbackToRenderSingleIndexIfNoPostArePresent() throws Exception { config.setPaginateIndex(true); config.setPostsPerPage(1); @@ -76,10 +76,10 @@ public void shouldFallbackToRenderSingleIndexIfNoPostArePresent() throws Excepti renderer.renderIndexPaging("index.html"); File paginatedFile = new File(destinationFolder, "index2.html"); - assertFalse("paginated file is not rendered", paginatedFile.exists()); + assertFalse(paginatedFile.exists(), "paginated file is not rendered"); File indexFile = new File(destinationFolder, "index.html"); - assertTrue("index file exists", indexFile.exists()); + assertTrue(indexFile.exists(), "index file exists"); } diff --git a/jbake-core/src/test/java/org/jbake/app/template/GroovyMarkupTemplateEngineRenderingTest.java b/jbake-core/src/test/java/org/jbake/app/template/GroovyMarkupTemplateEngineRenderingTest.java index c40819a19..0dae4cc27 100644 --- a/jbake-core/src/test/java/org/jbake/app/template/GroovyMarkupTemplateEngineRenderingTest.java +++ b/jbake-core/src/test/java/org/jbake/app/template/GroovyMarkupTemplateEngineRenderingTest.java @@ -1,25 +1,22 @@ package org.jbake.app.template; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; + import org.apache.commons.io.FileUtils; import org.jbake.app.Crawler; -import org.jbake.app.DBUtil; import org.jbake.app.Parser; import org.jbake.app.Renderer; import org.jbake.model.DocumentModel; -import org.jbake.model.DocumentTypes; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.File; -import java.nio.charset.Charset; -import java.util.Arrays; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class GroovyMarkupTemplateEngineRenderingTest extends AbstractTemplateEngineRenderingTest { +class GroovyMarkupTemplateEngineRenderingTest extends AbstractTemplateEngineRenderingTest { - public GroovyMarkupTemplateEngineRenderingTest() { + GroovyMarkupTemplateEngineRenderingTest() { super("groovyMarkupTemplates", "tpl"); outputStrings.put("post", Arrays.asList("

          Second Post

          ", @@ -54,7 +51,7 @@ public GroovyMarkupTemplateEngineRenderingTest() { } @Test - public void renderCustomTypePaper() throws Exception { + void renderCustomTypePaper() throws Exception { // setup @@ -69,7 +66,7 @@ public void renderCustomTypePaper() throws Exception { content.setUri("/" + filename); renderer.render(content); File outputFile = new File(destinationFolder, filename); - Assert.assertTrue(outputFile.exists()); + assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile, Charset.defaultCharset()); diff --git a/jbake-core/src/test/java/org/jbake/app/template/GroovyTemplateEngineRenderingTest.java b/jbake-core/src/test/java/org/jbake/app/template/GroovyTemplateEngineRenderingTest.java index d07855bf9..595ad056e 100644 --- a/jbake-core/src/test/java/org/jbake/app/template/GroovyTemplateEngineRenderingTest.java +++ b/jbake-core/src/test/java/org/jbake/app/template/GroovyTemplateEngineRenderingTest.java @@ -23,15 +23,15 @@ */ package org.jbake.app.template; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; /** * * @author jdlee */ -public class GroovyTemplateEngineRenderingTest extends AbstractTemplateEngineRenderingTest { +class GroovyTemplateEngineRenderingTest extends AbstractTemplateEngineRenderingTest { - @BeforeClass + @BeforeAll public static void setUpClass() { //setUpDatabase(StorageType.PLOCAL); } diff --git a/jbake-core/src/test/java/org/jbake/launcher/LaunchOptionsTest.java b/jbake-core/src/test/java/org/jbake/launcher/LaunchOptionsTest.java index 150f9271e..b67e72cc9 100644 --- a/jbake-core/src/test/java/org/jbake/launcher/LaunchOptionsTest.java +++ b/jbake-core/src/test/java/org/jbake/launcher/LaunchOptionsTest.java @@ -1,7 +1,8 @@ package org.jbake.launcher; import org.jbake.app.configuration.ConfigUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import picocli.CommandLine; import picocli.CommandLine.MissingParameterException; @@ -10,17 +11,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -public class LaunchOptionsTest { +class LaunchOptionsTest { @Test - public void showHelp() { + void showHelp() { String[] args = {"-h"}; LaunchOptions res = parseArgs(args); assertThat(res.isHelpNeeded()).isTrue(); } @Test - public void runServer() { + void runServer() { String[] args = {"-s"}; LaunchOptions res = parseArgs(args); @@ -28,7 +29,7 @@ public void runServer() { } @Test - public void runServerWithFolder() { + void runServerWithFolder() { String[] args = {"-s", "/tmp"}; LaunchOptions res = parseArgs(args); @@ -37,7 +38,7 @@ public void runServerWithFolder() { } @Test - public void init() { + void init() { String[] args = {"-i"}; LaunchOptions res = parseArgs(args); @@ -46,7 +47,7 @@ public void init() { } @Test - public void initWithTemplate() { + void initWithTemplate() { String[] args = {"-i", "-t", "foo"}; LaunchOptions res = parseArgs(args); @@ -55,7 +56,7 @@ public void initWithTemplate() { } @Test - public void initWithSourceDirectory() { + void initWithSourceDirectory() { String[] args = {"-i", "/tmp"}; LaunchOptions res = parseArgs(args); @@ -64,7 +65,7 @@ public void initWithSourceDirectory() { } @Test - public void initWithTemplateAndSourceDirectory() { + void initWithTemplateAndSourceDirectory() { String[] args = {"-i", "-t", "foo", "/tmp"}; LaunchOptions res = parseArgs(args); @@ -74,7 +75,7 @@ public void initWithTemplateAndSourceDirectory() { } @Test - public void shouldThrowAnExceptionCallingTemplateWithoutInitOption() { + void shouldThrowAnExceptionCallingTemplateWithoutInitOption() { String[] args = {"-t", "groovy-mte"}; assertThatExceptionOfType(MissingParameterException.class).isThrownBy(()-> { @@ -83,7 +84,7 @@ public void shouldThrowAnExceptionCallingTemplateWithoutInitOption() { } @Test - public void bake() { + void bake() { String[] args = {"-b"}; LaunchOptions res = parseArgs(args); @@ -91,7 +92,7 @@ public void bake() { } @Test - public void listConfig() throws Exception { + void listConfig() throws Exception { String[] args = {"-ls"}; LaunchOptions res = parseArgs(args); @@ -99,7 +100,7 @@ public void listConfig() throws Exception { } @Test - public void listConfigLongOption() throws Exception { + void listConfigLongOption() throws Exception { String[] args = {"--list-settings"}; LaunchOptions res = parseArgs(args); @@ -107,7 +108,7 @@ public void listConfigLongOption() throws Exception { } @Test - public void customPropertiesEncoding() throws Exception { + void customPropertiesEncoding() throws Exception { String[] args = {"--prop-encoding", "utf-16"}; LaunchOptions res = parseArgs(args); @@ -115,7 +116,7 @@ public void customPropertiesEncoding() throws Exception { } @Test - public void defaultEncodingIsUtf8() throws Exception { + void defaultEncodingIsUtf8() throws Exception { String[] args = {}; LaunchOptions res = parseArgs(args); @@ -123,7 +124,7 @@ public void defaultEncodingIsUtf8() throws Exception { } @Test - public void bakeNoArgs() { + void bakeNoArgs() { String[] args = {}; LaunchOptions res = parseArgs(args); @@ -137,7 +138,7 @@ public void bakeNoArgs() { } @Test - public void bakeWithArgs() { + void bakeWithArgs() { String[] args = {"/tmp/source", "/tmp/destination"}; LaunchOptions res = parseArgs(args); @@ -150,7 +151,7 @@ public void bakeWithArgs() { } @Test - public void configArg() { + void configArg() { String[] args = {"-c", "foo"}; LaunchOptions res = parseArgs(args); assertThat(res.getConfig().getAbsoluteFile().toString()).isEqualTo(System.getProperty("user.dir")+ File.separator + "foo"); diff --git a/jbake-core/src/test/java/org/jbake/launcher/MainTest.java b/jbake-core/src/test/java/org/jbake/launcher/MainTest.java index 0d2083929..c9ddceacf 100644 --- a/jbake-core/src/test/java/org/jbake/launcher/MainTest.java +++ b/jbake-core/src/test/java/org/jbake/launcher/MainTest.java @@ -1,8 +1,11 @@ package org.jbake.launcher; -import ch.qos.logback.classic.spi.LoggingEvent; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.PrintStream; +import java.nio.file.Path; + import org.apache.commons.configuration2.ex.ConfigurationException; -import org.itsallcode.junit.sysextensions.ExitGuard; import org.jbake.TestUtils; import org.jbake.app.JBakeException; import org.jbake.app.LoggingTest; @@ -13,20 +16,16 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import picocli.CommandLine; +import org.mockito.MockedStatic; +import org.mockito.Mockito; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.nio.file.Path; +import ch.qos.logback.classic.spi.LoggingEvent; +import picocli.CommandLine; import static org.assertj.core.api.Assertions.assertThat; -import static org.itsallcode.junit.sysextensions.AssertExit.assertExitWithStatus; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doThrow; @@ -35,7 +34,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@ExtendWith(ExitGuard.class) class MainTest extends LoggingTest { private final PrintStream standardOut = System.out; @@ -196,12 +194,13 @@ void shouldTellUserThatTemplateOptionRequiresInitOption() { String[] args = {"-t", "groovy-mte"}; - assertExitWithStatus(SystemExit.CONFIGURATION_ERROR.getStatus(), ()->Main.main(args)); - - verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture()); - - LoggingEvent loggingEvent = captorLoggingEvent.getValue(); - assertThat(loggingEvent.getMessage()).isEqualTo("Error: Missing required argument(s): --init"); + try (MockedStatic utilities = Mockito.mockStatic(BakeOff.class)) { + Main.main(args); + verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture()); + LoggingEvent loggingEvent = captorLoggingEvent.getValue(); + assertThat(loggingEvent.getMessage()).isEqualTo("Error: Missing required argument(s): --init"); + utilities.verify(() -> BakeOff.exit(SystemExit.CONFIGURATION_ERROR.getStatus())); + } } @Test diff --git a/jbake-core/src/test/java/org/jbake/model/DocumentTypesTest.java b/jbake-core/src/test/java/org/jbake/model/DocumentTypesTest.java index 9a664ea31..a83ff3755 100644 --- a/jbake-core/src/test/java/org/jbake/model/DocumentTypesTest.java +++ b/jbake-core/src/test/java/org/jbake/model/DocumentTypesTest.java @@ -1,15 +1,15 @@ package org.jbake.model; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -public class DocumentTypesTest { +class DocumentTypesTest { @Test - public void shouldReturnDefaultDocumentTypes() throws Exception { + void shouldReturnDefaultDocumentTypes() throws Exception { String[] knownDocumentTypes = DocumentTypes.getDocumentTypes(); String[] expectedDocumentType = new String[] {"page", "post", "masterindex", "archive", "feed" }; @@ -17,7 +17,7 @@ public void shouldReturnDefaultDocumentTypes() throws Exception { } @Test - public void shouldAddNewDocumentType() { + void shouldAddNewDocumentType() { String newDocumentType = "newDocumentType"; DocumentTypes.addDocumentType(newDocumentType); @@ -26,7 +26,7 @@ public void shouldAddNewDocumentType() { } @Test - public void shouldAddDocumentTypeOnlyOnce() { + void shouldAddDocumentTypeOnlyOnce() { // A a document type is already known String knownDocumentType = "known"; DocumentTypes.addDocumentType(knownDocumentType); @@ -39,7 +39,7 @@ public void shouldAddDocumentTypeOnlyOnce() { } @Test - public void shouldTellIfDocumentTypeIsKnown() { + void shouldTellIfDocumentTypeIsKnown() { String knownDocumentType = "known"; DocumentTypes.addDocumentType(knownDocumentType); @@ -47,14 +47,14 @@ public void shouldTellIfDocumentTypeIsKnown() { } @Test - public void shouldTellIfDocumentTypeIsUnknown() { + void shouldTellIfDocumentTypeIsUnknown() { String unknownType = "unknown"; assertThat( DocumentTypes.contains(unknownType) ).isFalse(); } @Test - public void shouldNotifyListenersWhenNewDocumentTypeIsAdded() { + void shouldNotifyListenersWhenNewDocumentTypeIsAdded() { // A DocumentTypeListener is added String newDocumentType = "newDocumentType"; DocumentTypeListener listener = mock(DocumentTypeListener.class); diff --git a/jbake-core/src/test/java/org/jbake/render/ArchiveRendererTest.java b/jbake-core/src/test/java/org/jbake/render/ArchiveRendererTest.java index 7d49a304e..62a79ed89 100644 --- a/jbake-core/src/test/java/org/jbake/render/ArchiveRendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/ArchiveRendererTest.java @@ -5,9 +5,10 @@ import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.RenderingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -16,10 +17,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class ArchiveRendererTest { +class ArchiveRendererTest { @Test - public void returnsZeroWhenConfigDoesNotRenderArchives() throws RenderingException { + void returnsZeroWhenConfigDoesNotRenderArchives() throws RenderingException { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -34,7 +35,7 @@ public void returnsZeroWhenConfigDoesNotRenderArchives() throws RenderingExcepti } @Test - public void doesNotRenderWhenConfigDoesNotRenderArchives() throws Exception { + void doesNotRenderWhenConfigDoesNotRenderArchives() throws Exception { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -49,7 +50,7 @@ public void doesNotRenderWhenConfigDoesNotRenderArchives() throws Exception { } @Test - public void returnsOneWhenConfigRendersArchives() throws RenderingException { + void returnsOneWhenConfigRendersArchives() throws RenderingException { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -65,7 +66,7 @@ public void returnsOneWhenConfigRendersArchives() throws RenderingException { } @Test - public void doesRenderWhenConfigDoesRenderArchives() throws Exception { + void doesRenderWhenConfigDoesRenderArchives() throws Exception { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -80,8 +81,8 @@ public void doesRenderWhenConfigDoesRenderArchives() throws Exception { verify(mockRenderer, times(1)).renderArchive(anyString()); } - @Test(expected = RenderingException.class) - public void propogatesRenderingException() throws Exception { + @Test + void propagatesRenderingException() throws Exception { ArchiveRenderer renderer = new ArchiveRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -93,11 +94,9 @@ public void propogatesRenderingException() throws Exception { doThrow(new Exception()).when(mockRenderer).renderArchive(anyString()); - renderer.render(mockRenderer, contentStore, configuration); + assertThatThrownBy(() -> renderer.render(mockRenderer, contentStore, configuration)) + .isInstanceOf(RenderingException.class); verify(mockRenderer, never()).renderArchive("random string"); } - } - - diff --git a/jbake-core/src/test/java/org/jbake/render/DocumentsRendererTest.java b/jbake-core/src/test/java/org/jbake/render/DocumentsRendererTest.java index 5985ccc15..c7a9dfe73 100644 --- a/jbake-core/src/test/java/org/jbake/render/DocumentsRendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/DocumentsRendererTest.java @@ -1,5 +1,9 @@ package org.jbake.render; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + import org.jbake.app.ContentStore; import org.jbake.app.DocumentList; import org.jbake.app.Renderer; @@ -8,19 +12,13 @@ import org.jbake.model.DocumentTypes; import org.jbake.model.ModelAttributes; import org.jbake.template.RenderingException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doThrow; @@ -29,9 +27,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class DocumentsRendererTest { +class DocumentsRendererTest { - public DocumentsRenderer documentsRenderer; + private DocumentsRenderer documentsRenderer; private ContentStore db; private Renderer renderer; private JBakeConfiguration configuration; @@ -40,8 +38,8 @@ public class DocumentsRendererTest { @Captor private ArgumentCaptor argument; - @Before - public void setUp() { + @BeforeEach + void setUp() { MockitoAnnotations.initMocks(this); @@ -54,7 +52,7 @@ public void setUp() { } @Test - public void shouldReturnZeroIfNothingHasRendered() throws Exception { + void shouldReturnZeroIfNothingHasRendered() throws Exception { when(db.getUnrenderedContent()).thenReturn(emptyTemplateModelList); @@ -64,7 +62,7 @@ public void shouldReturnZeroIfNothingHasRendered() throws Exception { } @Test - public void shouldReturnCountOfProcessedDocuments() throws Exception { + void shouldReturnCountOfProcessedDocuments() throws Exception { // given: DocumentTypes.addDocumentType("customType"); @@ -85,7 +83,7 @@ public void shouldReturnCountOfProcessedDocuments() throws Exception { } @Test - public void shouldThrowAnExceptionWithCollectedErrorMessages() { + void shouldThrowAnExceptionWithCollectedErrorMessages() { String fakeExceptionMessage = "fake exception"; // expect @@ -116,7 +114,7 @@ public void shouldThrowAnExceptionWithCollectedErrorMessages() { } @Test - public void shouldContainPostNavigation() throws Exception { + void shouldContainPostNavigation() throws Exception { // given DocumentTypes.addDocumentType("customType"); diff --git a/jbake-core/src/test/java/org/jbake/render/Error404RendererTest.java b/jbake-core/src/test/java/org/jbake/render/Error404RendererTest.java index 24281c526..0ac4a4c97 100644 --- a/jbake-core/src/test/java/org/jbake/render/Error404RendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/Error404RendererTest.java @@ -5,16 +5,22 @@ import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.RenderingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class Error404RendererTest { -public class Error404RendererTest { @Test - public void returnsZeroWhenConfigDoesNotRenderError404() throws RenderingException { + void returnsZeroWhenConfigDoesNotRenderError404() throws RenderingException { Error404Renderer renderer = new Error404Renderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -29,7 +35,7 @@ public void returnsZeroWhenConfigDoesNotRenderError404() throws RenderingExcepti } @Test - public void doesNotRenderWhenConfigDoesNotRenderError404() throws Exception { + void doesNotRenderWhenConfigDoesNotRenderError404() throws Exception { Error404Renderer renderer = new Error404Renderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -44,7 +50,7 @@ public void doesNotRenderWhenConfigDoesNotRenderError404() throws Exception { } @Test - public void returnsOneWhenConfigRendersError404() throws RenderingException { + void returnsOneWhenConfigRendersError404() throws RenderingException { Error404Renderer renderer = new Error404Renderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -59,7 +65,7 @@ public void returnsOneWhenConfigRendersError404() throws RenderingException { } @Test - public void doesRenderWhenConfigDoesNotRenderError404() throws Exception { + void doesRenderWhenConfigDoesNotRenderError404() throws Exception { Error404Renderer renderer = new Error404Renderer(); String error404file = "mock404file.html"; @@ -75,8 +81,8 @@ public void doesRenderWhenConfigDoesNotRenderError404() throws Exception { verify(mockRenderer, times(1)).renderError404(error404file); } - @Test(expected = RenderingException.class) - public void propogatesRenderingException() throws Exception { + @Test + void propagatesRenderingException() throws Exception { Error404Renderer renderer = new Error404Renderer(); String error404file = "mock404file.html"; @@ -89,8 +95,7 @@ public void propogatesRenderingException() throws Exception { doThrow(new Exception()).when(mockRenderer).renderError404(anyString()); - int renderResponse = renderer.render(mockRenderer, contentStore, configuration); - - verify(mockRenderer, never()).renderError404(error404file); + assertThatThrownBy(() -> renderer.render(mockRenderer, contentStore, configuration)) + .isInstanceOf(RenderingException.class); } } diff --git a/jbake-core/src/test/java/org/jbake/render/FeedRendererTest.java b/jbake-core/src/test/java/org/jbake/render/FeedRendererTest.java index cb81f1d7d..305876651 100644 --- a/jbake-core/src/test/java/org/jbake/render/FeedRendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/FeedRendererTest.java @@ -5,9 +5,10 @@ import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.RenderingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -16,10 +17,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class FeedRendererTest { +class FeedRendererTest { @Test - public void returnsZeroWhenConfigDoesNotRenderFeeds() throws RenderingException { + void returnsZeroWhenConfigDoesNotRenderFeeds() throws RenderingException { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -34,7 +35,7 @@ public void returnsZeroWhenConfigDoesNotRenderFeeds() throws RenderingException } @Test - public void doesNotRenderWhenConfigDoesNotRenderFeeds() throws Exception { + void doesNotRenderWhenConfigDoesNotRenderFeeds() throws Exception { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -49,7 +50,7 @@ public void doesNotRenderWhenConfigDoesNotRenderFeeds() throws Exception { } @Test - public void returnsOneWhenConfigRendersFeeds() throws RenderingException { + void returnsOneWhenConfigRendersFeeds() throws RenderingException { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -65,7 +66,7 @@ public void returnsOneWhenConfigRendersFeeds() throws RenderingException { } @Test - public void doesRenderWhenConfigDoesRenderFeeds() throws Exception { + void doesRenderWhenConfigDoesRenderFeeds() throws Exception { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); when(configuration.getRenderFeed()).thenReturn(true); @@ -79,8 +80,8 @@ public void doesRenderWhenConfigDoesRenderFeeds() throws Exception { verify(mockRenderer, times(1)).renderFeed(anyString()); } - @Test(expected = RenderingException.class) - public void propogatesRenderingException() throws Exception { + @Test + void propagatesRenderingException() throws Exception { FeedRenderer renderer = new FeedRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -92,7 +93,8 @@ public void propogatesRenderingException() throws Exception { doThrow(new Exception()).when(mockRenderer).renderFeed(anyString()); - renderer.render(mockRenderer, contentStore, configuration); + assertThatThrownBy(() -> renderer.render(mockRenderer, contentStore, configuration)) + .isInstanceOf(RenderingException.class); verify(mockRenderer, never()).renderFeed("random string"); } diff --git a/jbake-core/src/test/java/org/jbake/render/IndexRendererTest.java b/jbake-core/src/test/java/org/jbake/render/IndexRendererTest.java index 40d6f1d8e..90607d67e 100644 --- a/jbake-core/src/test/java/org/jbake/render/IndexRendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/IndexRendererTest.java @@ -5,9 +5,10 @@ import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.RenderingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -16,10 +17,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class IndexRendererTest { +class IndexRendererTest { @Test - public void returnsZeroWhenConfigDoesNotRenderIndices() throws RenderingException { + void returnsZeroWhenConfigDoesNotRenderIndices() throws RenderingException { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -34,7 +35,7 @@ public void returnsZeroWhenConfigDoesNotRenderIndices() throws RenderingExceptio } @Test - public void doesNotRenderWhenConfigDoesNotRenderIndices() throws Exception { + void doesNotRenderWhenConfigDoesNotRenderIndices() throws Exception { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -49,7 +50,7 @@ public void doesNotRenderWhenConfigDoesNotRenderIndices() throws Exception { } @Test - public void returnsOneWhenConfigRendersIndices() throws RenderingException { + void returnsOneWhenConfigRendersIndices() throws RenderingException { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -65,8 +66,8 @@ public void returnsOneWhenConfigRendersIndices() throws RenderingException { } - @Test(expected = RenderingException.class) - public void propagatesRenderingException() throws Exception { + @Test + void propagatesRenderingException() throws Exception { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -78,9 +79,8 @@ public void propagatesRenderingException() throws Exception { doThrow(new Exception()).when(mockRenderer).renderIndex(anyString()); - renderer.render(mockRenderer, contentStore, configuration); - - verify(mockRenderer, never()).renderIndex(anyString()); + assertThatThrownBy(() -> renderer.render(mockRenderer, contentStore, configuration)) + .isInstanceOf(RenderingException.class); } @@ -88,7 +88,7 @@ public void propagatesRenderingException() throws Exception { * @see Issue 332 */ @Test - public void shouldFallbackToStandardIndexRenderingIfPropertyIsMissing() throws Exception { + void shouldFallbackToStandardIndexRenderingIfPropertyIsMissing() throws Exception { IndexRenderer renderer = new IndexRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -104,7 +104,7 @@ public void shouldFallbackToStandardIndexRenderingIfPropertyIsMissing() throws E } @Test - public void shouldRenderPaginatedIndex() throws Exception { + void shouldRenderPaginatedIndex() throws Exception { IndexRenderer renderer = new IndexRenderer(); @@ -119,7 +119,6 @@ public void shouldRenderPaginatedIndex() throws Exception { renderer.render(mockRenderer, contentStore, configuration); verify(mockRenderer, times(1)).renderIndexPaging(anyString()); - } } diff --git a/jbake-core/src/test/java/org/jbake/render/RendererTest.java b/jbake-core/src/test/java/org/jbake/render/RendererTest.java index c1cd2f0ce..9c9fdc669 100644 --- a/jbake-core/src/test/java/org/jbake/render/RendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/RendererTest.java @@ -1,5 +1,8 @@ package org.jbake.render; +import java.io.File; +import java.nio.file.Path; + import org.jbake.TestUtils; import org.jbake.app.ContentStore; import org.jbake.app.Renderer; @@ -7,25 +10,22 @@ import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.model.DocumentModel; import org.jbake.template.DelegatingTemplateEngine; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import java.io.File; -import java.net.URL; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class RendererTest { +@ExtendWith(MockitoExtension.class) +class RendererTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private Path folder; private DefaultJBakeConfiguration config; private File outputPath; @@ -35,14 +35,14 @@ public class RendererTest { @Mock private DelegatingTemplateEngine renderingEngine; - @Before - public void setup() throws Exception { + @BeforeEach + void setup() throws Exception { File sourcePath = TestUtils.getTestResourcesAsSourceFolder(); if (!sourcePath.exists()) { throw new Exception("Cannot find base path for test!"); } - outputPath = folder.newFolder("output"); + outputPath = folder.resolve("output").toFile(); config = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(sourcePath); config.setDestinationFolder(outputPath); } @@ -53,14 +53,13 @@ public void setup() throws Exception { * @throws Exception */ @Test - public void testRenderFileWorksWhenPathHasDotInButFileDoesNot() throws Exception { - - Assume.assumeFalse("Ignore running on Windows", TestUtils.isWindows()); + @DisabledOnOs(OS.WINDOWS) + void testRenderFileWorksWhenPathHasDotInButFileDoesNot() throws Exception { String FOLDER = "real.path"; final String FILENAME = "about"; config.setOutputExtension(""); - config.setTemplateFolder(folder.newFolder("templates")); + config.setTemplateFolder(folder.resolve("templates").toFile()); Renderer renderer = new Renderer(db, config, renderingEngine); DocumentModel content = new DocumentModel(); diff --git a/jbake-core/src/test/java/org/jbake/render/ServiceLoaderTest.java b/jbake-core/src/test/java/org/jbake/render/ServiceLoaderTest.java index 05bb6b14d..c3e58e1a8 100644 --- a/jbake-core/src/test/java/org/jbake/render/ServiceLoaderTest.java +++ b/jbake-core/src/test/java/org/jbake/render/ServiceLoaderTest.java @@ -1,7 +1,5 @@ package org.jbake.render; -import org.junit.Test; - import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -10,16 +8,18 @@ import java.util.List; import java.util.ServiceLoader; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ServiceLoaderTest { +class ServiceLoaderTest { @Test - public void testLoadRenderer() throws Exception { + void testLoadRenderer() throws Exception { URL serviceDescription = ClassLoader.getSystemClassLoader().getResource("META-INF/services/org.jbake.render.RenderingTool"); File services = new File(serviceDescription.toURI()); - assertTrue("Service definitions File exists", services.exists()); + assertTrue(services.exists(), "Service definitions File exists"); FileReader fileReader = new FileReader(services); BufferedReader reader = new BufferedReader(fileReader); @@ -32,7 +32,7 @@ public void testLoadRenderer() throws Exception { } while ((serviceProvider = reader.readLine()) != null) { - assertTrue("Rendering tool " + serviceProvider + " loaded", renderingToolClasses.contains(serviceProvider)); + assertTrue(renderingToolClasses.contains(serviceProvider), "Rendering tool " + serviceProvider + " loaded"); } } } diff --git a/jbake-core/src/test/java/org/jbake/render/SitemapRendererTest.java b/jbake-core/src/test/java/org/jbake/render/SitemapRendererTest.java index ecbccc379..ddebc844b 100644 --- a/jbake-core/src/test/java/org/jbake/render/SitemapRendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/SitemapRendererTest.java @@ -5,9 +5,10 @@ import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.RenderingException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -16,10 +17,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class SitemapRendererTest { +class SitemapRendererTest { @Test - public void returnsZeroWhenConfigDoesNotRenderSitemaps() throws RenderingException { + void returnsZeroWhenConfigDoesNotRenderSitemaps() throws RenderingException { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -34,7 +35,7 @@ public void returnsZeroWhenConfigDoesNotRenderSitemaps() throws RenderingExcepti } @Test - public void doesNotRenderWhenConfigDoesNotRenderSitemaps() throws Exception { + void doesNotRenderWhenConfigDoesNotRenderSitemaps() throws Exception { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -49,7 +50,7 @@ public void doesNotRenderWhenConfigDoesNotRenderSitemaps() throws Exception { } @Test - public void returnsOneWhenConfigRendersSitemaps() throws RenderingException { + void returnsOneWhenConfigRendersSitemaps() throws RenderingException { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -65,7 +66,7 @@ public void returnsOneWhenConfigRendersSitemaps() throws RenderingException { } @Test - public void doesRenderWhenConfigDoesRenderSitemaps() throws Exception { + void doesRenderWhenConfigDoesRenderSitemaps() throws Exception { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -80,8 +81,8 @@ public void doesRenderWhenConfigDoesRenderSitemaps() throws Exception { verify(mockRenderer, times(1)).renderSitemap(anyString()); } - @Test(expected = RenderingException.class) - public void propogatesRenderingException() throws Exception { + @Test + void propagatesRenderingException() throws Exception { SitemapRenderer renderer = new SitemapRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -93,11 +94,9 @@ public void propogatesRenderingException() throws Exception { doThrow(new Exception()).when(mockRenderer).renderSitemap(anyString()); - renderer.render(mockRenderer, contentStore, configuration); - - verify(mockRenderer, never()).renderSitemap(anyString()); + assertThatThrownBy(() -> renderer.render(mockRenderer, contentStore, configuration)) + .isInstanceOf(RenderingException.class); } - } diff --git a/jbake-core/src/test/java/org/jbake/render/TagsRendererTest.java b/jbake-core/src/test/java/org/jbake/render/TagsRendererTest.java index 479ff67d6..0afcabf25 100644 --- a/jbake-core/src/test/java/org/jbake/render/TagsRendererTest.java +++ b/jbake-core/src/test/java/org/jbake/render/TagsRendererTest.java @@ -1,17 +1,18 @@ package org.jbake.render; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + import org.jbake.app.ContentStore; import org.jbake.app.Renderer; import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.template.RenderingException; -import org.junit.Test; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -20,10 +21,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class TagsRendererTest { +class TagsRendererTest { @Test - public void returnsZeroWhenConfigDoesNotRenderTags() throws RenderingException { + void returnsZeroWhenConfigDoesNotRenderTags() throws RenderingException { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -38,7 +39,7 @@ public void returnsZeroWhenConfigDoesNotRenderTags() throws RenderingException { } @Test - public void doesNotRenderWhenConfigDoesNotRenderTags() throws Exception { + void doesNotRenderWhenConfigDoesNotRenderTags() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -53,7 +54,7 @@ public void doesNotRenderWhenConfigDoesNotRenderTags() throws Exception { } @Test - public void returnsOneWhenConfigRendersIndices() throws Exception { + void returnsOneWhenConfigRendersIndices() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -74,7 +75,7 @@ public void returnsOneWhenConfigRendersIndices() throws Exception { } @Test - public void doesRenderWhenConfigDoesRenderIndices() throws Exception { + void doesRenderWhenConfigDoesRenderIndices() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -92,8 +93,8 @@ public void doesRenderWhenConfigDoesRenderIndices() throws Exception { verify(mockRenderer, times(1)).renderTags(anyString()); } - @Test(expected = RenderingException.class) - public void propogatesRenderingException() throws Exception { + @Test + void propagatesRenderingException() throws Exception { TagsRenderer renderer = new TagsRenderer(); JBakeConfiguration configuration = mock(DefaultJBakeConfiguration.class); @@ -105,9 +106,8 @@ public void propogatesRenderingException() throws Exception { doThrow(new Exception()).when(mockRenderer).renderTags(anyString()); - renderer.render(mockRenderer, contentStore, configuration); - - verify(mockRenderer, never()).renderTags(anyString()); + assertThatThrownBy(() -> renderer.render(mockRenderer, contentStore, configuration)) + .isInstanceOf(RenderingException.class); } } diff --git a/jbake-core/src/test/java/org/jbake/template/ModelExtractorsDocumentTypeListenerTest.java b/jbake-core/src/test/java/org/jbake/template/ModelExtractorsDocumentTypeListenerTest.java index 3c17c6f97..b99326991 100644 --- a/jbake-core/src/test/java/org/jbake/template/ModelExtractorsDocumentTypeListenerTest.java +++ b/jbake-core/src/test/java/org/jbake/template/ModelExtractorsDocumentTypeListenerTest.java @@ -1,14 +1,14 @@ package org.jbake.template; import org.jbake.model.DocumentTypes; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class ModelExtractorsDocumentTypeListenerTest { +class ModelExtractorsDocumentTypeListenerTest { @Test - public void shouldRegisterExtractorsForCustomType() { + void shouldRegisterExtractorsForCustomType() { // given: "A document type is known" String newDocumentType = "project"; DocumentTypes.addDocumentType(newDocumentType); diff --git a/jbake-core/src/test/java/org/jbake/template/ModelExtractorsTest.java b/jbake-core/src/test/java/org/jbake/template/ModelExtractorsTest.java index 4a98127d5..2ecaf07ea 100644 --- a/jbake-core/src/test/java/org/jbake/template/ModelExtractorsTest.java +++ b/jbake-core/src/test/java/org/jbake/template/ModelExtractorsTest.java @@ -1,25 +1,22 @@ package org.jbake.template; import org.jbake.model.DocumentTypes; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class ModelExtractorsTest { +class ModelExtractorsTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { ModelExtractors.getInstance().reset(); } @Test - public void shouldLoadExtractorsOnInstantiation() { + void shouldLoadExtractorsOnInstantiation() { ModelExtractors.getInstance(); String[] expectedKeys = new String[]{ @@ -46,7 +43,7 @@ public void shouldLoadExtractorsOnInstantiation() { } @Test - public void shouldRegisterExtractorsOnlyForCustomTypes() { + void shouldRegisterExtractorsOnlyForCustomTypes() { String knownDocumentType = "alltag"; DocumentTypes.addDocumentType(knownDocumentType); @@ -56,7 +53,7 @@ public void shouldRegisterExtractorsOnlyForCustomTypes() { } @Test - public void shouldRegisterExtractorsForCustomType() { + void shouldRegisterExtractorsForCustomType() { // A document type is known String newDocumentType = "project"; DocumentTypes.addDocumentType(newDocumentType); @@ -72,15 +69,14 @@ public void shouldRegisterExtractorsForCustomType() { } @Test - public void shouldThrowAnExceptionIfDocumentTypeIsUnknown() { - thrown.expect(UnsupportedOperationException.class); - + void shouldThrowAnExceptionIfDocumentTypeIsUnknown() { String unknownDocumentType = "unknown"; - ModelExtractors.getInstance().registerExtractorsForCustomTypes(unknownDocumentType); + assertThatThrownBy(() -> ModelExtractors.getInstance().registerExtractorsForCustomTypes(unknownDocumentType)) + .isInstanceOf(UnsupportedOperationException.class); } @Test - public void shouldResetToNonCustomizedExtractors() throws Exception { + void shouldResetToNonCustomizedExtractors() throws Exception { //given: // A document type is known @@ -98,6 +94,5 @@ public void shouldResetToNonCustomizedExtractors() throws Exception { //then: assertThat(ModelExtractors.getInstance().keySet().size()).isEqualTo(16); - } } diff --git a/jbake-core/src/test/java/org/jbake/util/HtmlUtilTest.java b/jbake-core/src/test/java/org/jbake/util/HtmlUtilTest.java index 0d5c4f8cc..eaeeca6d7 100644 --- a/jbake-core/src/test/java/org/jbake/util/HtmlUtilTest.java +++ b/jbake-core/src/test/java/org/jbake/util/HtmlUtilTest.java @@ -4,23 +4,23 @@ import org.jbake.app.configuration.ConfigUtil; import org.jbake.app.configuration.DefaultJBakeConfiguration; import org.jbake.model.DocumentModel; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class HtmlUtilTest { +class HtmlUtilTest { private DefaultJBakeConfiguration config; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { config = (DefaultJBakeConfiguration) new ConfigUtil().loadConfig(TestUtils.getTestResourcesAsSourceFolder()); } @Test - public void shouldNotAddBodyHTMLElement() { + void shouldNotAddBodyHTMLElement() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -36,7 +36,7 @@ public void shouldNotAddBodyHTMLElement() { } @Test - public void shouldNotAddSiteHost() { + void shouldNotAddSiteHost() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -52,7 +52,7 @@ public void shouldNotAddSiteHost() { } @Test - public void shouldAddSiteHostWithRelativeImageToDocument() { + void shouldAddSiteHostWithRelativeImageToDocument() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -67,7 +67,7 @@ public void shouldAddSiteHostWithRelativeImageToDocument() { } @Test - public void shouldAddContentPath() { + void shouldAddContentPath() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -83,7 +83,7 @@ public void shouldAddContentPath() { } @Test - public void shouldAddContentPathForCurrentDirectory() { + void shouldAddContentPathForCurrentDirectory() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -99,7 +99,7 @@ public void shouldAddContentPathForCurrentDirectory() { } @Test - public void shouldNotAddRootPath() { + void shouldNotAddRootPath() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -114,7 +114,7 @@ public void shouldNotAddRootPath() { } @Test - public void shouldNotAddRootPathForNoExtension() { + void shouldNotAddRootPathForNoExtension() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -130,7 +130,7 @@ public void shouldNotAddRootPathForNoExtension() { } @Test - public void shouldAddContentPathForNoExtension() { + void shouldAddContentPathForNoExtension() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -145,7 +145,7 @@ public void shouldAddContentPathForNoExtension() { } @Test - public void shouldNotChangeForHTTP() { + void shouldNotChangeForHTTP() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); @@ -161,7 +161,7 @@ public void shouldNotChangeForHTTP() { } @Test - public void shouldNotChangeForHTTPS() { + void shouldNotChangeForHTTPS() { DocumentModel fileContent = new DocumentModel(); fileContent.setRootPath("../../../"); fileContent.setUri("blog/2017/05/first_post.html"); diff --git a/jbake-core/src/test/java/org/jbake/util/PagingHelperTest.java b/jbake-core/src/test/java/org/jbake/util/PagingHelperTest.java index 4913daff3..3113cc304 100644 --- a/jbake-core/src/test/java/org/jbake/util/PagingHelperTest.java +++ b/jbake-core/src/test/java/org/jbake/util/PagingHelperTest.java @@ -1,64 +1,66 @@ package org.jbake.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.core.Is.is; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class PagingHelperTest { -public class PagingHelperTest { @Test - public void getNumberOfPages() throws Exception { + void getNumberOfPages() throws Exception { int expected = 3; int total = 5; int perPage = 2; - PagingHelper helper = new PagingHelper(total,perPage); + PagingHelper helper = new PagingHelper(total, perPage); - Assert.assertEquals( expected, helper.getNumberOfPages() ); + assertEquals(expected, helper.getNumberOfPages()); } @Test - public void shouldReturnRootIndexPage() throws Exception { - PagingHelper helper = new PagingHelper(5,2); + void shouldReturnRootIndexPage() throws Exception { + PagingHelper helper = new PagingHelper(5, 2); String previousFileName = helper.getPreviousFileName(2); - Assert.assertThat("", is( previousFileName) ); + assertThat(previousFileName).isEmpty(); } @Test - public void shouldReturnPreviousFileName() throws Exception { - PagingHelper helper = new PagingHelper(5,2); + void shouldReturnPreviousFileName() throws Exception { + PagingHelper helper = new PagingHelper(5, 2); String previousFileName = helper.getPreviousFileName(3); - Assert.assertThat("2/", is( previousFileName) ); + assertThat(previousFileName).isEqualTo("2/"); } @Test - public void shouldReturnNullIfNoPreviousPageAvailable() throws Exception { - PagingHelper helper = new PagingHelper(5,2); + void shouldReturnNullIfNoPreviousPageAvailable() throws Exception { + PagingHelper helper = new PagingHelper(5, 2); String previousFileName = helper.getPreviousFileName(1); - Assert.assertNull( previousFileName ); + assertNull(previousFileName); } @Test - public void shouldReturnNullIfNextPageNotAvailable() throws Exception { - PagingHelper helper = new PagingHelper(5,2); + void shouldReturnNullIfNextPageNotAvailable() throws Exception { + PagingHelper helper = new PagingHelper(5, 2); String nextFileName = helper.getNextFileName(3); - Assert.assertNull( nextFileName ); + assertNull(nextFileName); } @Test - public void shouldReturnNextFileName() throws Exception { - PagingHelper helper = new PagingHelper(5,2); + void shouldReturnNextFileName() throws Exception { + PagingHelper helper = new PagingHelper(5, 2); String nextFileName = helper.getNextFileName(2); - Assert.assertThat("3/", is( nextFileName) ); + assertThat(nextFileName).isEqualTo("3/"); } -} \ No newline at end of file +} diff --git a/jbake-dist/build.gradle b/jbake-dist/build.gradle index 110718421..3b9abfb67 100644 --- a/jbake-dist/build.gradle +++ b/jbake-dist/build.gradle @@ -39,17 +39,18 @@ dependencies { } task smokeTest(type: Test, dependsOn: installDist) { - group 'Verification' - description 'Runs the integration tests.' + group = 'Verification' + description = 'Runs the integration tests.' setTestClassesDirs sourceSets.smokeTest.output.classesDirs classpath = sourceSets.smokeTest.runtimeClasspath shouldRunAfter test } smokeTest { + useJUnitPlatform() testLogging { events "passed", "skipped", "failed" - exceptionFormat "full" + exceptionFormat = "full" } } diff --git a/jbake-dist/src/smoke-test/java/org/jbake/BuiltInProjectsTest.java b/jbake-dist/src/smoke-test/java/org/jbake/BuiltInProjectsTest.java index 84f9ba51a..318366633 100644 --- a/jbake-dist/src/smoke-test/java/org/jbake/BuiltInProjectsTest.java +++ b/jbake-dist/src/smoke-test/java/org/jbake/BuiltInProjectsTest.java @@ -1,62 +1,51 @@ package org.jbake; -import org.apache.commons.vfs2.util.Os; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - import java.io.File; import java.io.IOException; -import java.util.Arrays; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) -public class BuiltInProjectsTest { +class BuiltInProjectsTest { - @Parameter - public String projectName; - @Parameter(1) - public String extension; - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private Path folder; private File projectFolder; private File templateFolder; private File outputFolder; private String jbakeExecutable; private BinaryRunner runner; - @Parameters(name = " {0} ") - public static Iterable data() { - return Arrays.asList(new Object[][]{ - {"thymeleaf", "thyme"}, - {"freemarker", "ftl"}, - {"jade", "jade"}, - {"groovy", "gsp"}, - {"groovy-mte", "tpl"} - }); - } - - @Before - public void setup() throws IOException { - if (Os.isFamily(Os.OS_FAMILY_WINDOWS)) { + @BeforeEach + void setup() throws IOException { + if (OS.current() == OS.WINDOWS) { jbakeExecutable = new File("build\\install\\jbake\\bin\\jbake.bat").getAbsolutePath(); } else { jbakeExecutable = new File("build/install/jbake/bin/jbake").getAbsolutePath(); } - projectFolder = folder.newFolder("project"); + projectFolder = folder.resolve("project").toFile(); + Files.createDirectory(projectFolder.toPath()); templateFolder = new File(projectFolder, "templates"); outputFolder = new File(projectFolder, "output"); runner = new BinaryRunner(projectFolder); } - @Test - public void shouldBakeWithProject() throws Exception { + @ParameterizedTest + @CsvSource({ + "thymeleaf,thyme", + "freemarker,ftl", + "jade,jade", + "groovy,gsp", + "groovy-mte,tpl" + }) + void shouldBakeWithProject(String projectName, String extension) throws Exception { shouldInitProject(projectName, extension); shouldBakeProject(); } diff --git a/jbake-dist/src/smoke-test/java/org/jbake/ProjectWebsiteTest.java b/jbake-dist/src/smoke-test/java/org/jbake/ProjectWebsiteTest.java index 9ef2d0766..392364ba5 100644 --- a/jbake-dist/src/smoke-test/java/org/jbake/ProjectWebsiteTest.java +++ b/jbake-dist/src/smoke-test/java/org/jbake/ProjectWebsiteTest.java @@ -1,41 +1,38 @@ package org.jbake; -import org.apache.commons.vfs2.util.Os; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; + import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.IOException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; -public class ProjectWebsiteTest { - +class ProjectWebsiteTest { private static final String WEBSITE_REPO_URL = "https://github.com/jbake-org/jbake.org.git"; - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private Path folder; private File projectFolder; private File outputFolder; private String jbakeExecutable; private BinaryRunner runner; - @Before - public void setup() throws IOException, GitAPIException { - Assume.assumeTrue("JDK 7 is not supported for this test", !isJava7()); - if (Os.isFamily(Os.OS_FAMILY_WINDOWS)) { + @BeforeEach + void setup() throws IOException, GitAPIException { + if (OS.current() == OS.WINDOWS) { jbakeExecutable = new File("build\\install\\jbake\\bin\\jbake.bat").getAbsolutePath(); } else { jbakeExecutable = new File("build/install/jbake/bin/jbake").getAbsolutePath(); } - projectFolder = folder.newFolder("project"); + projectFolder = folder.resolve("project").toFile(); new File(projectFolder, "templates"); outputFolder = new File(projectFolder, "output"); @@ -44,11 +41,15 @@ public void setup() throws IOException, GitAPIException { } - private boolean isJava7() { - return System.getProperty("java.specification.version").equals("1.7"); + @Test + void shouldBakeWebsite() throws IOException, InterruptedException { + Process process = runner.runWithArguments(jbakeExecutable, "-b"); + assertThat(process.exitValue()).isEqualTo(0); + assertThat(new File(outputFolder, "index.html")).exists(); + process.destroy(); } - private void cloneJbakeWebsite() throws GitAPIException { + private void cloneJbakeWebsite() throws GitAPIException, IOException { CloneCommand cmd = Git.cloneRepository(); cmd.setBare(false); cmd.setBranch("master"); @@ -56,17 +57,10 @@ private void cloneJbakeWebsite() throws GitAPIException { cmd.setURI(WEBSITE_REPO_URL); cmd.setDirectory(projectFolder); - cmd.call(); + Git cloned = cmd.call(); + cloned.close(); assertThat(new File(projectFolder, "README.md").exists()).isTrue(); } - @Test - public void shouldBakeWebsite() throws IOException, InterruptedException { - Process process = runner.runWithArguments(jbakeExecutable, "-b"); - assertThat(process.exitValue()).isEqualTo(0); - assertThat(new File(outputFolder, "index.html")).exists(); - process.destroy(); - } - } diff --git a/jbake-maven-plugin/build.gradle b/jbake-maven-plugin/build.gradle index 6238eef09..906364a4b 100644 --- a/jbake-maven-plugin/build.gradle +++ b/jbake-maven-plugin/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'de.benediktritter.maven-plugin-development' version "$mavenPluginDevVersion" + id 'org.gradlex.maven-plugin-development' version '1.0.3' id "org.jbake.convention.java-common" } @@ -29,6 +29,8 @@ publishing { } } +checkstyleMain.exclude("org/jbake/maven/HelpMojo.java") + dependencies { implementation project(":jbake-core") @@ -36,17 +38,4 @@ dependencies { compileOnly "org.apache.maven.plugin-tools:maven-plugin-annotations:$mavenAnnotationsVersion" implementation "com.sparkjava:spark-core:$sparkVersion" - - // Include all optional dependencies by default - implementation "org.asciidoctor:asciidoctorj:$asciidoctorjVersion" - implementation "org.codehaus.groovy:groovy:$groovyVersion" - implementation "org.codehaus.groovy:groovy-templates:$groovyVersion" - implementation "org.codehaus.groovy:groovy-dateutil:$groovyVersion" - implementation "org.freemarker:freemarker:$freemarkerVersion" - implementation "org.thymeleaf:thymeleaf:$thymeleafVersion" - implementation "de.neuland-bfi:jade4j:$jade4jVersion" - implementation "com.vladsch.flexmark:flexmark:$flexmarkVersion" - implementation "com.vladsch.flexmark:flexmark-profile-pegdown:$flexmarkVersion" - implementation "io.pebbletemplates:pebble:$pebbleVersion" - implementation "org.yaml:snakeyaml:$snakeYamlVersion" } diff --git a/jbake-maven-plugin/src/main/java/org/jbake/maven/GenerateMojo.java b/jbake-maven-plugin/src/main/java/org/jbake/maven/GenerateMojo.java index fcb70cc91..a265b4442 100644 --- a/jbake-maven-plugin/src/main/java/org/jbake/maven/GenerateMojo.java +++ b/jbake-maven-plugin/src/main/java/org/jbake/maven/GenerateMojo.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import java.io.File; + import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -29,8 +31,6 @@ import org.jbake.app.configuration.JBakeConfiguration; import org.jbake.app.configuration.JBakeConfigurationFactory; -import java.io.File; - /** * Runs jbake on a folder */ diff --git a/jbake-maven-plugin/src/main/java/org/jbake/maven/InlineMojo.java b/jbake-maven-plugin/src/main/java/org/jbake/maven/InlineMojo.java index 5f2a5259f..57ee0a011 100644 --- a/jbake-maven-plugin/src/main/java/org/jbake/maven/InlineMojo.java +++ b/jbake-maven-plugin/src/main/java/org/jbake/maven/InlineMojo.java @@ -34,49 +34,49 @@ @Mojo(name = "inline", requiresDirectInvocation = true, requiresProject = false) public class InlineMojo extends WatchMojo { - /** - * Listen Port - */ - @Parameter(property = "jbake.listenAddress", defaultValue = "127.0.0.1") - private String listenAddress; + /** + * Listen Port + */ + @Parameter(property = "jbake.listenAddress", defaultValue = "127.0.0.1") + private String listenAddress; - /** - * Index File - */ - @Parameter(property = "jbake.indexFile", defaultValue = "index.html") - private String indexFile; + /** + * Index File + */ + @Parameter(property = "jbake.indexFile", defaultValue = "index.html") + private String indexFile; - /** - * Listen Port - */ - @Parameter(property = "jbake.port") - private Integer port; + /** + * Listen Port + */ + @Parameter(property = "jbake.port") + private Integer port; - private int getPort() { - if (this.port == null) { - try { - return createConfiguration().getServerPort(); - } catch (JBakeException e) { - // ignore since default will be returned - } - } else { - return this.port; + private int getPort() { + if (this.port == null) { + try { + return createConfiguration().getServerPort(); + } catch (JBakeException e) { + // ignore since default will be returned + } + } else { + return this.port; + } + return 8820; } - return 8820; - } - protected void stopServer() throws MojoExecutionException { - stop(); - } + protected void stopServer() throws MojoExecutionException { + stop(); + } - protected void initServer() throws MojoExecutionException { - externalStaticFileLocation(outputDirectory.getPath()); + protected void initServer() throws MojoExecutionException { + externalStaticFileLocation(outputDirectory.getPath()); - ipAddress(listenAddress); - port(getPort()); + ipAddress(listenAddress); + port(getPort()); - init(); + init(); - awaitInitialization(); - } + awaitInitialization(); + } } diff --git a/jbake-maven-plugin/src/main/java/org/jbake/maven/SeedMojo.java b/jbake-maven-plugin/src/main/java/org/jbake/maven/SeedMojo.java index 231745705..fe8bdd46b 100644 --- a/jbake-maven-plugin/src/main/java/org/jbake/maven/SeedMojo.java +++ b/jbake-maven-plugin/src/main/java/org/jbake/maven/SeedMojo.java @@ -16,12 +16,6 @@ * limitations under the License. */ -import org.apache.commons.io.IOUtils; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -31,6 +25,12 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import org.apache.commons.io.IOUtils; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; + import static java.lang.String.format; import static java.util.Arrays.asList; import static org.apache.commons.lang3.StringUtils.join; @@ -40,17 +40,17 @@ */ @Mojo(name = "seed", requiresProject = true, requiresDirectInvocation = true) public class SeedMojo extends AbstractMojo { - /** - * Location of the Seeding Zip - */ - @Parameter(property = "jbake.seedUrl", defaultValue = "https://github.com/jbake-org/jbake-template-bootstrap/zipball/master/", required = true) - protected String seedUrl; - - /** - * Location of the Output Directory. - */ - @Parameter(property = "jbake.outputDirectory", defaultValue = "${project.basedir}/src/main/jbake", required = true) - protected File outputDirectory; + /** + * Location of the Seeding Zip + */ + @Parameter(property = "jbake.seedUrl", defaultValue = "https://github.com/jbake-org/jbake-template-bootstrap/zipball/master/", required = true) + protected String seedUrl; + + /** + * Location of the Output Directory. + */ + @Parameter(property = "jbake.outputDirectory", defaultValue = "${project.basedir}/src/main/jbake", required = true) + protected File outputDirectory; /** * Really force overwrite if output dir exists? defaults to false @@ -59,10 +59,11 @@ public class SeedMojo extends AbstractMojo { protected Boolean force; public void execute() throws MojoExecutionException { - if (outputDirectory.exists() && (! force)) + if (outputDirectory.exists() && (!force)) { throw new MojoExecutionException(format("The outputDirectory %s must *NOT* exist. Invoke with jbake.force as true to disregard", outputDirectory.getName())); + } - try { + try { URL url = new URL(seedUrl); File tmpZipFile = File.createTempFile("jbake", ".zip"); @@ -76,19 +77,19 @@ public void execute() throws MojoExecutionException { getLog().info(format("%d bytes downloaded. Unpacking into %s", length, outputDirectory)); unpackZip(tmpZipFile); - } catch (Exception e) { - getLog().info("Oops", e); - throw new MojoExecutionException("Failure when running: ", e); - } - } + } catch (Exception e) { + getLog().info("Oops", e); + throw new MojoExecutionException("Failure when running: ", e); + } + } private void unpackZip(File tmpZipFile) throws IOException { ZipInputStream zis = - new ZipInputStream(new FileInputStream(tmpZipFile)); + new ZipInputStream(new FileInputStream(tmpZipFile)); //get the zipped file list entry ZipEntry ze = zis.getNextEntry(); - while(ze!=null){ + while (ze != null) { if (ze.isDirectory()) { ze = zis.getNextEntry(); continue; diff --git a/jbake-maven-plugin/src/main/java/org/jbake/maven/WatchMojo.java b/jbake-maven-plugin/src/main/java/org/jbake/maven/WatchMojo.java index e359dc099..2bb57f0ae 100644 --- a/jbake-maven-plugin/src/main/java/org/jbake/maven/WatchMojo.java +++ b/jbake-maven-plugin/src/main/java/org/jbake/maven/WatchMojo.java @@ -16,15 +16,14 @@ * limitations under the License. */ -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Mojo; -import org.jbake.maven.util.DirWatcher; - import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.Mojo; +import org.jbake.maven.util.DirWatcher; + import static org.apache.commons.lang3.StringUtils.isBlank; /** @@ -33,80 +32,81 @@ @Mojo(name = "watch", requiresDirectInvocation = true, requiresProject = false) public class WatchMojo extends GenerateMojo { - public void executeInternal() throws MojoExecutionException { - reRender(); + public void executeInternal() throws MojoExecutionException { + reRender(); - Long lastProcessed = System.currentTimeMillis(); + Long lastProcessed = System.currentTimeMillis(); - getLog().info( - "Now listening for changes on path " + inputDirectory.getPath()); + getLog().info( + "Now listening for changes on path " + inputDirectory.getPath()); - initServer(); + initServer(); - DirWatcher dirWatcher = null; + DirWatcher dirWatcher = null; - try { - dirWatcher = new DirWatcher(inputDirectory); - final AtomicBoolean done = new AtomicBoolean(false); - final BufferedReader reader = new BufferedReader( - new InputStreamReader(System.in)); + try { + dirWatcher = new DirWatcher(inputDirectory); + final AtomicBoolean done = new AtomicBoolean(false); + final BufferedReader reader = new BufferedReader( + new InputStreamReader(System.in)); - (new Thread() { - @Override - public void run() { - try { - getLog() - .info("Running. Enter a blank line to finish. Anything else forces re-rendering."); + (new Thread() { + @Override + public void run() { + try { + getLog() + .info("Running. Enter a blank line to finish. Anything else forces re-rendering."); - while (true) { - String line = reader.readLine(); + while (true) { + String line = reader.readLine(); - if (isBlank(line)) { - break; - } + if (isBlank(line)) { + break; + } - reRender(); - } - } catch (Exception exc) { - getLog().info("Ooops", exc); - } finally { - done.set(true); - } - } - }).start(); + reRender(); + } + } catch (Exception exc) { + getLog().info("Ooops", exc); + } finally { + done.set(true); + } + } + }).start(); - dirWatcher.start(); + dirWatcher.start(); - do { - Long result = dirWatcher.processEvents(); + do { + Long result = dirWatcher.processEvents(); - if (null == result) { - // do nothing on purpose - } else if (result >= lastProcessed) { - getLog().info("Refreshing"); + if (null == result) { + // do nothing on purpose + } else if (result >= lastProcessed) { + getLog().info("Refreshing"); - super.reRender(); + super.reRender(); - lastProcessed = Long.valueOf(System.currentTimeMillis()); - } - } while (!done.get()); - } catch (Exception exc) { - getLog().info("Oops", exc); + lastProcessed = Long.valueOf(System.currentTimeMillis()); + } + } while (!done.get()); + } catch (Exception exc) { + getLog().info("Oops", exc); - throw new MojoExecutionException("Oops", exc); - } finally { - getLog().info("Finishing"); + throw new MojoExecutionException("Oops", exc); + } finally { + getLog().info("Finishing"); - if (null != dirWatcher) - dirWatcher.stop(); + if (null != dirWatcher) { + dirWatcher.stop(); + } - stopServer(); + stopServer(); + } } - } - protected void stopServer() throws MojoExecutionException { - } + protected void stopServer() throws MojoExecutionException { + } - protected void initServer() throws MojoExecutionException { - } + protected void initServer() throws MojoExecutionException { + } } diff --git a/jbake-maven-plugin/src/main/java/org/jbake/maven/util/DirWatcher.java b/jbake-maven-plugin/src/main/java/org/jbake/maven/util/DirWatcher.java index 6f8a40d4b..240792e39 100644 --- a/jbake-maven-plugin/src/main/java/org/jbake/maven/util/DirWatcher.java +++ b/jbake-maven-plugin/src/main/java/org/jbake/maven/util/DirWatcher.java @@ -1,70 +1,70 @@ package org.jbake.maven.util; -import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; -import org.apache.commons.io.monitor.FileAlterationMonitor; -import org.apache.commons.io.monitor.FileAlterationObserver; - import java.io.File; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; +import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; +import org.apache.commons.io.monitor.FileAlterationMonitor; +import org.apache.commons.io.monitor.FileAlterationObserver; + /** * Example to watch a directory (or tree) for changes to files. */ public class DirWatcher { - private final FileAlterationObserver observer; + private final FileAlterationObserver observer; - private final FileAlterationMonitor monitor; + private final FileAlterationMonitor monitor; - private final BlockingQueue changeQueue = new ArrayBlockingQueue(1); + private final BlockingQueue changeQueue = new ArrayBlockingQueue(1); - /** - * Creates a WatchService and registers the given directory - */ - public DirWatcher(File dir) throws IOException { - this.observer = new FileAlterationObserver(dir); - this.monitor = new FileAlterationMonitor(1000, observer); + /** + * Creates a WatchService and registers the given directory + */ + public DirWatcher(File dir) throws IOException { + this.observer = new FileAlterationObserver(dir); + this.monitor = new FileAlterationMonitor(1000, observer); - observer.addListener(new FileAlterationListenerAdaptor() { - @Override - public void onFileCreate(File file) { - onUpdated(); - } + observer.addListener(new FileAlterationListenerAdaptor() { + @Override + public void onFileCreate(File file) { + onUpdated(); + } - @Override - public void onFileChange(File file) { - onUpdated(); - } - }); - } + @Override + public void onFileChange(File file) { + onUpdated(); + } + }); + } - public void start() throws Exception { - monitor.start(); - } + public void start() throws Exception { + monitor.start(); + } - public void stop() { - try { - monitor.stop(); - } catch (Exception exc) { + public void stop() { + try { + monitor.stop(); + } catch (Exception exc) { + } } - } - private void onUpdated() { - try { - changeQueue.put(Long.valueOf(System.currentTimeMillis())); - } catch (InterruptedException iex) { - Thread.currentThread().interrupt(); + private void onUpdated() { + try { + changeQueue.put(Long.valueOf(System.currentTimeMillis())); + } catch (InterruptedException iex) { + Thread.currentThread().interrupt(); + } } - } - /** - * Process all events for keys queued to the watcher - */ - public Long processEvents() throws InterruptedException { - return changeQueue.poll(1, TimeUnit.SECONDS); - } -} \ No newline at end of file + /** + * Process all events for keys queued to the watcher + */ + public Long processEvents() throws InterruptedException { + return changeQueue.poll(1, TimeUnit.SECONDS); + } +}