Groovy Half-mock with MockFor - groovy

I want to test the following class:
public class DBSync {
public dbNotify( String path ) {
if (!path) {
return
}
def pathIndex = path.lastIndexOf(File.separator)
if (pathIndex > 0) {
def folder = path[0..pathIndex - 1]
def fileName = path[pathIndex + 1..path.length() - 1]
println "Syncing from directory $folder for filename $fileName"
if (fileName.contains(EXCLUDE_FILE_PATTERN)) {
println "Filename is $EXCLUDE_FILE_PATTERN skipping db write "
return
}
writeToDB(folder, fileName)
}
}
public writeToDB ( folder, file ) {
// inserting to database
}
}
The test class is:
public class TestDBSync {
#Test
public void test() {
def dbSyncContext = new MockFor(DBSync)
def file = "file.zip"
def folder = "data"
def path = folder + File.separator + file
def called = false
// Expect at least one call
mockDBSyncContext.demand.writeToDB(1..1) { String folderargs, String fileargs -> called = true }
mockDBSyncContext.demand.dbNodify(1..1) { String pathargs -> return }
// Obtaining a usuable mock instance
def mockDBSyncProxy = mockDBSyncContext.proxyInstance()
// Fake calling the method
mockDBSyncContext.use {
mockDBSyncProxy.dbNotify(path )
}
// Verify invoked at least once?
mockDBSyncContext.verify(mockDBSyncProxy)
}
}
The test is failing and I am getting the following error:
junit.framework.AssertionFailedError: No call to 'dbNotify' expected
at this point. Still 1 call(s) to 'writeToDB' expected.

Related

Groovy - add missing method to Closure

