Saturday, 15 August 2015

Spying with Spock

For Mocking previously we have used, Mockito with Powermock, which extensively provides all the ways to deal with different scenarios (as posted HERE ).

Few days back I came across a situation, where I need to perform Partial Mocking of a Service Class, I thought of exploring Mocking with Spock for something new, and now I can say that I am overwhelmed.

Let me brief about the scenario before going into the coding.
There is a service class, which has got a utility bean injected into it like:


@Service
class FileProcessorImpl implements IProcessor
{
 @Autowired
 App appImpl
 
 
 public File process(File file) throws Exception {
  // TODO Auto-generated method stub
  appImpl.main(file)
  appImpl.subMain(file.canonicalPath)
  return file;
 }
 
}


interface IProcessor {
 File process(File file) throws Exception
}

and the Utility class is:

@Service
class AppImpl implements App
{

 public void main(File args) throws Exception {
  // TODO Auto-generated method stub
  println " I am Implementing $args"
 }

 public void subMain(String args) throws Exception {
  // TODO Auto-generated method stub
  println " I AM A SUBMAIN METHOD IN $args "
 }
 
}

interface App {
 void main(File args) throws Exception
 void subMain(String args) throws Exception
}

So, FileProcessorImpl is the service class, and App is the utility bean type injected into the service class.

Now the requirement is, we want to test the functionality of FileProcessorImpl i.e. process(), but we want to mock the behaviour of App implementation called from within the Service, so that the actual implementation do not get invoked.

Now in order to to this we came up with 2 approaches:

a) Using interfaces
b) Using Spock Mock/Spy

Using interfaces

We have written Test cases here using Spock framework:
Here is the Test class:


@ContextConfiguration(classes=EIPConfig)
class EIPConfigTest extends Specification
{
 
 @Autowired
 IProcessor fileProcessorImpl
 
 
 def "Test Beans"()
 {
  given:
   def output
   def file = new File("C:/Users/MIC/Desktop/web.xml")
   App appMock = [ main: {println ' ****** I am being Overridden ****** '}, subMain: {println ' ****** Submain being Overridden ******'}] as App
   fileProcessorImpl.appImpl = appMock
  
  when:
   output = fileProcessorImpl.process(file)
  
  then:
   output==file
 }
}

The annotation @ContextConfiguration defines a normal Spring Confuguration class which contains all the Bean definitions and also does Package scanning of the beans with @ComponentScan and registers all of them in the ApplicationContext.

So, due to @ContextConfiguration the IProcessor type is injected into the Unit Test Case.

Now if we have look into the given block, we can see that we have provided an implementation of the App interface, and then we have set this reference within the injected IProcessor type.

So when we are calling processorMock.process(.... then the mocked version will get called rather than the original.

Using Spock Spy


@ContextConfiguration(classes=EIPConfig)
class EIPConfigTest extends Specification
{
 
 @Autowired
 IProcessor fileProcessorImpl
 
 
 def "Test Beans"()
 {
  given:
   def output
   def file = new File("C:/Users/MIC/Desktop/web.xml")
   App mockApp = Spy(AppImpl)
   mockApp.main(_) >> {println "****** I am being Overridden ****** '"}
   //mockApp.subMain(_) >> { println ' ****** Submain being Overridden IN $it'}
   fileProcessorImpl.appImpl = mockApp
  
  when:
   output = fileProcessorImpl.process(file)
  
  then:
   output==file
 }
}

Now if we look into the above code snippet, then we can see that we have SPIED the Utility class i.e. AppImpl, and we have provided implementation to the main() only, while the submMain() that will be invoked will be from the Original implementation.

[Please Note: The underscore (_) represents any parameter, i.e. it is wildcard representation]

So, the output will be:

****** I am being Overridden ****** '
 I AM A SUBMAIN METHOD IN C:\Users\MIC\Desktop\web.xml

Now if we uncomment subMain(), then the mocked implementation will be called, i.e. we will be providing implementation of only those methods which we want to mock, otherwise not, and then in that case the original implementation will be invoked.

Really this feature is helpful. Apart from using Spy(), you can also check out the Mock() or Stub() feature.

So till next time Keep contributing and Keep coding.
View Subhankar Paul's profile on LinkedIn

Sunday, 9 August 2015

My Tryst with Groovy DSL

In my tryst with Groovy DSL, I went through some blogs describing groovy DSL features.
To explore groovy DSL features in a more vivid way I realized that I need to gather more insight on how groovy AST works.
In this blog I am going to add components to an existing groovy class using Groovy AST, I can co-relate (to some extent) that this groovy AST is somewhat like byte code engineering in Java, it changes the behaviour of components.

To do that I had an encounter with Groovy ASTBuilder class. Now this class does all that magic with the of its 3 methods:

1) buildFromCode(CompilePhase phase = CompilePhase.CLASS_GENERATION, boolean statementsOnly = true, Closure block)
2) buildFromSpec(Closure specification)
3) buildFromString(CompilePhase phase = CompilePhase.CLASS_GENERATION, boolean statementsOnly = true, String source)

