Drag & Drop with Selenium

Using Selenium for web-gui tests is really nice. You can record your workflow with the excelent selenium plugin for firefox and use them to write your own test.
The only problem seems to be Drag&Drop. The senenium runner has some drag&drop methods, but they don’t seem to work in any way. But selenium offeres mouse controll where you can simulate mouse clicks not only at an absolute position, but rather relative to a dom object. So, if your dragable <div> element has ID1 and the dropzone has ID2 you could write the following in your testrunner:

   selenium.mouseDownAt("//div[@id='ID1']","10,10");
   selenium.mouseMoveAt("//div[@id='ID2']","10,10");
   selenium.mouseOver("//div[@id='ID2']");
   selenium.mouseUpAt("//div[@id='ID2']","10,10");

The important command for this is probably the mouseOver one, without that the richfaces d&d component for JSF would not work.

Posted in java, Testing | Tagged , , | 1 Comment

Logging with SLF4J and Guice

After getting angry at the java.util.logger once again i was thinking how to replace it with the SLF4J logger. Although Guice provides a very nice internal binding to java.util.logger, slf4j does offer a much nicer syntax.
The devil is in the detail, as allways … if you want your logger to be initialized with the current class you can’t simply inject the logger … But .. there is a nice tutorial on the guice wiki about injecting a log4j logger. SLF4J works the same.

First you need a new annotiation, like InjectLogger:

import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectLogger {
}

next is a TypeListener, that listenes to org.slf4j.Logger classes with the annotiation InjectLogger:

import java.lang.reflect.Field;

import org.slf4j.Logger;

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

public class Slf4jTypeListener implements TypeListener {

	public <I> void hear(TypeLiteral<I> aTypeLiteral, TypeEncounter<I> aTypeEncounter) {

		for (Field field : aTypeLiteral.getRawType().getDeclaredFields()) {
			if (field.getType() == Logger.class
	            && field.isAnnotationPresent(InjectLogger.class)) {
	        	aTypeEncounter.register(new Slf4jMembersInjector<I>(field));
	        }
	      }
	}
}

Finally, you need the Slf4jMembersInjector, which does the actual injection:

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.MembersInjector;

public class Slf4jMembersInjector<T>  implements MembersInjector<T> {
	private final Field field;
    private final Logger logger;

    Slf4jMembersInjector(Field aField) {
    	field = aField;
    	logger = LoggerFactory.getLogger(field.getDeclaringClass());
    	field.setAccessible(true);
    }

	public void injectMembers(T anArg0) {
		try {
			field.set(anArg0, logger);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}

Now you just need to bind your TypeListener inside your module class:

   bindListener(Matchers.any(), new Slf4jTypeListener());

The actual usage is simple, but instead of @Inject we need to use @InjectLogger :

    @InjectLogger Logger logger;
Posted in guice, java | Tagged , , , | 2 Comments

got the Imon VFD Display (15c2:0036) finally working

The IR part of the SoundGraph 15c2:0036 VFD/IR device was working for quite some time now after a couple of big updates hit lirc (currently it works for the 0.8.5+ cvs version)

One small quirk was still present, the vfd display would not work all the time. There were allways entries like

lirc_imon: vfd_write: send packet failed for packet #1

in the dmesg logfile and the screen would become garbled from time to time.
Turns out to be a timing issue, with a small patch to lirc_imon everything works perfectly !

diff -u -r1.105 lirc_imon.c
--- drivers/lirc_imon/lirc_imon.c       5 Aug 2009 01:17:26 -0000       1.105
+++ drivers/lirc_imon/lirc_imon.c       23 Aug 2009 08:49:15 -0000
@@ -625,8 +625,10 @@
        }

