Skip to content

Instantly share code, notes, and snippets.

@hgbrown
Created August 30, 2013 14:01
Show Gist options
  • Save hgbrown/6390170 to your computer and use it in GitHub Desktop.
Save hgbrown/6390170 to your computer and use it in GitHub Desktop.
GROOVY:Generate Gradle Groovy Project
#!/usr/bin/env groovy
/**
* Simple script to create a Groovy project using Gradle
*/
def console = System.console()
String projectName = console.readLine("What is the name of the project? ")
String projectFolderName = projectName.replaceAll(" ", "-").toLowerCase()
if(!projectFolderName.matches(/^[a-zA-Z]+[-0-9a-zA-Z]+$/)) {
println "Invalid project name"
System.exit(1)
}
String BASE_DEV_FOLDER = "/home/henryb/Desktop"
["main", "test"].each { srcRoot ->
["groovy", "java", "resources"].each { folder ->
["dummy"].each { defaultPackage ->
String fullFolderPath = """$BASE_DEV_FOLDER/$projectFolderName/src/$srcRoot/$folder/$defaultPackage"""
File file = new File(fullFolderPath)
if(!file.exists()) {
boolean createdFolder = file.mkdirs()
}
}
}
}
String readmeText = """$projectName
""" << "=".multiply(projectName.size()) << """
To run the included tests you can execute the `gradle clean test --daemon` Gradle command.
----
Author: henry.g.brown@gmail.com
Created on: new java.text.SimpleDateFormat('dd MMMM yyyy').format(new Date())
"""
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/README.md", readmeText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/.hgignore", SampleTextForFile.hgIgnoreText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/build.gradle", SampleTextForFile.buildGradleFileText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/main/resources/simplelogger.properties", SampleTextForFile.simpleLoggerText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/main/java/dummy/Greeting.java", SampleTextForFile.greetingText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/test/java/dummy/GreetingTest.java", SampleTextForFile.greetingTestText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/test/groovy/dummy/HelloSpock.groovy", SampleTextForFile.helloSpockText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/test/resources/db.properties", SampleTextForFile.dbConfigText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/test/groovy/dummy/DatabaseDrivenSpec.groovy", SampleTextForFile.databaseDrivenSpecText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/test/groovy/dummy/DatabaseCheckTest.groovy", SampleTextForFile.databaseCheckTestText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/main/groovy/dummy/Publisher.groovy", SampleTextForFile.publisherText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/main/groovy/dummy/Subscriber.groovy", SampleTextForFile.subscriberText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/test/groovy/dummy/PublisherSpec.groovy", SampleTextForFile.publisherSpecText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/main/resources/dummy/placeholder.txt", SampleTextForFile.placeHolderText)
createAndWriteFile("$BASE_DEV_FOLDER/$projectFolderName/src/test/resources/dummy/placeholder.txt", SampleTextForFile.placeHolderText)
def createAndWriteFile(String fileName, String text) {
new File(fileName).write(text, "UTF-8")
}
class SampleTextForFile {
//--------------------------------------------------------------------------------
public static final String hgIgnoreText = """# use glob syntax.
syntax: glob
build
out
test.h2.db
test.trace.db
.gradle
.idea/workspace.xml
"""
//--------------------------------------------------------------------------------
public static final String buildGradleFileText = """apply plugin: 'groovy'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.1.6'
compile 'com.google.guava:guava:14.0.1'
compile 'org.slf4j:slf4j-simple:1.7.5'
testCompile 'junit:junit:4.11'
testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
testCompile 'com.h2database:h2:1.3.172'
}
test {
testLogging {
exceptionFormat = 'full'
}
}
"""
//--------------------------------------------------------------------------------
//
public static final String simpleLoggerText = """#See http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for configuration details
org.slf4j.simpleLogger.defaultLogLevel=info
org.slf4j.simpleLogger.log.dummy=debug
"""
//--------------------------------------------------------------------------------
public static final String greetingText = """package dummy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.base.CharMatcher.WHITESPACE;
import static java.lang.String.format;
public class Greeting {
static final Logger LOGGER = LoggerFactory.getLogger(Greeting.class);
public String greet(String name) {
LOGGER.debug("name=[{}]", name);
return WHITESPACE.trimFrom(format("Hello %s", nullToEmpty(name)));
}
}
"""
//--------------------------------------------------------------------------------
public static final String greetingTestText = """package dummy;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class GreetingTest {
private Greeting greeting;
@Before
public void setUp() throws Exception {
greeting = new Greeting();
}
/*******************************************************
******************** Sanity checks ********************
******************************************************/
@Test
public void shouldHaveCreatedClassUnderTest() {
assertNotNull(greeting);
}
@Test
public void shouldHaveLoggerInClassUnderTest() throws Exception {
assertNotNull(greeting.LOGGER);
}
/*******************************************************
*********** Tests for class under test ****************
******************************************************/
@Test
public void shouldBeAbleToGreetWithName() throws Exception {
final String actualGreeting = greeting.greet("Henry");
assertThat(actualGreeting, is("Hello Henry"));
}
@Test
public void shouldBeAbleToHandleNullNameInGreeting() {
final String actualGreeting = greeting.greet(null);
assertThat(actualGreeting, is("Hello"));
}
}
"""
//--------------------------------------------------------------------------------
public static final String helloSpockText = """package dummy
import spock.lang.Specification
import spock.lang.Unroll
class HelloSpock extends Specification {
/**
* A simple 'When-Then' feature method is used when there is no setup required and you simply want to
* test a stimulus-response scenario.
*/
def "test basic multiplication"() {
when:
def a = 5
def b = 3
then:
a * b == 15
}
/**
* An 'and' block can also be introduced to the 'When-Then' feature to make it clearer.
*/
def "test basic addition"() {
when:
def a = 5
and:
def b = 3
then:
a + b == 8
}
/**
* Demonstrates a 'Given-When-Then' feature method where we do some setup (the 'given')
* block, manipulate the setup (the 'when') block and assert the correct response (the 'then').
*/
def "adding element to an empty list should result in the element being in the list"() {
given:
def a = []
when:
a << "hello"
then:
a.contains("hello")
}
/**
* The blocks in Spock can also contain descriptive messages to make the specification more clear.
*
* The {@code old} method is also a nifty way of capturing state before the {@code then}
* block executes.
*/
def "adding an element to a list of 1 element should increase size of list by 1"() {
given: "a list containing a single element"
def a = ["hello"]
when: "adding another element to the list"
a << "world"
then: "the size of the list should increase by 1"
a.size() == old(a.size()) + 1
}
/**
* The 'Expect-Where' feature method first specifies the assertions and then has a block to initialise the
* state. This type of feature method is very useful for performing data driven tests.
*
* The {@link Unroll} annotation can be used to provide more details of the individual tests being run.
* In this case, it uses the name of the feature method to provide the detail for each test.
*/
@Unroll
def "#name should have length #length"() {
expect:
name.size() == length
where:
name << ["Kirk", "Spock", "Scotty"]
length << [4, 5, 6]
}
/**
* An alternative way to specify the same test above. Which style to use is largely a matter of personal style.
*/
@Unroll("#name should have length of #length")
def "an alternative way of specifying the test above"() {
expect:
name.size() == length
where:
name | length
"Kirk" | 4
"Spock" | 5
"Scotty" | 6
}
}
"""
//--------------------------------------------------------------------------------
public static final String dbConfigText = """#create embedded database in the current working directory
jdbc.url=jdbc:h2:test
jdbc.driverName=org.h2.Driver
jdbc.user=sa
"""
//--------------------------------------------------------------------------------
public static final String databaseDrivenSpecText = """package dummy
import groovy.sql.Sql
import spock.lang.*
class DatabaseDrivenSpec extends Specification {
def config
@Shared sql
// normally an external database would be used,
// and the test data wouldn't have to be inserted here
def setupSpec() {
File file = new File('src/test/resources/db.properties')
java.util.Properties props = new java.util.Properties()
props.load(file.newReader())
def config = new ConfigSlurper().parse(props)
//Sql.newInstance(db.url, db.user, db.password, db.driver)
sql = Sql.newInstance(config.jdbc.url, config.jdbc.user, '', config.jdbc.driverName)
def row = sql.firstRow("select count(*) as num from information_schema.tables where table_name = ?", ['MAXDATA'])
if(row.num == 0) {
sql.execute("create table MAXDATA (id int primary key, a int, b int, c int)")
sql.execute("insert into MAXDATA values (1, 3, 7, 7), (2, 5, 4, 5), (3, 9, 9, 9)")
}
}
def "maximum of two numbers"() {
expect:
Math.max(a, b) == c
where:
[a, b, c] << sql.rows("select a, b, c from maxdata")
}
}
"""
//--------------------------------------------------------------------------------
public static final String databaseCheckTestText = """package dummy
import groovy.sql.Sql
class DatabaseCheckTest extends groovy.util.GroovyTestCase {
void testSomething() {
def sql = Sql.newInstance("jdbc:h2:test", "sa", "", "org.h2.Driver")
def row = sql.firstRow("select count(*) as num from information_schema.tables where table_name = ?", ['MAXDATA'])
println row
}
}
"""
//--------------------------------------------------------------------------------
public static final String placeHolderText = """This is a place holder file. It can be deleted and replaced with content.
"""
//--------------------------------------------------------------------------------
public static final String publisherText = """package dummy
class Publisher {
List<Subscriber> subscribers = []
void send(String message) {
subscribers.each { subscriber ->
subscriber.receive(message)
}
}
}
"""
//--------------------------------------------------------------------------------
public static final String subscriberText = """package dummy
interface Subscriber {
void receive(String message)
}
"""
//--------------------------------------------------------------------------------
public static final String publisherSpecText = """package dummy
import spock.lang.*
class PublisherSpec extends Specification {
Publisher publisher = new Publisher()
Subscriber subscriber = Mock()
Subscriber subscriber2 = Mock()
def setup() {
publisher.subscribers << subscriber
publisher.subscribers << subscriber2
}
def "should send messages to all subscribers"() {
when:
publisher.send("hello")
then:
1 * subscriber.receive("hello") // exactly one call
1 * subscriber2.receive("hello")
}
}
"""
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment