Clicky

Grokking Geb Part 1 - Prerequisites

Extremely sorry about the delay on Part 2 of this series. Graduate exams are just round the corner and I am unable to find time for quality research. Exams get over by end of November.

I thoroughly enjoy Geb and I think it is the most stylish way to write functional tests. So, I could promise you one thing - this is going to be a fun ride.

Tools

This is Part 1 of i-dont-know-how-many parts of how to build some cool functional/smoke tests with reporting abilities based on Geb. The end goal will be to replace the stack mentioned here.

So, the Prerequisites :

  1. Some Groovy Magic. Most of all that you need to learn Groovy is covered in this manual but for obvious reasons if you get obsessed with the language you might want to consider Groovy in Action. If you are from a Java (except for closures) or a Python background, you could probably skim through the tutorial for 15 minutes and you are there already).

  2. A little Selenium. The more, the better but fear not this single page tells you all that you need to know about the Selenium Webdriver that you would generally use.

  3. jQuery selectors (everybody says that it is easy but frankly, I refer to the manual at least twice per hour. I am dumb, so…). If you are new to jQuery, you would want to start from basic selectors and click on the left navigation menu for more.

  4. PageObjects is actually not a prerequisite for Geb but PageObjects are so awesome that you never wanted to think about Geb outside of it. Interestingly, PageObjects is not a technology that you need to pick. It is cute little pattern which says that you wrap the structure of your HTML page into an Object so that the actual test does not have to deal with it. Hah. Got you. Let me put that in plain English.

Say, you have a registration form with input textbox which has an id of “nametext”. How would you get the handle of the textbox? In DOM terms, in javascript, you would just do a

1
   document.getElementById("nametext")

In Selenium, you would do a very similar thing

1
 driver.findElement(By.id("nametext"))

So, if you would want to populate Jason in your text box in Selenium, you would do a

1
 driver.findElement(By.id("nametext")).sendKeys("Jason");

If you do that for all your input fields, very soon your testcases become ugly and hateful. Instead of that, in OO terms, you encapsulate. You create a new class, say RegistrationPage and wrap your findElement and sendKeys as in :

1
2
3
4
5
6
7
8
9
10
11
12
 public class RegistrationPage{

      
      
      public RegistrationPage fillRegistrationForm(String name, String email){
      
          driver.findElement(By.id("nametext")).sendKeys(name);
          driver.findElement(By.id("emailtext")).sendKeys(email);
  
      }

  }

and from your testcase, you would say

1
2
3
RegistrationPage regPage=new RegistrationPage();
regPage.fillRegistrationForm("Jason","jason@bourne.com");
  

(Even better idea is to wrap your input values into a class and pass it to the fillRegistrationForm)

In fact, Geb leverages PageObjects in a much better way - jQuery selectors to the rescue

1
2
3
4
5
6
7
8
9
   class InputFormPage extends Page{

      

          static content={
          name {$("input", id:"entry_0")}
          emailAddress {$("input", id:"entry_1")}
      }
     }

and in your testcase, you would just say

1
2
name.value ("Jason")
emailAddress.value ("jason@bourne.com")

(you could do even better. Stay tuned)

Architexa - a Fine Code Reading Tool

I love reading code.

For two reasons :

  1. If the code is bad, it is an awesome ego boost PLUS you get to foul mouth someone who has a good reputation for designing amazing things.

  2. If the code is good, then you get to learn some new tricks and some cool patterns yet to be published anywhere

Architexa - Logo

I am sure you read a lot of code and I am sure you’ll love this awesome code reading tool which I came across a few days ago - Architexa. Architexa also has collaborative documentation support, as I could clearly see with their codemaps project, but I’ve been using primarily for code reading.

Hey, forgot to tell you - Architexa is absolutely free for individual users.

Before going any further, a WOW video is here

A UML diagram is worth a thousand lines of code :

Architexa does not bring in a lot of diagrams but only the most relevant.

  1. Class diagram - for Static view
  2. Sequence diagram - for Dynamic view
  3. Layered diagram (package diagram + awesomeness) - for overall project static view

Class first - Class diagrams :

Imagine you are assigned to a new project or you are simply opening up an open source library to check its implementation.

If you are like me, you would probably

  1. go directly to the class that you are interested and start from there
  2. check all the methods of the class in the Outline window
  3. go to the method of choice and start drawing a Class dependency graph on your mind using the caller and the callee hierarchy.

Architexa - Generate Class Diagram

With Architexa, all you need to do is to throw all your classes into a diagram. Inheritence hierarchy gets automatically mapped by default.

Architexa - Class Diagram

If you would like to map the associations (which I always do), then all you need to do is a right click.

Architexa - Show Referencing Types

You get to choose what associates/members you would want to display in your diagram

Architexa - Referencing Types

The best part I like about Architexa is that you could add/remove items that are not of interest to you. No more noisy A3 print outs.

The big picture - Layered diagrams

If you dont have any Class of interest, then you would probably do a package scan - you simply open up all packages and check how the files in the project are arranged. Again, you are trying to construct a Package Dependency graph and identify commonly used design patterns or frameworks. From my personal experience, I always found that idenfifying package dependency is more difficult than individual classes. However, Architexa does it naturally.

The following is a layered representation of a Google web toolkit project where the client and the server folder are dependent on the shared package (for models, of course). The white components indicate that they are siblings.

Architexa - Layered Diagram

Say 1,2,3 - Sequence diagrams

I love the way that the messages are marked with not only its name but also the complete parameter list. And I absolutely love the way that the classes are marked with either a “C” (for class with source), “I” and “E” for interfaces and enums and a “jar icon” if the class is sourced from a bundle. Generics support in messages. FTW !!

