Sunday, July 30, 2006

JUnit tests for known issues, part 3

My quest for a way to handle known issues as JUnit tests seemed already finished, when Marcel Reutegger, a committer of the Apache Jackrabbit project and a developer of the Technology Compatibility Kit (TCK) of JSR 170, displayed some serious JUnit-fu by pointing to the TestResult class in JUnit.

It turns out that JUnit creates a TestResult instance for each test being run and uses that instance to store the test results. It is possible to customize the TestResult being used by overriding the TestCase.createResult() method. You can then decide in TestResult.addFailure(Test, AssertionFailedError) and TestResult.addError(Test, Throwable) whether to skip some failure or error reports. This is what we ended up doing in Jackrabbit.

Digging deeper along these lines I found out that you could actually implement similar functionality also directly in a TestCase subclass, thus avoiding the need to override TestCase.createResult(). The best way to do this is to override the TestCase.runBare() method that gets invoked by TestResult to run the actual test sequence. The customized method can check whether to skip the test and just return without doing anything in such cases.

I implemented this solution as a generic JUnit 3.x ExcludableTestCase class, that you are free to copy and use under the Apache License, version 2.0. The class uses system properties named junit.excludes and junit.includes to determine whether a test should be excluded from the test run. Normally all tests are included, but a test can be excluded by including an identifier of the test in the junit.excludes system property. An exclusion can also be cancelled by including a test identifer in the junit.includes system property. Both system properties can contain multiple whitespace-separated identifiers. See the ExcludableTestCase javadocs for more details.

You can use this class by subclassing your test cases from ExcludableTestCase instead of directly from TestCase:
package my.test.package;
public class MyTestCase extends ExcludableTestCase {
public void testSomething() {
// your test code
}
}

You can then exclude the test case with -Djunit.excludes=my.test.package, -Djunit.excludes=MyTestCase, or -Djunit.excludes=testSomething or a combination of these identifiers. If you've for example excluded all tests in my.test.package, you can selectively enable this test class with -Djunit.includes=MyTestCase.

You can also add a custom identifiers to your test cases. For example, if your test case was written for Bugzilla issue #123, you can identify the test in the constructor like this:
    public MyTestCase(String name) {
super(name);
addIdentifier("#123");
}

Then you can exclude tests for this issue with -Djunit.excludes=#123.

Thursday, July 20, 2006

Jira tips and tricks

Having just filed a number of Graffito issues in the Jira installation at the ASF, I figured it might be useful if I shared some of the tips and tricks I've learned as a relatively heavy user of Jira. Here comes:

  • You can personalize your Dashboard page to show all sorts of custom reports and statistics. I've configured mine to show summary statistics for all the projects I'm involved with and to list all the open issues assigned to me along with some generally useful links.

  • When navigating back and forth over a number of related issues, click the "History" link on the top-right corner to access all the recently visited issues.

  • You can configure the number of issues listed per page by editing your preferences on your profile page. I've set my preferences to 100 issues per page to avoid having to page back and forth over long issue lists.

  • On the same preference editor you can also disable the feature that sends you an email notification of all the actions you've made on the web interface. I usually get those notifications anyhow through the issue mailing lists, so there's no need for duplicates.

  • The "Road Map" tab on a project page gives a nice overview of the TODO's for an upcoming release.

  • There's a "Subversion commits" tab on the issue pages that lists all commits whose commit message includes the key of the respective issue. There are even links to the ViewVC interface. Very useful! The "All" tab shows you both the issue comments, metadata changes, and Subversion commits on a single time-line.

  • When opening an issue from the Issue Navigator, the upper right corner of the issue contains a small box that allows you to "Return to search" or to jump directly to the "Previous" or "Next" issue on the list.

  • You can "Configure" the Issue Navigator to customize the set of columns it displays. I've replaced the default "Bugzilla Id" column with the "Components" column.

  • You can customize any issue search by clicking "Edit" in the top left corner of the Issue Navigator. You can also save such customized filters for future use.

  • You can subscribe the results of any query in your favourite feed aggregator.


There are probably a ton of other nice features that I haven't yet noticed.

Wednesday, July 19, 2006

JUnit tests for known issues, part 2

A few days ago I considered different options for including known issue test cases (ones that you expect to fail) in a JUnit test suite in a way that wouldn't make the full test suite fail. I decided to adopt a solution that uses system properties to selectively enable such known issue test cases. Here's how I implemented it for Apache Jackrabbit using Maven 1 (we're currently working on migrating to Maven 2, so I'll probably post Maven 2 instructions later on).

The first thing to do is to make the known issue tests check for a system property used to enable a test. The example class below illustrates two ways of doing this; either to make the full known issue test code conditional, or to add an early conditional return to skip the known issue. You can either use a single property like "test.known.issues" or different properties to allow fine grained control over which tests are run and which skipped. I like to use the known issue identifier from the issue tracker as the controlling system property, so I can selectively enable the known issue tests for a single reported issue.
public class ExampleTest extends TestCase {

public void testFoo() {
if (Boolean.getBoolean("ISSUE-foo")) {
// test code for "foo"
}
}

public void testBar() {
if (!Boolean.getBoolean("ISSUE-bar")) {
return;
}
// test code for "bar"
}

}