        kfree(control_req);
+       set_current_state(TASK_INTERRUPTIBLE);
+       schedule_timeout(10);

-       return retval;
+       return retval;
 }

 /**

The original patch hat the timeout to 50 jiffies, but that lead to a quite slow updating of the vfd display, commands did take up to two seconds to display on the vfd. Mabye it even works with lower values, but it seems fast enough for me right now.

Next thing to do is to find a way to display the current mpd information on the vfd, the lcdproc way seems a bit oversized. For mpd there is a nice ruby package on http://librmpd.rubyforge.org/ , so getting the information is not a big problem.

Posted in linux | Tagged , , , | Leave a comment

Easymock … or taking the pain out of (j)unit tests

What are Unit tests?

Unit tests are the lowest level of testing, they are whitebox tests, which means you know what the code does do. Unit tests are for testing methods of a class independently without relying to other classes or services.

This sounds good in theory, but can lead to many problems in real life, especially in J2EE enviroments, as the class you are testing depends on lots of other things, from a database connection to http request parameters.
This is one of the reasons why Unit Test Frameworks like JUnit are often (mis-)used as integration tests, for example by providing a database connection in your test. But with a database connection what are you testing ? Your code ? the state of the Database ? The OR-Mapper ? This would be a Black-Box test with too many unknown and out-of-scope variables, you would never know where in which part the error could be.
Thats why it is still very usefull to have unit tests, even if they seem hard and cumbersome to write.

Enter Easymock

With easymock it is possible to mock every Object that has an Interface. Mocking means that the actual implementation of the interface will be replaced with a dummy placeholder class that you can fill with behaviour. For example you could create a mock from HttpServletRequest which you could use to pass request parameters to your class. Another example would be to replace the database connection classes (DAOs) with mocks, so your test class does need a database anymore.

Lets look at an easy example:

public class User {
    public String name;
    public String password;
    public Integer active;
}
public interface UserDao {
     public User find(String name);
}

The actual implementation would connect to the database and fetch the User Object with the matching name.
Now, lets think we would want to test an UserService, which would use the dao to locate an user, test if the user is active and return
the user object or null if the user is inactive. The implementation (with a dependency injection framework like guice) would look like this:

public class UserService {
   private UserDao dao;

   @Inject
   public Userservice(UserDao tempDao)  {
      dao = tempDao;
   }

   public User logon(String name) {
       User tempUser = dao.find(name);
       if (tempUser.active > 0) return tempuser;
       return null;
   }
}

Now this implementation has a simple bug inside, what happens if the dao didn’t find the user ? How would a testcase find that bug ? A first draft could look like this:

import static org.easymock.EasyMock.*;
...
@Test
public void testUserLogon() {
   UserDao mockDao = createMock(UserDao.class);
   fred = new User(1, "Fred",1);
   joe = new User(2,"Joe",-1);
   expect(dao.load(1)).andReturn(fred);
   expect(dao.load(2)).andReturn(joe);
   replay(dao);
   // now we initialize the service with the mocked DAO Object !
   UserService serviceToTest = new UserService(dao);
   User result = serviceToTest.logon("fred");
   assertNotNull(result);
   assertSame(1,user.id);
   result = serviceToTest.logon("joe");
   assertNotNull(result);
   assertSame(2,user.id);

   result = serviceToTest.logon("Unknown");
   assertNull(result);
}

Now, with the help of AtUnit we can simlify the code a lot:

@RunWith(AtUnit.class)
@MockFramework(MockFramework.Option.EASYMOCK) // tells AtUnit to use EasyMock
@Container(Container.Option.GUICE)
public class UserServiceTest {
   @Inject @Unit UserService serviceToTest;
   @Mock UserDao dao;

   @Test
   public void testUserLogon() {
      fred = new User(1, "Fred",1);
      joe = new User(2,"Joe",-1);
      expect(dao.load(1)).andReturn(fred);
      expect(dao.load(2)).andReturn(joe);
      replay(dao);
      User result = serviceToTest.logon("fred");
      assertNotNull(result);
   }
}
Posted in java, Testing | Tagged , , , | Leave a comment