Architexa - Sequence Diagram

No more lonely notes

The best part is that the diagrams does not live in isolation. You could just double click on your class component in your diagram and go to the respective class, or double click on your sequence message and go to that method in the code directly. This helps in switching back and forth between code and diagram (Ctrl+F6). Cool huh?

Optionally, you could export your diagram and have a hard copy printed out for reference - in case you hate switching windows.

Notes :

  1. A little disappointment when you are writing in language other than Java. Architexa currently supports only Java. And it is a plugin only for Eclipse. You might want to check with them for support for your other favourite IDEs. Mine is eclipse. I am good.

  2. Referenced constants being a part of the sequence diagrams when you select the “Add All” references is strange but probably would come in handy. You can always remove the Constants files off the sequences, if you dont like them.

  3. I see that the time taken to draw the diagram is stunning and the UI too looks light-weight. It takes no lag to drag and drop a class or remove a component off the diagram. I am running a 16GB + quad core though (show off time !!). YMMV

  4. You could export the diagram as an image in your local file or in their community server (publicly available). However, I understand that if you need to have your own private secured server setup in your intranet you might want to go for an upgraded edition.

  5. No support of Generics on the class diagram could be painful for some but I am not deeply concerned there.

Links :

Architexa Project site

CodeMaps Beta site (Interesting)

A Lazy Developers Introduction to Java Concurrency Executors

I would make a fool out of myself if I tell you that util.concurrent APIs kicks cheetah’s ass when the classes are available since 2004. However, there are some cool features which I would like to revisit. Concurrency experts, now is the time for you to close this window. All others, stay tight for the fun ride.

Thou shall not forget your roots

Executor Service Class diagram

Executor is the root interface with a single execute method. Anything that implements a Runnable interface can passed as a parameter. Silly Executor, however, has no support for Callable though.

No Callable Support from Executor

Good news : ExecutorService interface, which extends Executor, adds support for Callable. Its implementation class is ThreadPoolExecutor.

I am going to pretend that the ScheduledExecutorService interface and its implementation class ScheduledThreadPoolExecutor does not exist as they just add scheduling capabilities on top of the ExecutorService and ThreadPoolExecutor. But remember this class when the powerful but boring java.util.Timer is not enough and a full blown external scheduler is just too much.

If you are new to concurrency or forgot the difference between Callable and Runnable, you might want to read up a little before reading further. A dummy guide is here

The ExecutorService.submit Facts :

The three submit variants :

Future submit(Callable task)
Future submit(Runnable task)
Future submit(Runnable task, T result)

  1. The submit method of the ExecutorService is overloaded and accepts either a Callable or Runnable.

  2. Since the run method of the Runnable returns void, it is no surprise that Future.get always returns a null when the task is complete.

     Future<?>   submit(Runnable task)
    
  3. The other overloaded submit method that accepts a Runnable and a generic returns whatever you passed in as the second parameter as the result.

     <T> Future<T>   submit(Runnable task, T result)
    

In fact, opening up the code (FutureTask), you’ll notice that the RunnableAdapter top level nested class of Executors simply holds the result and returns the same result after the run method is complete.

RunnableAdapter source

In both the cases, if you would like to (you should !) terminate the program instead of your executor thread blocking the program and entering a busy loop, you should call the shutdown method as in

executorService.shutdown()

shutDown facts

You could imagine shutdown as a half-closed door of a mall. No new customers will be let in but the existing customers can leave the mall once they are done.

To reiterate,

  1. shutdown is a polite method. It does not actually shut down the tasks in the pool immediately. It just says that no new tasks will be accepted.

  2. Unless you are executing your tasks using invokeAll, you would need to wait for all tasks in progress to complete. This is achieved by calling the awaitTermination method. (invokeAll and submit examples at the bottom of the post)

  3. Once all the current tasks are done, the executor service shuts down.

If you are in need of an impolite, intruding method which doesn’t care whether the current threads are done with their tasks, then shutdownNow is your guy. However, there’s no guarantee that the method will shutdown the service on the dot but it is the closest you have to immediate shutdown.

On awaitTermination, you could specify the timeout period until which the main thread should wait for the pool threads to complete its tasks.

    ExecutorService executorService=Executors.newFixedThreadPool(10);
    …
    future = executorService.submit(getInstanceOfCallable(count,sum));
    …
    executorService.shutdown();

    if (executorService.awaitTermination(10, TimeUnit.SECONDS)){
        System.out.println("All threads done with their jobs");
    }

Executors - the factory guy

Executors Factory

The classes above are all awesome. But, say, you wanted to create a single thread executor, you would write something like

new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());

Compare that to

Executors.newSingleThreadExecutor()

So, here you go. Executors is a class with just factory methods for creating various forms of executor service with some commonly used defaults. Note that, other than the awesome factory methods, it doesn’t bring any new features to the table.

It is recommended that you have a quick look at the implementation of the factory methods and check if it suits your needs.

The invokeAll and the submit

The All part of invokeAll method of the ExecutorService gives no surprise. It just says that you need to pass in a Collection of Callables. Again, as expected, the method does not return until all the Threads are done with their tasks. So, for cases when you are interested in the result only after all the jobs are complete, invokeAll is your guy.

On the other hand, the submit method returns immediately after the callable is submitted to the executor service. Unless you are doing nothing at all in your call method of your Callable, your worker threads should ideally be running when the submit method returns.

The following samples might be useful for your reference. The programs just tries to find the sum of all the natural numbers till 100 (Brute force, of course)

Further reading :

Alex Miller’s amazing blog

Alex Miller’s concurrency gotchas

Vogella’s article on comparison with original API

Good introduction to concurrency in general

Highly recommended book on Java concurrency