Once this instrumentation is in place, the build system needs to be configured to pass the identified system properties to the code when requested. In Maven 1 this happens through the maven.junit.sysproperties setting in project.properties:
maven.junit.sysproperties=ISSUE-foo ISSUE-bar
ISSUE-foo=false
ISSUE-bar=false

This way the known issue tests will be skipped when normally running "maven test", but can be selectively enabled either on the command line ("maven -DISSUE-foo=true test") or by modifying project.properties or build.properties.

Sunday, July 16, 2006

Volunteering to mentor Graffito

Raphaƫl Luta, mentor of the incubating Apache Graffito project, recently asked for volunteers to help him mentor the Graffito project. Encouraged by my recent ASF membership and the fact that I had been keeping an eye on the project for quite a while, I decided to volunteer.

Before formal appointment as a mentor I've introduced myself on the Graffito mailing list and started getting more familiar with the project. I'm especially interested in the Object/Content Mapping (OCM) framework JCR-mapping that is included as a Graffito subproject, but also on the other parts of the project. Having worked on various content management systems for over ten years since our first pre-Midgard site experiments (including a custom SGML vocabulary mapped to early HTML with DSSSL) with the Greywolves, I'm still eager to learn new approaches like Graffito.

Graffito is both a framework for building content applications and a set of existing portlet components. Although the project is related to Apache Jetspeed-2, the portlets should work on any compliant portal engine. The framework components can also be used outside the portlet model. The project aims also for independence from the underlying content storage, using a generic "Graffito Core Model" and itsderivates as the abstract content model and "Content Server" abstraction for the content storage layer.

The current default content server implementation is based on Apache OJB and runs on top of relational databases. The JCR-mapping subproject is planned to be used for a similar task on top of JCR content repositories, especially Apache Jackrabbit. Just like OJB is not a subproject of Graffito, we've had initial discussion about possibly moving the JCR-mapping project outside Graffito. Making it a Jackrabbit subproject is an interesting alternative, especially if we want to target for an eventual JCR federation within the ASF, but for now I think it's best to get the communities together and see what patterns emerge before making final decisions on what to do with thesubproject.

Missing API details in Java: Null references

Even though Java APIs tend to be well documented thanks to the Javadoc, there are some details that are quite often missing, causing developers to program by coincidence. One of the main issues is the handling of null references.

Although there are guaranteed to be no dangling references on the Java platform, a reference can still be null and cause the infamous NullPointerException (aka NPE) when passed to an unwary piece of code. Null references are very convenient in expressing the absense of something, but I these special cases are often not well documented. There are three main cases of null references that are commonly used but seldom documented: optional arguments, member variables, and return values.

Optional arguments

Instead of overloading a method name to cover the case where one or more of the arguments are unavailable, the method can allow some of its arguments to be null. This is especially common for constructors that allow optional configuration options. This practice is otherwise very convenient, but disturbingly often not documented, leaving the client developer to wonder whether it is OK to pass a null reference to as a seemingly optional method argument. Often the solution is to just pass the null reference and rely on coincidence to keep it working.

A good example is the DocumentBuilder.parse(InputStream stream, String systemId) method in JAXP. It is explicitly documented that an IllegalArgumentException is thrown when the stream argument is null, but the systemId argument is just documented as "Provide a base for resolving relative URIs". There is also an overloaded DocumentBuilder.parse(InputStream stream) method, and incidentally it happens that calling the former method with a null systemId is equivalent to calling the latter method.

Now a JAXP client developer that has an InputStream and system identifier string that might be null, could either do the right thing and program defensively:
if (systemId == null) {
builder.parse(stream);
} else {
builder.parse(stream, systemId);
}

or rely on the coincidence that a null system identifier is actually allowed:
builder.parse(stream, systemId);

The latter case is in my experience what most of the developers would do, and thus the JAXP implementation is in practice required to keep allowing null system identifiers. The systemId argument should therefore be documented as "Optional base for resolving relative URIs" or even more explicitly as "Base for resolving relative URIs, or null".

Member variables

A good practice in Java is to keep all member variables private or at least protected. Unfortunately this allows the developer to be lazy in documenting the permitted states of the variable. After all, a private member is not a part of the public interface of a class, so why bother documenting it. A member variable can be null either by having explicitly been set so or by having been passed as null to a constructor or a setter. Often you need to explicitly search through the sources of a class to determine the possible states of a member variable. This is especially important when using the JavaBean conventions where a private member variable is often exposed trough a getter method with a template javadoc that contains no mention of the valid states of the underlying variable.

The JavaBean case is actually especially troublesome as the common pattern for JavaBean properties is:
private Object something;

/** Returns something */
public Object getSomething() {
return something;
}

/** Sets something */
public void setSomething(Object something) {
this.something = something;
}

It is most often not documented whether null references are allowed in the setter or if the client is required to explicitly set the property before doing anything with a bean instance. This is in my experience the main cause ofNullPointerExceptions in component-based systems.

Return values

