|
Groovy example source code file (StubTestCase.groovy)
The Groovy StubTestCase.groovy source code/* * Copyright 2003-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.tools.stubgenerator import static groovy.io.FileType.* import org.codehaus.groovy.control.CompilerConfiguration import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit import com.thoughtworks.qdox.JavaDocBuilder import com.thoughtworks.qdox.model.JavaClass import org.codehaus.groovy.control.CompilationFailedException /** * Base class for all the stub generator test samples. * <br>
*/
protected void init() {}
/**
* @return the folder containing the sample Groovy and Java sources for the test
*/
protected File sourcesRootPath() {
def nameWithoutTest = this.class.simpleName - 'Test'
def folder = nameWithoutTest[0].toLowerCase() + nameWithoutTest[1..-1]
def testDirectory = new File(StubTestCase.class.classLoader.getResource('.').toURI())
return new File(testDirectory, "../../src/test-resources/stubgenerator/${folder}")
}
/**
* Sole JUnit test method which will delegate to the <code>verifyStubs() method
* in the subclasses of <code>StubTestCase.
*/
void testRun() {
init()
configure()
sourceRootPath = sourcesRootPath()
if (!sourceRootPath && !sourceRootPath.exists()) {
fail "Path doesn't exist: ${sourceRootPath}"
}
def sources = collectSources(sourceRootPath)
if (debug) {
println ">>> Sources to be compiled:"
sources.each { File sourceFile ->
println " -> " + sourceFile.name
println sourceFile.text
}
}
compile(sources)
// use QDox for parsing the Java stubs and Java sources
qdox.addSourceTree sourceRootPath
qdox.addSourceTree stubDir
if (debug) {
println ">>> Stubs generated"
stubDir.eachFileRecurse(FILES) { File stubFile ->
if (stubFile.name ==~ /.*(\.groovy|\.java)/) {
println " -> " + stubFile.name
println stubFile.text
}
}
println ">>> QDox canonical sources"
qdox.classes.each { JavaClass jc ->
println " -> " + jc.fullyQualifiedName
println jc.source
}
println "Verifying the stubs"
}
use (QDoxCategory) {
verifyStubs()
}
}
/**
* Collect all the Groovy and Java sources to be joint compiled.
*
* @param path the root path where to find the sources
* @return a list of files
*/
protected List<File> collectSources(File path) {
def sources = []
path.eachFileRecurse(FILES) { sourceFile ->
if (sourceFile.name ==~ /.*(\.groovy|\.java)/) {
// add all the source files for the compiler to compile
sources << sourceFile
}
}
return sources
}
/**
* Launch the actual compilation -- hence launching the stub generator as well.
*
* @param sources the sources to be compiled
*/
protected void compile(List<File> sources) {
def loader = new GroovyClassLoader(this.class.classLoader)
def cu = new JavaAwareCompilationUnit(config, loader)
cu.addSources(sources as File[])
try {
cu.compile()
if (debug) println "Sources compiled successfully"
} catch (CompilationFailedException any) {
handleCompilationFailure(any)
}
}
/**
* Handle any compilation error that may have happened.
*
* @param any the compilation exception
*/
protected void handleCompilationFailure(CompilationFailedException any) {
def stringWriter = new StringWriter()
any.printStackTrace(new PrintWriter(stringWriter))
fail "Compilation failed for stub generator test:\n${stringWriter.toString()}"
}
/**
* Create a compiler configuration to define a place to store the stubs and compiled classes
*/
protected void configure() {
config = new CompilerConfiguration()
config.with {
targetDirectory = targetDir
jointCompilationOptions = [stubDir: stubDir, keepStubs: true]
}
}
/**
* All tests must implement this method, for doing
*/
abstract void verifyStubs()
/**
* Method providing a useful shortcut for the subclasses, so that you can use <code>classes
* from within the <code>verifyStubs() method, to access all the stubs.
*
* @return an array of QDox' <code>JavaClasses.
*/
protected JavaClass[] getClasses() {
qdox.classes
}
/**
* Retrieves the source code of the Java stub of the fully qualified name class in argument.
* Example:
* <pre>
* assert stubJavaSourceFor('com.foo.Bar').contains(...)
* </code>
*
* @param fqn the fully qualified name of the class
* @return the source code of the class
*/
protected String stubJavaSourceFor(String fqn) {
new File(stubDir, fqn.replace('.' as char, File.separatorChar) + '.java').text
}
/**
* Create a temporary directory.
*
* @return the created temporary directory
* @throws IOException if a temporary directory could not be created
*/
protected static File createTempDirectory() throws IOException {
File tempDirectory = File.createTempFile("stubgentests", Long.toString(System.currentTimeMillis()))
if (!(tempDirectory.delete())) {
throw new IOException("Impossible to delete temporary file: ${tempDirectory.absolutePath}")
}
if (!(tempDirectory.mkdir())) {
throw new IOException("Impossible to create temporary directory: ${tempDirectory.absolutePath}")
}
return tempDirectory
}
/**
* Create sub-folders used in relativeFilePath under the specified directory
*
* @throws IOException if a sub-directory could not be created
*/
protected static void createNecessaryPackageDirs(File path, String relativeFilePath) {
def index = relativeFilePath.lastIndexOf('/')
if(index < 0) return
def relativeDirectories = relativeFilePath.substring(0, index)
def tmpPath = path.absolutePath
relativeDirectories.split('/').each {
if(!tmpPath.endsWith(File.separator)) {
tmpPath = tmpPath + File.separator
}
File newDir = new File(tmpPath + it)
if(!newDir.exists()) {
if (!(newDir.mkdir())) {
throw new IOException("Impossible to create package directory: ${newDir.absolutePath}")
}
}
tmpPath = newDir.absolutePath
}
}
}
|
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.