I am trying to mock dockerImage.inside() call
but I am getting following error. I tried just about anything, but am not able to add inside():
groovy.lang.MissingMethodException: No signature of method: java.lang.String.inside() is applicable for argument types: (String, com.dsl.shared.CustomService$_createMethod_closure15$_closure27) values: [-u root, com.dsl.shared.CustomService$_createMethod_closure15$_closure27#4248ed58]
Possible solutions: size(), size(), intern(), inspect(), find()
at com.dsl.shared.CustomService$_createMethod_closure15.doCall(CustomService.groovy:677)
BuildContentMock.groovy
class BuildContextMock {
String commandCalled
class dockerMock {
def image(def imageName){
return imageName
}
}
dockerMock docker = new dockerMock()
def sh(String command) {
commandCalled = command
}
def usernamePassword(Map inputs) {
inputs
}
def string(Map inputs) {
inputs
}
def withCredentials(List args, Closure closure) {
def delegate = [:]
for (arg in args) {
delegate[arg.get('usernameVariable')] = 'the_username'
delegate[arg.get('passwordVariable')] = 'the_password'
delegate[arg.get('variable')] = 'the_apikey'
}
closure.delegate = delegate
closure()
}
}
CustomServiceTest.groovy
class CustomServiceTest {
#Test
void testCreateMaintenanceWindow() {
def buildContextMock = new BuildContextMock()
def mockForBuildInfo = new MockFor(BuildInfo)
def mockBuildInfo = mockForBuildInfo.proxyInstance()
AEMBuildHelper aemBuildHelper = new AEMBuildHelper(buildContextMock, "artifactory", mockBuildInfo)
CustomService customService = aemBuildHelper.customService
String id = customService.createMethod()
assert id !== null
}
}
CustomService.groovy
class CustomService extends BuildHelper {
String createMaintenanceWindow(){
buildContext.withCredentials(
[buildContext.string(credentialsId:
ApiKey, variable:'ApiKey')]){
this.dockerBuildHelper.getDockerImage(
this.dockerBuildHelper.getWdBuildDockerImageName())
.inside('-u root'){
return sh(script: "test", returnStdout: true).trim()
}
}
}
}
BuildHelper.groovy
class BuildHelper extends ContextHolder implements Serializable {
protected def mavenBuildHelper = null
BuildHelper(buildContext, mavenBuildHelper) {
super(buildContext)
this.mavenBuildHelper = mavenBuildHelper
}
BuildHelper(buildContext, credentialId, buildContainerEntryPointCommand) {
super(buildContext)
this.mavenBuildHelper = new MavenBuildHelper(buildContext, credentialId, buildContainerEntryPointCommand)
}
}
DockerBuildHelper.groovy
class DockerBuildHelper extends BuildHelper {
DockerBuildHelper(buildContext, mavenBuildHelper, credentialsID = null) {
super(buildContext, mavenBuildHelper)
this.artifactoryCredentialsId = credentialsID
}
String getWdBuildDockerImageName() {
return wdBuildDockerImageName
}
String getDockerImage(String imageName) {
return buildContext.docker.image(imageName)
}
}

Groovy: writing dynamically compiled class to disc

In my app I need to compile classes / scripts in runtime.
as a Class:
Class<? extends LoginAdapter> clazz = groovyClassLoader.loadClass name
LoginAdapter la = clazz.newInstance id, logo
or as a Closure:
Closure action = groovyShell.evaluate( script, name ) as Closure
Both ways work like charm.
Now I need to be able to write the compiled classes/scripts to some persistant storage (disc) and later restore them back without compiling from scratch.
How can this be done?
For those who might be interested, this is my programming kata:
class Base {
String answer() { null }
String question() { 'WHAT IS.... ?' }
}
class ClazzSpec extends Specification {
def "test compile"() {
given:
String packageName = 'some.pckg'
String body = """
package $packageName
class SomeClass extends Base {
Closure cl = { a -> println a }
#Override String answer(){ '42' }
String json( m ){ JsonOutput.toJson( m ) }
String longOne( int times ){
times.times{ sleep 100 }
'done'
}
}
"""
CompilerConfiguration cc = new CompilerConfiguration( targetDirectory:new File( './out' ) )
ImportCustomizer imp = new ImportCustomizer()
imp.addStarImports 'groovy.json', Base.package.name
cc.addCompilationCustomizers imp, new ASTTransformationCustomizer( value:1, TimedInterrupt )
new Compiler( cc ).compile packageName + '.SomeClass', body
File base = new File( './out' )
GroovyClassLoader gcl = new GroovyClassLoader()
gcl.addClasspath './out'
Class clazz = gcl.loadClass 'some.pckg.SomeClass'
when:
def inst = clazz.newInstance()
then:
inst.question() == 'WHAT IS.... ?'
inst.answer() == '42'
inst.json( [ q:42 ] ) == '{"q":42}'
inst.longOne( 2 ) == 'done'
when:
inst.longOne 11
then:
thrown TimeoutException
}
}

Gradle: Force Custom Task to always run (no cache)

I wrote up a custom Gradle task to handle some dependency resolution on the file system where the paths are configurable. I want tasks of this type to always run. It seems though they only run once, I'm guessing because the inputs never seem to change.
I am aware of using configurations { resolutionStrategy.cacheChangingModulesFor 0, 'seconds' } to effectively disable the cache, but I only want it to apply to very specific tasks. Also am aware of --rerun-tasks command line prompt, which is also similar. Neither feel like the best solution, there must be a way to set this up properly in the custom task definition.
Follows is my current implementation. I also had a version prior where the first 3 def String statements were instead #Input annotated String declarations.
class ResolveProjectArchiveDependency extends DefaultTask {
def String archiveFilename = ""
def String relativeArchivePath = ""
def String dependencyScope = ""
#OutputFile
File outputFile
#TaskAction
void resolveArtifact() {
def arcFile = project.file("dependencies/"+dependencyScope+"/"+archiveFilename)
def newArcFile = ""
if(project.hasProperty('environmentSeparated') && project.hasProperty('separatedDependencyRoot')){
println "Properties set denoting the prerelease environment is separated"
newArcFile = project.file(project.ext.separatedDependencyRoot+relativeArchivePath+archiveFilename)
} else {
newArcFile = project.file('../../'+relativeArchivePath+archiveFilename)
}
if(!newArcFile.isFile()){
println "Warn: Could not find the latest copy of " + archiveFilename + ".."
if(!arcFile.isFile()) {
println "Error: No version of " + archiveFilename + " can be found"
throw new StopExecutionException(archiveFilename +" missing")
}
}
if(!arcFile.isFile()) {
println archiveFilename + " jar not in dependencies, pulling from archives"
} else {
println archiveFilename + " jar in dependencies. Checking for staleness"
def oldHash = generateMD5(new File(arcFile.path))
def newHash = generateMD5(new File(newArcFile.path))
if(newHash.equals(oldHash)) {
println "Hashes for the jars match. Not pulling in a copy"
return
}
}
//Copy the archive
project.copy {
println "Copying " + archiveFilename
from newArcFile
into "dependencies/"+dependencyScope
}
}
def generateMD5(final file) {
MessageDigest digest = MessageDigest.getInstance("MD5")
file.withInputStream(){is->
byte[] buffer = new byte[8192]
int read = 0
while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
}
byte[] md5sum = digest.digest()
BigInteger bigInt = new BigInteger(1, md5sum)
return bigInt.toString(16)
}
}
Here's an example of usage of the task:
task handleManagementArchive (type: com.moremagic.ResolveProjectArchiveDependency) {
archiveFilename = 'management.jar'
relativeArchivePath = 'management/dist/'
dependencyScope = 'compile/archive'
outputFile = file('dependencies/'+dependencyScope+'/'+archiveFilename)
}
You can achieve this by setting outputs.upToDateWhen { false } on the task.
This can be performed in your build.gradle file:
handleManagementArchive.outputs.upToDateWhen { false }
It can also be done in the constructor of your custom task.
ResolveProjectArchiveDependency() {
outputs.upToDateWhen { false }
}

Groovy function with parameter

I have a class which is paring csv based file, but I would like to put a parameter for the token symbol.
Please let me know how can I change the function and use the function on program.
class CSVParser{
static def parseCSV(file,closure) {
def lineCount = 0
file.eachLine() { line ->
def field = line.tokenize(';')
lineCount++
closure(lineCount,field)
}
}
}
use(CSVParser.class) {
File file = new File("test.csv")
file.parseCSV { index,field ->
println "row: ${index} | ${field[0]} ${field[1]} ${field[2]}"
}
}
You'll have to add the parameter in between the file and closure parameters.
When you create a category class with static methods, the first parameter is the object the method is being called on so file must be first.
Having a closure as the last parameter allows the syntax where the open brace of the closure follows the function invocation without parentheses.
Here's how it would look:
class CSVParser{
static def parseCSV(file,separator,closure) {
def lineCount = 0
file.eachLine() { line ->
def field = line.tokenize(separator)
lineCount++
closure(lineCount,field)
}
}
}
use(CSVParser) {
File file = new File("test.csv")
file.parseCSV(',') { index,field ->
println "row: ${index} | ${field[0]} ${field[1]} ${field[2]}"
}
}
Just add the separator as the second parameter to the parseCSV method:
class CSVParser{
static def parseCSV(file, sep, closure) {
def lineCount = 0
file.eachLine() { line ->
def field = line.tokenize(sep)
closure(++lineCount, field)
}
}
}
use(CSVParser.class) {
File file = new File("test.csv")
file.parseCSV(";") { index,field ->
println "row: ${index} | ${field[0]} ${field[1]} ${field[2]}"
}
}

groovy multithreading

I'm newbie to groovy/grails.
How to implement thread for this code . Had 2500 urls and this was taking hours of time for checking each url.
so i decided to implement multi-thread for this :
Here is my sample code :
def urls = [
"http://www.wordpress.com",
"http://67.192.103.225/QRA.Public/" ,
"http://www.subaru.com",
"http://baldwinfilter.com/products/start.html"
]
def up = urls.collect { ur ->
try {
def url = new URL(ur)
def connection = url.openConnection()
if (connection.responseCode == 200) {
return true
} else {
return false
}
} catch (Exception e) {
return false
}
}
For this code i need to implement multi-threading .
Could any one please suggest me the code.
thanks in advance,
sri.
I would take a look at the Groovy Parallel Systems library. In particular I think that the Parallel collections section would be useful.
Looking at the docs, I believe that collectParallel is a direct drop-in replacement for collect (bearing in mind the obvious caveats about side-effects). The following works fine for me:
def urls = [
"http://www.wordpress.com",
"http://www.subaru.com",
"http://baldwinfilter.com/products/start.html"
]
Parallelizer.doParallel {
def up = urls.collectParallel { ur ->
try {
def url = new URL(ur)
def connection = url.openConnection()
if (connection.responseCode == 200) {
return true
} else {
return false
}
} catch (Exception e) {
return false
}
}
println up
}
See the Groovy docs for an example how to use an ExecutorService to do what you want.
You can use this to check the URL in a separate thread.
class URLReader implements Runnable
{
def valid
def url
URLReader( url ) {
this.url = url
}
void run() {
try {
def connection = url.toURL().openConnection()
valid = ( connection.responseCode == 200 ) as Boolean
} catch ( Exception e ) {
println e.message
valid = Boolean.FALSE
}
}
}
def reader = new URLReader( "http://www.google.com" )
new Thread( reader ).start()
while ( reader.valid == null )
{
Thread.sleep( 500 )
}
println "valid: ${reader.valid}"
Notes: The valid attribute will be either null, Boolean.TRUE or Boolean.FALSE. You'll need to wait for a while to give all the threads a chance to open the connection. Depending on the number of URLs you're checking you will eventually hit a limit of the number of threads / connections you can realistically handle, so should check URLs in batches of the appropriate size.
I think this way is very simple to achieve.
import java.util.concurrent.*
//Thread number
THREADS = 100
pool = Executors.newFixedThreadPool(THREADS)
defer = { c -> pool.submit(c as Callable) }
def urls = [
"http://www.wordpress.com",
"http://www.subaru.com",
]
def getUrl = { url ->
def connection = url.openConnection()
if (connection.responseCode == 200) {
return true
} else {
return false
}
}
def up = urls.collect { ur ->
try {
def url = new URL(ur)
defer{ getUrl(url) }.get()
} catch (Exception e) {
return false
}
}
println up
pool.shutdown()
This is how I implemented:
class ValidateLinks extends Thread{
def valid
def url
ValidateLinks( url ) {
this.url = url
}
void run() {
try {
def connection = url.toURL().openConnection()
connection.setConnectTimeout(5000)
valid = ( connection.responseCode == 200 ) as Boolean
} catch ( Exception e ) {
println url + "-" + e.message
valid = Boolean.FALSE
}
}
}
def threads = [];
urls.each { ur ->
def reader = new ValidateLinks(ur.site_url)
reader.start()
threads.add(reader);
}
while (threads.size() > 0) {
for(int i =0; i < threads.size();i++) {
def tr = threads.get(i);
if (!tr.isAlive()) {
println "URL : " + tr.url + "Valid " + tr.valid
threads.remove(i);
i--;
}
}
}

Resources