Null references are commonly used to represent the absence of some value. For example the Map.get(Object key) method returns null when an entry for the given key is not found in the map. Such cases are usually well documented (the Map.get method returns "the value to which this map maps the specified key, or null if the map contains no mapping for this key"), but in some cases it is just implicitly assumed that a client developer will expect a null return value.

The most common causes of undocumented null return values are the JavaBean getters described above, but sometimes a genuine processing method forgets to mention that the return value might be null. A good example is theZipInputStream.getNextEntry() method, that returns "the ZipEntry just read" but fails to mention that the "ZipEntry just read" is null if no more Zip entries are available. A clever developer will of course assume that this is the case, since the method doesn't throw aNoSuchElementException like the Iterator.next() method does, but the only way to know for sure is to read the ZipInputStream sources and even then you are left with the bad feeling that the implementation might well be changed in a future release.

The return value of the getNextEntry() method should therefore be documented as "the ZipEntry just read, or null if no more entries are available".

Monday, July 10, 2006

UMLet 7

org.apache.jackrabbit.extractor class diagramEver since learning UML back in 1998 I've been looking for decent UML tools that best suit my rather ad-hoc diagramming style. Even though I've occasionally used them, I've never really enjoyed the heavyweight, round-tripping, IDE-integrated (even IDE-embedding!) modelling monoliths that most of the UML tools seem to evolve into sooner or later. My reasons for using UML are documenting existing code and discussing new ideas, almost never to actually implement anything. I usually also work in highly heterogeneous settings with co-developers using a wide variety of tools and development environments. Adapting to a do-all-be-all UML tool is in many cases simply impossible or at least quite difficult.

org.apache.jackrabbit.core.query TextFilter class diagramThus I've actively stayed away from the high-end offerings and focused more on the low-end alternatives like Dia and the most popular UML tool in the world, MS PowerPoint. However they never felt really natural, being either too inflexible or requiring too much manual work especially when rearranging diagrams. Luckily a few years ago, while doing my yearly lookout for better development tools, I stumbled upon UMLet, a lightweight open source UML diagram editor that has a rather original but very flexible and convenient user interface. It even works as a drop-in plugin for Eclipse.

org.apache.jackrabbit.core.query.lucene TextExtractor class diagramA few weeks ago after upgrading to Eclipse 3.2, I went looking for an UMLet upgrade and was happy to find version 7 available for download. The new version has nice new features like color and transparency support, new diagram types, and various user interface improvements like improved mouse selection support. Warmly recommended.

The attached class diagrams were quickly created using UMLet 7 to describe the structure of a mid-sized patch I sent for consideration as part of the Jackrabbit issue JCR-415.

Saturday, July 8, 2006

JUnit tests for known issues

A few months ago I started working on the Jackrabbit improvement issue JCR-325. Following a good practice, the first thing I did was create a test case for the missing functionality. However, this breaks another good practice of always passing 100% of the test suite. This and a few other know issue tests are currently causing the Jackrabbit test suite to fail even without any real problems, making it more difficult to check whether a recent change or an experimental patch breaks things.

To fix the situation I started wondering if there was a JUnit version of the TODO blocks in Perl's Test::More. The problem is that JUnit can only report tests as successful or failing (or erroneous if they throw an exception), there is no way to easily mark test failures as TODOs. Googling around and asking the Jackrabbit mailing list produced some workarounds:

  • Use a system property to determine whether to perform or skip the known issue test cases.

  • Put the known issues tests in separate test case classes and exclude them from the test suite.

  • Use a JUnit addon to ignore marked test cases as explained in an article that discusses this same issue.

  • Use an alternative test framework like TestNG, that has this functionality built-in.


I didn't want to start changing the entire test suite or even tweaking the build environment, so the last two options were out. I also wanted to make the setup easily configurable so a developer can selectively enable testing for a known issue, thus the first alternative of using a system property looks like the best solution. It seems that the Apache OJB project has reached the same solution.

Monday, July 3, 2006

Analyzing sleep EEG

I'm about to start playing with some sleep EEG data from my girlfriend's research group. She's studying neurobiology, and spends this summer working for the Sleep Research Group at Biomedicum Helsinki. They are looking for a way to automatically detect (score) different sleep stages from the raw EEG data. They currently have some semi-automated tools that use a Fourier transformation and some heuristics to detect the different stages, but the tools are not nearly accurate enough. Thus they need to spend countless dull hours manually scoring the data from their rat experiments.

I promised my girlfriend that I'd take a look at the data and see if I could come up with something useful. It's quite likely that I'll just end up admitting defeat (smarter people have tried before...), but it's still a very interesting problem which also gives me a chance to learn something new. She promised to provide me with some real data and any required background information. Here's a list of things I plan to do with the data:

  • Find or write a simple tool for displaying the time and frequence graphs of a selected window of the EEG data. This will allow me to get familiar with the data and the possible common patterns.

  • Apply tools like genetic algorithms or neural networks (for example self-organizing maps) on the data and let the computer come up with the heuristics for detecting the sleep stages.

  • Validate the effectiveness of these tools against the manual scoring and the existing semi-automated tools.


Let's see how this turns out...