With the help of the above 3 methods of the Groovy ASTBuilder class, we can change the Abstract Syntax Tree (AST) of a Groovy class.

Out of these 3 methods, I chose buildFromSpec as this presents a more Groovy DSL rich feature.

While I was browsing, to gain more on Groovy AST with ASTBuilder's buildFromSpec, I came across a post,which converts an annotated method into a main method, i.e. the main method do have all the code block of the annotated method.

I thought of why not integrate the main method in a class with some fresh code block, rather than taking the code block from the existing method,as this will enable to explore a little more on buildFromSpec.

Here the main method that I have implemented using ASTBuilder's buildFromSpec is a overloaded one, i.e. it contains two parameters of type String instead of one.

So here is the code:
The annotation that we will be using is @Main


@Retention (RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@GroovyASTTransformationClass("com.groovy.ast.transformers.MainTransformation")
@interface Main {
}

For this annotation, the Retention type is Source, we will be using the annotation on Element Type and the Groovy AST Transformation class is MainTransformation, this is the class which does the byte code engineering on the class which we will annotate with @Main

The Transformer Class is:

@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class MainTransformation implements ASTTransformation{

 @Override
 public void visit(ASTNode[] astNodes, SourceUnit source) {
  // TODO Auto-generated method stub
  
   if (!astNodes) return
   if (!astNodes[0]) return
   if (!astNodes[1]) return
   if (!(astNodes[0] instanceof AnnotationNode)) return
   if (astNodes[0].classNode?.name != Main.class.getName()) return
   if (!(astNodes[1] instanceof ClassNode)) return

  ClassNode annotatedClass = astNodes[1]
  MethodNode mainMethod = makeMainMethod(null)
  annotatedClass.addMethod(mainMethod)

 }


 MethodNode makeMainMethod(MethodNode source) {

  def ast = new AstBuilder().buildFromSpec {
   method('main', ACC_PUBLIC | ACC_STATIC, Void.TYPE) {
    parameters {
     parameter 'args': String.class
     parameter 'args2': String.class
    }
    exceptions {

     classNode  Exception.class
     classNode  NullPointerException.class

    }
    block {

     expression{
      declaration {
       variable "list"
       token "="
       list {
        constant 1
        constant 2
        constant 3
       }
      }
     }
     ifStatement {
      booleanExpression {
       binary {
        constant "foo"
        token "=="
        constant "foo"
       }


      }



      //if block

      block{

       expression{
        declaration {
         variable "list2"
         token "="
         list {
          constant "Ok1"
          constant "Ok2"
          constant "Ok333333"
         }
        }
       }

       expression { // NOTE: if block and else block are order dependent and same type


        methodCall {
         variable "this"
         constant "println"
         argumentList {
          constant "Hello"
         }
        }
       }

       expression{
        methodCall {
         variable "this"
         constant "println"
         argumentList {
          variable "list2"
         }
        }
       }

      }
      //else block
      expression {
       methodCall {
        variable "this"
        constant "println"
        argumentList {
         constant "World"
        }
       }
      }
     }
    }
   }

  }

  MethodNode newMainMethod = ast[0]
  //newMainMethod.code = source.code
  newMainMethod
  
 }
}


The Model class that we will be annotating is:

@Main
class MainExample {

}

Now lets describe things a little:
When we annotate the class MainExample with @Main, the Groovy Transformation class MainTransformation start doing the magic. This class basically adds a method of signature

public static void main(String args, String args2)
    throws Exception, NullPointerException{
 
 ......
 
 }

within MainExample and this task is performed by the block



 method('main', ACC_PUBLIC | ACC_STATIC, Void.TYPE) {
    parameters {
     parameter 'args': String.class
     parameter 'args2': String.class
    }
    exceptions {

     classNode  Exception.class
     classNode  NullPointerException.class

    }
    
within MainTransformation.
Now within public static void main(String args, String args2), we declare a variable of type list containing 1, 2, 3 and this is being done by


expression{
      declaration {
       variable "list"
       token "="
       list {
        constant 1
        constant 2
        constant 3
       }
      }
     }


Next we have added an if block , now if the block evaluates true then, we will declare another list and print Hello along with the list and this is being done by:

block{

       expression{
        declaration {
         variable "list2"
         token "="
         list {
          constant "Ok1"
          constant "Ok2"
          constant "Ok333333"
         }
        }
       }

       expression {        // NOTE: if block and else block are order dependent and same type


        methodCall {
         variable "this"
         constant "println"
         argumentList {
          constant "Hello"
         }
        }
       }

       expression{
        methodCall {
         variable "this"
         constant "println"
         argumentList {
          variable "list2"
         }
        }
       }

      }

and if the If block evaluated to false, then World will get printed.
The code can be tested as:



class MainExampleTest {

 static main(args)
 {
  def file = new File("./src/com/groovy/ast/model/MainExample.groovy")
  assert file.exists()
  
  def invoker = new TransformTestHelper(new MainTransformation(), CompilePhase.CANONICALIZATION)
  def clazz = invoker.parse(file)
  def tester = clazz.newInstance()
  tester.main(null,null)
 }

}
After we annotate the MainExample with @Main, and compile it, the bytecode of MainExample will contain all the intended changes.
Now the thing that I want to put stress here on is the way the Groovy transformation class implemented.
Here we have used new AstBuilder's buildFromSpec() method which takes a closure as an argument.
Now the closure call is being delgated to AstSpecificationCompiler class which contains all the necessary methods like method(), parameters(), block(), expression() etc..

Because:
 
 public List buildFromSpec(@DelegatesTo(AstSpecificationCompiler.class) Closure specification)
  {
  
  ........
 
 }
 
So when the buildFromSpec() is invoked with the closure as the argument all the method calls are being delegated to AstSpecificationCompiler and each of the methods along with the parameters (if any) also contains a closure as an argument, which is again the method call to another method within AstSpecificationCompiler, i.e. Nested closures!!!!!! Intersting isn't it.

The way we have coded, Groovy Transformation class, is much like writing Business rules and less like coding, that's the beauty of Groovy DSL. This feature of Groovy is really engaging, I must say, and with buildFromCode() Or buildFromString() we won't be getting this flavour.

In my next blog I will try to show to add more components within a class using Groovy ASTBuilder.
Till then keep sharing and keep coding.....

My Tryst with Groovy DSL Part 2

View Subhankar Paul's profile on LinkedIn

Tuesday, 4 August 2015

Groovy AST with DSL

Groovy AST (Abstract Syntax Tree) TRANSFORMATION is one of the interesting features, which I think will everybody would like to explore, because of its intense usefulness and its overwhelming effect.

I will not be going into the details any in-built AST TRANSFORMATION that groovy provides, but I will try to present here, how to write and custom Groovy AST TRANSFORMATION and then adding DSL to do that.
There are several built-in AST TRANSFORMATION groovy provide, which really makes our life easier Like @Canonical, @Bindable, @Veteoble. But in order to understand the working principal of how AST transformation works, I decided to write a Custom AST TRANSFORMATION Implementation.
Objecttive 1: To write an AST transformation that will make the class Serializable.
Now in order to achieve that we need, that the class must implement Serializable.
1) Custom Annotation that will enable us to achive our end. We are going to annotate the class with this annotation, whom do we want to be Serializable.


@Retention (RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@GroovyASTTransformationClass("com.subha.model.SerializeTransformation")
public @interface Serializable {
 
}


The most signification part in the above code is the annotation @GroovyASTTransformationClass which contains the fully qualifies class name of the Transformation class, which will apply the Transformation to the bytecode generated after compilation.
Let's get into the transformation class.


@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
class SerializeTransformation implements ASTTransformation {

 @Override
 public void visit(ASTNode[] astNode, SourceUnit source) {
  // TODO Auto-generated method stub
  
  if (astNode == null || astNode.size() == 0) return
  if (!(astNode[0] instanceof AnnotationNode) || !(astNode[1] instanceof ClassNode)) {
   throw new GroovyBugError("@Serializable must only be applied at type level!")
  }
  AnnotatedNode parent = (AnnotatedNode) astNode[1]
  AnnotationNode node = (AnnotationNode) astNode[0]
  if (parent instanceof ClassNode) {
   ClassNode classNode = (ClassNode) parent
   
  classNode.addInterface(ClassHelper.makeWithoutCaching(java.io.Serializable.class))
  
  }
  
 }

 
}


The first thing is the Compiler Phase where the Transformation needs to be applied, which is being specified by the GroovyASTTransformation annotation. We are applying in the transformation in SEMANTIC_ANALYSIS.
Now these are the following Compiler Phases:

a) INITIALIZATION
b) PARSING
c) CONVERSION
d) SEMANTIC ANALYSIS
e) CANONICALIZATION
f) INSTRUCTION SELECTION
g) CLASS GENERATION
h) OUTPUT
i) FINALIZATION.

We have to be careful, that we cannot apply AST transformation to any of the Compiler Phases we like. If we apply an AST transformation to phase which that we should not, we will be getting a Runtime Exception saying that we cannot do so.

Our Custom transformation class implements ASTTransformation and its corresponding visit method. Within this visit method only we write the code which will apply the required transformation to the target entity.
The visit method takes two parameters: an array of ASTNode and the SourceUnit.

Now in this array, the first element represents the annotation node and the next element represents the parent node where the annotation is applied, Had it been applied at the Method level, we will be getting a MethodNode, had it been at the Class level, we will be getting the ClassNode.

Lets Look into the target class:


@Serializable
class MainExample {
 
 def a = 0
 
 ..............

From the target class we can conclude that, since @Serializable is applied at the class level so ASTNode[1] represents the ClassNode. and ASTNode[0] represents the annotation node.

The next and the most important thing that we are doing in the code block is that we are adding the interface Serializable to the ClassNode.. After compilation of the target, if we decompile it, we will see that the target class SerializeTransformation implements Serializable

Pretty Easy isn't it.
In the next post we will see adding dynamic behaviour to various elements of the class with groovy DSL.
View Subhankar Paul's profile on LinkedIn