In the last posts (1, 2, 3) I showed various ways for producing fake tests. Of course, good developers won't fake their tests, and the chances to encounter a test suite purely made of fake tests in real life is rather low. Nevertheless, in certain environments it may occasionally happen that metrics are polished for various reasons. But it's more likely, that the quality of a test suites deteriorates over time because of various reasons, i.e. project pressure, sloppy moments during coding, wrong assumptions, etc. And typically we rely on metrics to determine whether our project is in good shape.
My intention for the last three posts was to show, how easy the common metrics - test count, line and condition coverage - can be tricked and are of very low value without the proper context. They are as good for determining the health of a software project as lines of codes are. They might be an weak indicator but nothing more.
The main question is, how could we determine the actual value of our tests and test suites? How would others do it? Firebrigades test their procedures and techniques on a real fire. Military is holding maneuvers, martial arts fighters test their skills in championships, NetFlix is letting the Chaos Monkey terminate instances to detect holes in the recovery procedures.
What is the main reason to have automated tests? To detects bugs that slipped into existing code unintentionally. It doesn't matter if you wrote the tests beforehand by practicing Uncle Bob style TDD or afterwards to create a safepoint for your code. The base assumption is, once you've written your code and your tests, it's free of errors. But it's called Software for a reason: it may change over time. The once written, error-free code will eventually be changed. To ensure, it is still functional, the test suites are run and if it's all green, nothing was broken. But how can you be sure of that?
The only thing to verify your test suite is capable of detecting bugs is to induce bugs in your code.
The technique of altering your code and re-run your test suite to verify the test suite detects the code change is called Mutation Testing. The concept is known for quite a while and was mostly subject to academic research with the tools being somewhat theoretical and less practical to use. But since the arrival of Pitest.org a practical, stable and well integrated tool has been around that should be in every developer's toolbox.
Pitest mutates bytecode and runs highly parallel making it the fastest mutation testing tool for the JVM. Pitest offers a set of Mutation Operators that modify bytecode according to a defined ruleset and thus creates a modified version of the code, a Mutation. The test suite is run again and if at least one test fails, the Mutation is killed. In the end, the Mutation Score is calculated from the number of killed mutations vs the total number of mutations.
Different to line or branch coverage, which can be determined with a single test suite execution, Pitest requires one test suite execution per mutation. With larger code-bases the execution time increases exponentially due to the sheer number of combinations of mutations. Although Pitest offers a variety of settings and options to limit execution time - i.e. delta execution, selection of mutation operators, exclusion of classes, to name a few - it requires some thorough planning how this technique should be incorporated into the CI/CD pipeline. The value it delivers, comes with a price.
In the next post of this series, I will provide examples of how to setup and run pitest with practical examples, so stay tuned.
Wednesday, June 29, 2016
Wednesday, June 22, 2016
How to fake tests (Part 3)
In this 3rd part of the series I want to show how assertions can be faked, so that not only lines and branches get covered but the test themselves also contain some assertions.
Faking Assertions only makes sense if a metric such as "assertions/test" is computed at all. Otherwise you may skip that part, because every proper code review would reveal your test as fake.
Test libraries such as Junit or TestNG contain various means for expressing assertions. In addition to this, some frameworks exist for that sole purpose, i.e. Hamcrest, Truth, to name a few. Basic approach for all is, to invoke the system under test (generating coverage information) and to verify outcomes against assertions.
But the outcomes doesn’t have to be related to what is declared as expected for the test to succeed. So all of the following assertions might do the trick
After having applied fake assertions and fake coverage, our testsuite satisfies the following criteria
Not!
You’ve probably produced the most sophisticated test suite with best quality ratings with minimum effort to create that has no value at all (Achievement unlocked).
In the next post I'll show how all these fakes described in this and the earlier posts can be revealed as such - and more important, how the effectiveness of a test suite can be determined and gaps in a sensible test suite be found. So stay tuned.
Faking Assertions only makes sense if a metric such as "assertions/test" is computed at all. Otherwise you may skip that part, because every proper code review would reveal your test as fake.
Test libraries such as Junit or TestNG contain various means for expressing assertions. In addition to this, some frameworks exist for that sole purpose, i.e. Hamcrest, Truth, to name a few. Basic approach for all is, to invoke the system under test (generating coverage information) and to verify outcomes against assertions.
But the outcomes doesn’t have to be related to what is declared as expected for the test to succeed. So all of the following assertions might do the trick
assertTrue(true);assertNotNull(new Object());(a real life example I’ve encountered during a code review)assertEquals("2","2");- …
After having applied fake assertions and fake coverage, our testsuite satisfies the following criteria
- Big, lots of tests for all the methods
- 100% Line Coverage
- 100% Condition Coverage
- Tests contain assertions (maybe 1 assertion/method as a metric)
Not!
You’ve probably produced the most sophisticated test suite with best quality ratings with minimum effort to create that has no value at all (Achievement unlocked).
In the next post I'll show how all these fakes described in this and the earlier posts can be revealed as such - and more important, how the effectiveness of a test suite can be determined and gaps in a sensible test suite be found. So stay tuned.
Labels:
fake testing,
junit,
mutation testing,
test,
unit test
Thursday, June 9, 2016
How to fake tests (Part 2)
In the last post I described how to write fake tests to statisfy number-of-tests KPI. Apparently this is not a good practice for software craftsmen. Unfortunately some organisation do value KPIs more than good craftsmenship and may be simply tricked by fake tests. So in today's post I'd like to show you how to fake line and condition coverage of tests. This is a call to action for decision makers who base their decisions on such numbers: don't trust them. And for developers: if encouter things like the following (or like in the last post): fix them. So let's start with line coverage.
Obviously this test is broken because in cannot fail – unless the code itself produces an exception. But with tests like these you may achieve quite easily a high line coverage and a stable test suite.
But typical programs are rarely linear and have some sort of loop or branch constructs. So it’s unlikely you achieve 100% line coverage. So we have to fake branch coverage, too.
It has one condition with two branches. With a single test, you may get 66% Line Coverage and 50% Condition Coverage. I’ve experiences several times that branch coverage is perceived as “better” or of “more value” because it’s harder to achieve. If “harder” means “more code” it’s certainly true, but branch coverage suffers the same basic problem as line coverage does: it’s just a measure for which code is executed and not how good your tests are. It also depends on the code base, what is harder to achieve. If the happy-flow you test covers only a minor part of the code, you may have 50% branch-coverage but only 10% line coverage. Given the above example, assume the “left”-branch contains 10 lines of code, but you only test for the “right”-branch.
But as we are developers who want to make happy managers, let’s fake branch coverage!
Given, we only test a single flow in a single test, we need two tests:
This test will produce 100% branch- and line coverage and is very unlikely to fail, ever.
But again: it’s worthless, because we don’t check any output of the operation. So the operation may return anything without failing the test. But still in terms of KPI metrics we achieved:
So in the next post, I'll show you how to fake assertions.
Faking Line Coverage
Line Coverage is a metric that measures how many and which lines have been covered during execution. There are various tools to measure coverage.- Jacoco – Measuring on ByteCode level which has the advantage that you can test your actual artifacts, but bytecode can be different to its source at times.
- ECobertura, Clover – Measuring on SourceCode level which is more precise than byte-code measuring but injects additional code before compilation, ending up in different artifacts than you want to deliver.
@Test
public void test() {
subject.invokeSomeMethod();
}
Obviously this test is broken because in cannot fail – unless the code itself produces an exception. But with tests like these you may achieve quite easily a high line coverage and a stable test suite.
But typical programs are rarely linear and have some sort of loop or branch constructs. So it’s unlikely you achieve 100% line coverage. So we have to fake branch coverage, too.
Faking Condition Coverage
Lets assume our simple program consists of the following code
Object compute(Object input) {
if("left".equals(input) {
return "right";
}
return "left";
}
It has one condition with two branches. With a single test, you may get 66% Line Coverage and 50% Condition Coverage. I’ve experiences several times that branch coverage is perceived as “better” or of “more value” because it’s harder to achieve. If “harder” means “more code” it’s certainly true, but branch coverage suffers the same basic problem as line coverage does: it’s just a measure for which code is executed and not how good your tests are. It also depends on the code base, what is harder to achieve. If the happy-flow you test covers only a minor part of the code, you may have 50% branch-coverage but only 10% line coverage. Given the above example, assume the “left”-branch contains 10 lines of code, but you only test for the “right”-branch.
But as we are developers who want to make happy managers, let’s fake branch coverage!
Given, we only test a single flow in a single test, we need two tests:
@Test
public void testLeft() {
String output = compute("left");
}
@Test
public void testRight() {
String output = compute("right");
}
This test will produce 100% branch- and line coverage and is very unlikely to fail, ever.
But again: it’s worthless, because we don’t check any output of the operation. So the operation may return anything without failing the test. But still in terms of KPI metrics we achieved:
- 2 tests for 1 method (great ratio!)
- 100% line coverage
- 100% condition coverage
So in the next post, I'll show you how to fake assertions.
Labels:
fake testing,
java,
junt,
kpi,
metrics,
mutation testing,
test,
unit test
Tuesday, May 31, 2016
How to fake tests (Part 1)
In most projects, metrics play an important role to determine the status, health, quality etc. of the project. Not rarely the common metrics for quality have been
This post is about to show how to game the system and life-hack those KPIs to fake good quality. It’s NOT a best practice but a heads up to those who make decision based on those metrics to look behind the values.
Let’s look at the Junit which is the de-facto standard for developing and executing Java based unit tests, but other frameworks such as TestNG follow similar concepts.
In Junit 3 it was every parameterless public void method starting with “test” in a class extending TestCase. Since Junit 4 every method annotated with @Test counts as a Test.
That’s it. Just a name convention or an Annotation and you have your test, so let’s fake it!
This is pure gold: a stable and ever succeeding Unit Test!
Copy and paste or even generate those and you produce a test suite satisfying the criteria:
In the upcoming posts we'll have a look into both.
- Number of Unit Tests (Total, Failed, Successful)
- Line Coverage
- Branch Coverage
This post is about to show how to game the system and life-hack those KPIs to fake good quality. It’s NOT a best practice but a heads up to those who make decision based on those metrics to look behind the values.
Faking Number of Unit Tests
Most (if not all?) frameworks count the number of tests executed, which failed and which succeeded. A high number of tests is usually perceived as a good indicator of quality. The increase of the amount of tests should correlate with the increase in lines of code (another false-friend KPI). But what is counted as a test?Let’s look at the Junit which is the de-facto standard for developing and executing Java based unit tests, but other frameworks such as TestNG follow similar concepts.
In Junit 3 it was every parameterless public void method starting with “test” in a class extending TestCase. Since Junit 4 every method annotated with @Test counts as a Test.
That’s it. Just a name convention or an Annotation and you have your test, so let’s fake it!
@Test
public void test() {
}
This is pure gold: a stable and ever succeeding Unit Test!
Copy and paste or even generate those and you produce a test suite satisfying the criteria:
- Big, tons of tests, probable even more than you have LoCs
- Stable, none of these tests is failing. Ever.
- Fast, you have feedback about the success within seconds.
- It doesn’t run any code
- It doesn’t pose any assertion about the outcome
In the upcoming posts we'll have a look into both.
Labels:
fake testing,
java,
junt,
kpi,
metrics,
mutation testing,
test,
unit test
Saturday, December 19, 2015
Scribble 0.3.0
I am proud to announce a new version of the the Scribble testing library! The biggest changes are the new modularization and
documentation. For every functional aspect there is now a separate
module so that not a whole load of unused dependencies have to be
included in your project if you only require just a single functional
aspect. In addition to this, the entire project documentation is now
kept in the source and be generated using maven's site support. This
includes this wiki documentation as well, although the publishing
process is not yet part of the release build jobs.
As new features for testing I introduce a http server as a TestRule that can be set up in various ways to server static content. It's still rather limited, but will be contiuously improved in future releases. Further features are the possibility to create temporary zip files, record system out and err via a TestRule and capture and restore System Properties - a simple rule that helps keeping the test environment clean, and finally a matcher for matching date strings against a data format.
For more information, have a look at the wiki or find the source code on GitHub.
As new features for testing I introduce a http server as a TestRule that can be set up in various ways to server static content. It's still rather limited, but will be contiuously improved in future releases. Further features are the possibility to create temporary zip files, record system out and err via a TestRule and capture and restore System Properties - a simple rule that helps keeping the test environment clean, and finally a matcher for matching date strings against a data format.
For more information, have a look at the wiki or find the source code on GitHub.
Task
- [SCRIB-55] - Modularize Scribble
Story
- [SCRIB-35] - Embedd static HTTP content as a rule
- [SCRIB-43] - Build documentation as part of the release
- [SCRIB-49] - Create zipped temp file from resources
- [SCRIB-50] - Date Format Matcher
- [SCRIB-52] - Rule for capturing System.out and System.err
- [SCRIB-53] - Rule for setting and restoring System Properties
Bug
Wednesday, July 8, 2015
Scribble Release 0.2.0
I am proud to announce a new version of the the Scribble testing library! The new version has support for an embedded ldap server which allows to write tests against an ldap server without having to rely on existing infrastructure. Further, the JCR support has been improved, now it's possible to pre-initialize a JCR repository with content from a descriptor file and to create a security-enabled in-memory repository. Some additional improvements have been made in the CDI injection support and the matchers have been extended for availability checks for URLs.
For more information, have a look at the wiki or find the source code on GitHub.
For more information, have a look at the wiki or find the source code on GitHub.
Release Notes - Scribble - Version 0.2.0
Bug
- [SCRIB-31] - Primitive types not support for ConfigProperty injection
- [SCRIB-32] - String to Number conversion of default values in ConfigProperty injection fails
- [SCRIB-41] - LDAP Rules are not properly applied
- [SCRIB-42] - ResourceAvailabilityMatcher is not compatible with URL
- [SCRIB-48] - Directory Rules can not be used as ClassRules
Story
- [SCRIB-1] - Builder support for LDAP Server and Service
- [SCRIB-2] - Make LDAP Port configurable
- [SCRIB-5] - Matchers for availability of an URL
- [SCRIB-10] - Support for prepared JCR Content
- [SCRIB-12] - Support security enabled content repositories
- [SCRIB-14] - Add Convenience method for admin login
- [SCRIB-33] - Convenience Methods for Directory creation
- [SCRIB-34] - Convenience Method for anonymous login
- [SCRIB-38] - Supply package-info.java
Friday, May 29, 2015
Multi-Module Integration Test Coverage with Jacoco and Sonar
So lets assume, I have the following setup:
rootModule
+Module1
+Module2
| +SubModule2-1
| +SubModule2-1-1
| +SubModule2-2
+ITModule
+ITModule1
The ITModule contains only integration tests, where ITModule1 is a special scenario, that requires a single module. Module2 consists of nested submodules. There are several examples out there to use a path like ../target/jacoco-it.exec but that's obviously not working if you more than one nesting level.
To know how to solve it, you must understand, how sonar is doing the analysis. When analysing the coverage information sonar checks the code of each module against the coverage file that is specified in the
sonar.jacoco.itReportPath property which defaults to target/jacoco-it.exec. So when analyzing Module1 it check for coverage info in Module1/target/jacoco-it.exec.
But as the coverage data is captured in the ITModule, respectively ITModule1, I have to
point sonar to the file generated in the IT
module.So the best location to gather the coverage data is to the use rootModule, i.e. rootModule/target/jacoco-it.exec and append the results of all IT tests to that file.
I use the following plugin configuration that uses separate files for unit-test coverage (don't forget the append flag otherwise overall coverage will be incorrect) and the central file for IT covergage.
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.4.201502262128</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>target/jacoco.exec</destFile>
<append>true</append>
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>prepare-it-agent</id>
<phase>pre-integration-test</phase>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>${session.executionRootDirectory}/target/jacoco-it.exec</destFile>
<append>true</append>
<propertyName>failsafeArgLine</propertyName>
</configuration>
</execution>
</executions>
</plugin>
The ${session.executionRootDirectory} property is the root
of execution, when I build the entire project, it will point to the rootModule. So this is the best path to use, when you have
multi-module with more than one level of nesting.For the analysis, I need to point sonar to use that file when analyzing IT coverage. So I have to set the
sonar.jacoco.itReportPath to that file. Unfortunately, this does not work with the session.executionRootDirectory
property and I have to set the absolute path to the file manually. I
do not recommend to specify the absolute path in the pom.xml as this
path is specific to the build environment. So either set the path in
Sonar or as System property of your build environment. I set it directly
in the Sonar Project Settings (Java > Jacoco), for example /opt/buildroot/myProject/target/jacoco-it.exec.
Now sonar will check that file for the IT coverage analysis of each module.
Labels:
coverage,
integration test,
jacoco,
java,
maven,
multi-module,
sonar,
test
Wednesday, May 27, 2015
Scribble 0.1.3
While working on the next release of Inkstand, I had to fix some bugs in the Scribble test framework's injection support which just got released.
Release Notes - Scribble - Version 0.1.3
Bug
- [SCRIB-26] - Check for null injection target
- [SCRIB-27] - TcpPort has no proper toString() representation
- [SCRIB-30] - Field candidates are not collected for null-values
Story
- [SCRIB-29] - Injection does not fail if no target is found
Tuesday, May 26, 2015
Java XML Processing Vulnerabilities
Last week I was
fixing issues for my pet project Scribble. I use Sonar for capturing
issues in my code. Since April this year, the Findbugs plugin for
Sonar includes rules for finding security bugs. Two of the bugs found
were related to XML processing using Java's XML APIs for Xpath and
DOM parsing. The security issue themselves were not new, both of them
were discovered some years ago. But to me they were new as I was not
aware of them at all. For my pet project they are not that critical
as it is just a framework for writing tests and no one using that
framework is kept from writing vulnerable code themselves. But for me
it was a good case for studying the issues to avoid them when it
really matters.
Xpath Injection
Xpath injection adheres to the same principle as SQL injection were parameter values that are used in an Xpath expression contain characters that are semantically bound to the Xpath syntax to break out from the path defined by the expression.The Attack
Given, you have an XML document containing sensitive data<technical-users> <user id=”reader”> <privateKey>ABC</privateKey> </user> <user id=”writer”> <privateKey>123</privateKey> </user> </technical-users>and an Xpath expression with a parameter that is filled in at runtime:
//technical-users/user[@id='”+userId+”']/privateKeyLets assume, the attacker has authenticated successfully as reader and now tries to query for the private key, manipulating it's own user id to that value:
reader']/../user[@id='writer
The Defense
The only effective defense is to sanitize the user input! Typically, a regex-pattern could help with allowing only input of a certain pattern, i.e. allowing only alphanumeric characters and within a specific length range (5 to 15 characters):if(!userId.matches([a-zA-Z0-9]{5,15}) {
throw new Exception(“Invalid Input“);
}
If reserved characters should be allowed, you may escape them:String escapedUserId = userId.replaceAll(“'“, “\\'“);
public class SanitizingVariableResolver implements XPathVariableResolver {
//create a map to contain the variable values
private Map<QName, String> variables = new HashMap<>();
//keep a list of all valid patterns
private final List<Pattern> validationPatterns;
//constructor accepting regular expression patterns
public SanitizingVariableResolver(String... regexPatterns){
this.validationPatterns = new ArrayList<>();
for(String regexPattern : regexPatterns) {
this.validationPatterns.add(Pattern.compile(regexPattern));
}
}
//method to add variable value on which the sanity check is applied
public void addVariable(String name, String value) {
for(Pattern pattern : validationPatterns){
if(pattern.matcher(value).matches()){
variables.put(new QName(name), value);
return;
}
}
//don't accept invalid values
throw new IllegalArgumentException("The value '" + value + "' is not
allowed for a variable" );
}
@Override
public Object resolveVariable(QName variableName) {
return this.variables.get(variableName);
}
}
Next, you'll have to apply this resolver to your Xpath instance
and use an Xpath expression with a variable placeholder://create new xpath instance
final XPath xp = XPathFactory.newInstance().newXPath();
//instantiate the resolver with an alpahnumeric pattern
final SanitizingVariableResolver resolver =
new SanitizingVariableResolver("[a-zA-Z0-9]{4,15}");
//add the user id value
resolver.addVariable("userId", userId);
//assign the resolver to the xpath instance
xp.setXPathVariableResolver(resolver);
//apply the xpath expression with variable
xp.evaluate("//technical-users/user[@id=$userId]/privateKey",source);
An alternative to sanitizing the input yourself, you may use alternative libraries such as Xquery that provides an abstraction layer on top of the Xpath API that provides means to sanitize parameter input.
References
-
OWASP:
Top 10 2013-A1-Injection
-
CWE-643:
Improper Neutralization of Data within XPath Expressions ('XPath
Injection')
-
CERT:
IDS09-J. Prevent XPath Injection (archive)
-
Black
Hat Europe 2012: Hacking XPath 2.0
-
Balisage:
XQuery Injection
XML External Entity (XXE)
XML document have to be well-formed and may be validated. For validation, there are two options for declaring a structure against which the document is validated: Doctype Definition (DTD) or XML Schema. A DTD may be embedded in the document itself. For XML the concepts of entities exist to describe characters or values that are parsed and replaced by the XML processor. A common example is the &-entity for describing an ampersand character ('&') because the '&' is a reserved character in Xml. Within a DTD custom entities can be declared. Values for those entities could be characters but also the content external resources indicated by an URI.The Attack
In an XXE atttack, the attacker sends a perpared XML file containing a malicious entity. The entity points to an external resource containing a secret, i.e. /etc/passwd. Depending on what the service actually does, the attacker may easily read the secret from the parsed document.A prepared XML document may be
<?xml version="1.0"?>
<!DOCTYPE document [
<!-- placeholder for the attacked file url -->
<!ENTITY xxe SYSTEM "/etc/passwd" >
]>
<document>
<!-- the external entity is replaced with the injected value -->>
<property>&xxe;</property>
</document>
When being processed by DocumentBuilder, the &xxe; is
resolved to the content of /etc/passwd and accessible as text content
of the The Defense
There are several options to fix this vulnerability. Probably the easiest one is to use XML-Schemas only for XML validation and disable the Doctype Declaration feature by setting the DocumentBuilderFactory Feature http://apache.org/xml/features/disallow-doctype-decl to true:DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
This feature however is only supported by Xerces2. If you're on Xerces 1 or you can not disable Doctype declaration, you could disable the features
Xerces 1
http://xerces.apache.org/xerces-j/features.html#external-general-entities
http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
Xerces 2
http://xerces.apache.org/xerces2-j/features.html#external-general-entities
http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
Sax in general
http://xml.org/sax/features/external-general-entities
http://xml.org/sax/features/external-parameter-entities
and set on the DocumentBuilderFactory the flags
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);Oracle proposes two alternative approaches. The first is to perform the parse operation in a privileged context with a no-permission ProtectionDomain where the java security policy is effective, preventing access to restricted system files. The second is to use an EntityResolver and allow only entities that match a certain pattern.
Further attacks against DTD, Schema and Entities and how to defend against are discussed in XML "Schema, DTD, and Entity Attacks"(pdf).
References
-
CWE-611:
Improper Restriction of XML External Entity Reference ('XXE')
-
CERT:
IDS10-J. Prevent XML external entity attacks
-
OWASP.org:
XML External Entity (XXE) Processing
-
WS-Attacks.org:
XML Entity Expansion
-
WS-Attacks.org:
XML External Entity DOS
-
WS-Attacks.org:
XML Entity Reference Attack
-
Xerces2
complete features list
All examples, including JUnit tests that can be used as template to tests your own code can be found on https://github.com/gmuecke/whoopdicity/tree/master/examples
Inkstand Release 0.1.3
Yesterday I released 0.1.3 of the Inkstand microservice framework fixing some bugs and added some minor improvements.
Bug
[INK-31] - Sonar Issue - Security - XML Parsing Vulnerable to XXE (SAXParser) in JCRContentLoader[INK-17] - Apply Apache Licence to code base
[INK-29] - Findings in Code Inspection
[INK-32] - remove log4j2.xml from core
[INK-41] - Wrong Logging Statements in ServiceLauncher
Task
[INK-4] - Document Inkstand in wiki[INK-5] - Set up Test Quality Assessment
[INK-6] - Set up Build for master branch
[INK-34] - Update to Apache Jackrabbit 2.10.1
[INK-35] - Update Apache DS to 2.0.0-M20 and LDAP API to 1.0.0-M30
[INK-36] - Update Undertow to 1.2.6.Final
[INK-37] - Update Apache Deltaspike to 1.4.0
[INK-40] - Update Scribble to 0.1.2
Tuesday, May 19, 2015
Scribble 0.1.2
Today I released version 0.1.2 of the Scribble testing framwork. Beside some bugifxes, the main improvement was the added support for initializing the JCR ContentRepository test rules with nodetype definitions from a CND file.
[SCRIB-19] - InjectableHolders are not recognized properly when injecting
[SCRIB-23] - Sonar Issue: The use of XPath.evaluate() is vulnerable to XPath injection
[SCRIB-24] - Sonar Issue: The usage of /DocumentBuilder.parse(...) is vulnerable to XML External Entity attacks
[SCRIB-25] - Sonar Issue: Use a cryptographically strong random number generator (RNG) like "java.security.SecureRandom" in place of this PRNG
[SCRIB-20] - Initialize Repository with CND node types
[SCRIB-18] - Set up Test Quality Assesment
[SCRIB-21] - Update Apache DS Dependency to 2.0.0-M20
[SCRIB-22] - Fix "Copyright and license headers should be defined" Rule configuration
Bug
[SCRIB-16] - @Inject Annotations is not considered[SCRIB-19] - InjectableHolders are not recognized properly when injecting
[SCRIB-23] - Sonar Issue: The use of XPath.evaluate() is vulnerable to XPath injection
[SCRIB-24] - Sonar Issue: The usage of /DocumentBuilder.parse(...) is vulnerable to XML External Entity attacks
[SCRIB-25] - Sonar Issue: Use a cryptographically strong random number generator (RNG) like "java.security.SecureRandom" in place of this PRNG
Story
[SCRIB-11] - Convenience Methods for InMemory and StandaloneRepository creation[SCRIB-20] - Initialize Repository with CND node types
Task
[SCRIB-17] - Set up Build for master branch[SCRIB-18] - Set up Test Quality Assesment
[SCRIB-21] - Update Apache DS Dependency to 2.0.0-M20
[SCRIB-22] - Fix "Copyright and license headers should be defined" Rule configuration
Tuesday, May 12, 2015
Off to new horizons
April 30th was a weird day. It started like a normal day and ended in me being fired out of blue 20 minutes before I had to leave to pickup my kids from childcare. The reason I was told was that I don't fit into the company's culture, which is kind of weird after 2.5years of hard working making customers happy and having a proven track record of outstanding results.
What happened?
Well, I don't know, but I can only speculate. With the last project I was involved in, the company tried to enter the market of software vendors. The company itself has a long history of being successful in consulting, but had no experience so far in producing software themselves. We adopted Scrum as method and I had the role of Solution Architect or Architecture Owner (you name it) and Scrum Master. We made good progress having to tackle lots of obstacles especially as the stack we used was new to us, same as the persistence layer.
My personal goals as scrum master were to pave the way for bringing the product to it's first go-live, second aiming for high quality as a small company cannot afford producing crappy software and third, increase transparency of the project's progress as a lot of the stakeholders were working at customers and were not located in the office. I also stood up for protecting the team from unnecessary overtime as the effect on declining quality is well known. And I tried to mitigate unrealistic expectations from wishful thinking to what's realizable, always embracing challenges. I really took my job seriously and diligently. But I assume it was too much for a company that not fully embraced the agile idea. I guess in the end it was a personal conflict that grew on one end, totally hidden from me, and no one ever made attempts to solve it in a professional way. Stories about scrum master's being fired for taking their job seriously are not unknown, and now it was my turn. Bad luck I'd say.
My advice for other scrum masters, if your stakeholder are not available physically most of the time find ways for effective communication rather sooner than later. And if your stakeholders are detached, try to re-connect them with the project and what's actually going on. Though that might just reduce but not remove the risk.
Anyway, so now it's official, I'm looking for a new Job!
So if you have or hear of an open position as Scrum Master, Software Engineer or Architect, drop me a message.
And while I'm on job search, I'll spent some time on my new pet project, a microservice framework named Inkstand! If you're interested, I'll invite you come around, have look, drop a comment or join!
What happened?
Well, I don't know, but I can only speculate. With the last project I was involved in, the company tried to enter the market of software vendors. The company itself has a long history of being successful in consulting, but had no experience so far in producing software themselves. We adopted Scrum as method and I had the role of Solution Architect or Architecture Owner (you name it) and Scrum Master. We made good progress having to tackle lots of obstacles especially as the stack we used was new to us, same as the persistence layer.
My personal goals as scrum master were to pave the way for bringing the product to it's first go-live, second aiming for high quality as a small company cannot afford producing crappy software and third, increase transparency of the project's progress as a lot of the stakeholders were working at customers and were not located in the office. I also stood up for protecting the team from unnecessary overtime as the effect on declining quality is well known. And I tried to mitigate unrealistic expectations from wishful thinking to what's realizable, always embracing challenges. I really took my job seriously and diligently. But I assume it was too much for a company that not fully embraced the agile idea. I guess in the end it was a personal conflict that grew on one end, totally hidden from me, and no one ever made attempts to solve it in a professional way. Stories about scrum master's being fired for taking their job seriously are not unknown, and now it was my turn. Bad luck I'd say.
My advice for other scrum masters, if your stakeholder are not available physically most of the time find ways for effective communication rather sooner than later. And if your stakeholders are detached, try to re-connect them with the project and what's actually going on. Though that might just reduce but not remove the risk.
Anyway, so now it's official, I'm looking for a new Job!
So if you have or hear of an open position as Scrum Master, Software Engineer or Architect, drop me a message.
And while I'm on job search, I'll spent some time on my new pet project, a microservice framework named Inkstand! If you're interested, I'll invite you come around, have look, drop a comment or join!
Tuesday, February 3, 2015
Mutation Testing
End of January I attended the OOP2015 conference in Munich. Among the load of interesting sessions was one that left a mark. It was the workshop conducted by Filip van Laenen and Markus Schirp about Mutation Testing (slides here), which I'd like to summarize in this post.
Further, some survived mutants may have to be accepted. Survived mutants may easily occur and may not necessarily be an indicator that your coverage is insufficient. For a simple example, think about logging code or the equality in some comparison cases, like ( a > b ? a : b) which in Java is equal to (a >=b ? a : b).
For using it with SonarQube, a plugin is available, but its current version 0.5 is only compatible with SonarQube prior to version 4.2. There is a fork on github, making it compatible with Sonar API version 4.3 and I am working on a version for SonarQube 5.0 with some more rules. Both have to be compiled and deployed manually to Sonar.
What is Mutation Testing?
Mutation testing is a method to ensure the quality of your Test. With mutations testing you verify if your tests not only invokes your product code pretending to cover lines and branches but that the tests actually reflects the semantics of your code. While your tests guard your product code from bugs, mutation testing guards your tests suite from critical gaps.How does it work?
Mutation testing is available for a set of languages. The implementation for Java is the PIT. PIT modifies the compiled byte code by applying a set of predefined rules, so call Mutators. Each change to the byte code is called a Mutant. Against the altered byte code your unit tests are executed, resulting in three outcomes:- The tests fails. This proves, that your tests detects the changes to the byte code correctly and reports an error. This outcome is called a Killed Mutant.
- The test does not fail, but the line of code is covered by the test execution. This proves, that your test does not cover the full semantics of the product. This outcome is called a Survived Mutant (I call them Survivors).
- The product code is not covered by a test at all but contains a mutant. This is outcome is an Uncovered Mutant (I call them Lurker), which can also be indicated by a Code Coverage tool such as Cobertura or jacoco.
What's the use of it?
Every mutant not killed by a test is a blind spot of your test suite and may become an actual bug in the long run. With mutation testing you can determine, whether your Unit Test - the detail specification - covers all the semantics of your product code. For every uncovered mutant you may either decide if your specification (test) is incomplete or your product code contains unneeded semantics which should be removed. That way mutation testing leads to smaller and simpler code and further is an indicator, when you are done with testing.Its no silver bullet
Mutation testing is no silver bullet as it does not replace the need for properly designed tests in the first place. Testing for all combinations of Mutations may become a quite resource consuming operation, requiring to reduce the scope of mutation testing in larger projects on the crucial parts.Further, some survived mutants may have to be accepted. Survived mutants may easily occur and may not necessarily be an indicator that your coverage is insufficient. For a simple example, think about logging code or the equality in some comparison cases, like ( a > b ? a : b) which in Java is equal to (a >=b ? a : b).
How to use it?
To use it on a maven project, an official maven plugin is avaible (see link for a good documentation how to use it). There are options for command line or Ant as well. This will create a report in html or xml. You may narrow the scope of the mutation testing using include and exclude parameter. The report itself run on a regular basis is already a good source of information for conduction code reviews.For using it with SonarQube, a plugin is available, but its current version 0.5 is only compatible with SonarQube prior to version 4.2. There is a fork on github, making it compatible with Sonar API version 4.3 and I am working on a version for SonarQube 5.0 with some more rules. Both have to be compiled and deployed manually to Sonar.
TL;DR
Mutation Testing alters your product code in a deterministic way and verifies if your test suite finds the induced bug. This leads to smaller and simpler source code and you can tell when your're done with testing.Tuesday, September 23, 2014
Rasterizing scalable images during build
In most web projects your content does not only include code, html or css but also images. Those images are typically delivered as non-scalable graphics to the clients (i.e. jpg, png, gif). But ususally those images are created from a scalable image that allows to "design" the actual image and produce versions of various sizes from the scalable image. The process of transforming a scalable graphic to a non-scalable graphic is called rasterization and fortunately the process can be automated when you're running your build with Maven.
The Batik Maven plugin allows you to convert your svg (Scalable Vector Graphics) images to non-scalable images, supported types are
png,
jpeg, tiff or pdf. The plugin can be added to your build lifecycle. The plugin documentation states that adding the following snippet to your pom.xml<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>batik-maven-plugin</artifactId>
<version>1.0-beta-1</version>
<executions>
<execution>
<goals>
<goal>rasterize</goal>
</goals>
</execution>
</executions>
</plugin>
Unfortunately that's not sufficient as not all dependencies seem to be satisfied. But the following snippet worked for me (see also https://jira.codehaus.org/browse/MOJO-1670 )<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>batik-maven-plugin</artifactId>
<version>1.0-beta-1</version>
<executions>
<execution>
<goals>
<goal>rasterize</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-rasterizer</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.axsl.org.w3c.dom.svg</groupId>
<artifactId>svg-dom-java</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.w3c.css</groupId>
<artifactId>sac</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
With that snippet I could place my svg files into
/src/main/svg and during the build those files are rasterized to png files in the /target/generated-resources/images (locations and type are default settings and can be configured). From now on it's quite easy to "compile" your images during the build and you never have to paint your images by pixel anymore.If you're looking for a free and powerful SVG "editor", try Inkscape.
Tuesday, August 26, 2014
User Acceptance Testing with Selenium and Cucumber
In the last implementation project I participated in we applied the Behavior Driven Development approach where the user stories are defined in Given-When-Then style. In this article I want to describe how I combined Cucumber with Selenium in order to automate our User-Acceptance Tests using Behavior Driven Development.
For running automated BDD tests there are some free frameworks available (a brief comparison of BDD frameworks). We decided to go for Cucumber because it served all our requirements, has a good documentation with good examples and is pretty easy to get it up and running
With that feature in the right location you can run the above test with JUnit. Of course it will not be successful. Actually, with the default settings it will ignore all the steps unless you use the @CucumberOption(strict=true) which is recommended when you run the test as part of a quality gate.
The Cucumber documentation provides some good descriptions on Features and their syntax. You can define Backgrounds that are executed for each scenario of the feature (similar to JUnit 4 @BeforeClass) or Scenario Outlines to run the feature against a set of data. It is even possible to write your BDDs in different languages. Therefore you have to start the feature with the line following line and have all the keywords in the according language.
But you have to be careful with the encoding of the Feature files and special characters. It's best to use UTF-8 as default encoding. A complete list of the keywords in other languages can be found in the Cucumber apidoc.
The test prints out skeletons for unimplemented steps. What you do now is to create a new step which is a simple Java class and put in one of the packages defined in the glue. Copy the skeletons into the class and implement it.
So the steps are basically what is executed for each line. It is possible to pass parameters to the steps that are extracted and converted so that steps can be reused with different values. Its also possible to define entire tables as input.
and the according hook in Java will be
For automated user-acceptance tests with Selenium and Cucumber the basic approach would be to
In order to reuse steps for different browsers, I used the BrowserHook shown in on of the example on above and set-up the browser using a specific tag for each browser. The driver is first initialized upon the first call to getDriver(). In the step itself I retrieve the driver from the BrowserHook that got injected. The BrowserHook may be implemented like this
So let's assume you define a login user story such as
And how it is used in a story
For running automated BDD tests there are some free frameworks available (a brief comparison of BDD frameworks). We decided to go for Cucumber because it served all our requirements, has a good documentation with good examples and is pretty easy to get it up and running
Cucumber JUnit Test
The following listing shows a simple example that is practically the archetype for all our Cucumber tests.@RunWith(Cucumber.class)
@CucumberOptions(
features = { "classpath:features/example/" },
glue = { "my.project.uat." },
tags = { "@Example" })
public class ExampleCucumberTest {
//empty
}
The annotations of the example in detail are:- @RunWith declares the TestRunner for this test, which is the Cucumber class. The test won't run without it.
- @CucumberOptions define various options for this tests. The options are optional but are quite helpful in controlling the behavior of the test
- features: declares a path were the BDD feature files (text files) are found. The example points to a location in the classpath. All feature files (.feature extension) below that location are considered. Multiple locations can be defined as an array.
- glue: defines the packages where Steps and Hooks are located. Steps and Hooks contain the actual code for the tests. Multiple packages can be defined as an array.
- tags: defines which stories should be executed. If you omit this option, all Stories are executed, otherwise only those that have one of the tags set will be run.
BDD Feature
The following exaple story is taken from the Cucumber documentation@Example
Feature: Search courses
Courses should be searchable by topic
Search results should provide the course code
Scenario: Search by topic
Given there are 240 courses which do not have the topic "biology"
And there are 2 courses, A001 and B205, that each have "biology" as one of the topics
When I search for "biology"
Then I should see the following courses:
| Course code |
| A001 |
| B205 |
With that feature in the right location you can run the above test with JUnit. Of course it will not be successful. Actually, with the default settings it will ignore all the steps unless you use the @CucumberOption(strict=true) which is recommended when you run the test as part of a quality gate.
The Cucumber documentation provides some good descriptions on Features and their syntax. You can define Backgrounds that are executed for each scenario of the feature (similar to JUnit 4 @BeforeClass) or Scenario Outlines to run the feature against a set of data. It is even possible to write your BDDs in different languages. Therefore you have to start the feature with the line following line and have all the keywords in the according language.
#language: de Funktionalität: ...
But you have to be careful with the encoding of the Feature files and special characters. It's best to use UTF-8 as default encoding. A complete list of the keywords in other languages can be found in the Cucumber apidoc.
Cucumber Steps
When the test for the feature is run and the steps or part of it are not yet implemented, it will produce an output like this:You can implement missing steps with the snippets below:
@Given("^there are (\\d+) courses which do not have the topic \"([^\"]*)\"$")
public void there_are_courses_which_do_not_have_the_topic(int arg1, String arg2) throws Throwable {
// Express the Regexp above with the code you wish you had
throw new PendingException();
}
@Given("^there are (\\d+) courses, A(\\d+) and B(\\d+), that each have \"([^\"]*)\" as one of the topics$")
public void there_are_courses_A_and_B_that_each_have_as_one_of_the_topics(int arg1, int arg2, int arg3, String arg4) throws Throwable {
// Express the Regexp above with the code you wish you had
throw new PendingException();
}
...
The test prints out skeletons for unimplemented steps. What you do now is to create a new step which is a simple Java class and put in one of the packages defined in the glue. Copy the skeletons into the class and implement it.
So the steps are basically what is executed for each line. It is possible to pass parameters to the steps that are extracted and converted so that steps can be reused with different values. Its also possible to define entire tables as input.
Hooks
Hooks are basically the same as steps but fulfill a similar role like the JUnit @Before and @After annotated methods, the even use the similar annotations (actually, the are named the same but are in a different package). You can trigger certain hooks using tags like shown in the following example:@WithFirefox Scenario: Response times with 10 users ...
and the according hook in Java will be
@Before("@WithFirefox")
public class BrowserHook {
...
public void setupScenario_Firefox() {
...
}
...
Dependencies between Hooks and Steps
In order to reuse existing code or to access the state of a particular Hook or Step instance you can create a dependency between the classes by defining a constructor that accepts a particular Hook or Step. The Cucumber JUnit runner will create instances of the according classes and inject them in classes that are dependent.public class MyBrowserSteps {
private BrowserHook browserHook;
public MyBrowserSteps(final BrowserHooks browserHook) {
this.browserHook = browserHook;
}
The same applies to Steps so you can make one set of steps dependent on other steps.Selenium Steps
So far I only described how to write any test with Cucumber, but for User Acceptance Testing you might want to test the actual solution. For web application that is the deployed application that is accessed by a browser. For browser automation the Selenium framework is widely known and framework of choice for most cases. It provides a recording tool (a plugin to Firefox) to record user interactions with the browser. It provides a model to access elements of the website using Java and various methods of locating elements in the browser.For automated user-acceptance tests with Selenium and Cucumber the basic approach would be to
- Record actions with the Selenium Recorder
- Copy them to Steps classes that match your BDD
- Define assertions in Then step implementations
@When("^I push the button$")
public void i_push_the_button() throws Throwable {
driver.findElement(By.cssSelector("div.v-select-button")).click();
}
In order to reuse steps for different browsers, I used the BrowserHook shown in on of the example on above and set-up the browser using a specific tag for each browser. The driver is first initialized upon the first call to getDriver(). In the step itself I retrieve the driver from the BrowserHook that got injected. The BrowserHook may be implemented like this
public final class BrowserHooks {
private enum DriverType {
headless,
firefox,
ie,
chrome, ;
}
private WebDriver driver;
public WebDriver getDriver() {
if (driver == null) {
switch (driverType) {
case ie:
driver = new InternetExplorerDriver();
break;
case firefox:
driver = new FirefoxDriver();
break;
...
}
return driver;
}
@Before("@WithFirefox")
public void setupScenario_Firefox() {
driverType = DriverType.firefox;
}
@Before("@WithIE")
public void setupScenario_InternetExplorer() {
driverType = DriverType.ie;
}
...
}
And the step definition that uses it may look like public class MyBrowserSteps {
private BrowserHook browserHook;
public MyBrowserSteps(final BrowserHooks browserHook) {
this.browserHook = browserHook;
}
@When("^I push the button$")
public void i_push_the_button() throws Throwable {
this.browserHook.getDriver().findElement(By.cssSelector("div.v-select-button")).click();
}
...
Aggregate Steps
One of the big advantages of a BDD framework like Cucumber is, that you can define steps that aggregate multiple steps. A good example for this is the Login Story. Although this is a point of typical discussions whether "Login User" is a valid Use Case or User Story (with regards to its business value) the requirement to allow a user to login does exists and its parameters need to be defined (whether it is via Single Sign On, Smartcard, Username/Password, Two-Factor or whatever else).So let's assume you define a login user story such as
Given the login screen is being displayed When I enter my username "xxx" and my password "yyy" And I push the login button Then I see the main screen of the application And I see my name being displayed in the user info boxNow you don't want to describe all these steps over and over again because the rest of the application under test requires a logged in user. So you could begin the other stories with
- When the user "xxx" is logged in
- @Authenticated
public class LoginSteps {
private BrowserHook browserHook;
public LoginSteps (final BrowserHooks browserHook) {
this.browserHook = browserHook;
}
@Given("^the login screen is being displayed$")
public the_login_screen_is_being_displayed() {
this.browserHook.getDriver().get(baseURL);
}
@When("^I enter my username \"([^\"]*)\" and my password \"([^\"]*)\"$")
public void I_enter_my_username_and_my_password(String arg1, String arg2) throws Throwable {
//with Selenium, put in the values in the login form
}
@When("^I push the login button$")
public void I_push_the_login_button() throws Throwable {
// with Selenium, locate the submit/login button and click it
}
...
}
public class LoginHook {
private LoginSteps loginSteps;
private String testUser;
private String testPassword;
public LoginHook (final LoginSteps loginSteps) {
this.loginSteps= loginSteps;
}
@Before(value="@PersonaXY", order=1)
public void selectPersonaXY() {
this.testUser = ...;
this.testPassword = ...;
}
@Before(value="@Authenticated", order=2)
public void login() {
this.loginSteps.the_login_screen_is_being_displayed();
this.loginSteps.I_enter_my_username_and_my_password(testUser, testUserPassword);
this.loginSteps.I_push_the_login_button();
...
}
}
And how it is used in a story
@Authenticated @PersonaXY Given I see the meaningful screen When I do something purposeful Then I get a sensible result
Conclusion
In this article I gave a brief introduction into Cucumber and how to write testcases with it. I showed how to define steps with Selenium to create meaningful, browser-based user acceptance testing and I showed how to combine thereby reuse steps and hook to create a rich user acceptance testing suite.
Labels:
acceptance testing,
bdd,
behavior driven,
cucumber,
development,
howto,
java,
junit,
selenium,
test,
uat
Friday, August 22, 2014
Developing a dynamic JEE service client with CDI (part 2)
In the previous blog entry I described how to develop an JEE service client that performs lazy lookups and is injectable to satisfy a service dependency. In this article I want to describe how to extend this service client to allow client-side service call interception.
Before I dive into the details of the interception, I want to outline the reasons why client-side call interception might be useful.
With JEE we could easily add caching behavior on the service side of a service consumer-provider relationship by adding an interceptor that serves a call with data from a cache and therefore reducing processing resource usage on the service side.
On the consumer side there is no such mechanism as to transparently intercept a service call before it is actually sent to the service. Such a client-side call interception could be of use for a range of use-cases
When a JEE interceptors is invoked an InvocationContext is passed to the interceptor. The interceptor may decide to fully intercept the request and not proceeding the invocation further. This is behavior is needed for caching or security concern. Alternatively, interceptors may execute some additional operations before or after proceeding with the invocation which is useful for logging or error handling.
The InvocationContext is an interface introduced by JEE6. I used my own implementation of this interface where the getter methods defined by the interface simply return the values that are passed to the InvocationHandler of the dynamic proxy (see the ProxyServiceInvocationHandler of the previous blog post), the getTimer() method returns null, as I don't really need it. The main functionality of the InvocationContext however resides in the proceed() method. I used a stack (Deque) to maintain a list of registered interceptors of which each is checked whether it may intercept the method invocation or not.
The check is done in the method isInterceptedBy and does check the class of the interceptor instance as well as the method whether they both are annotated with the same the InterceptorBinding annotation. I deviated a bit from the JEE6 standard as I allowed an interceptor without an explicit interceptor binding to intercept any method invocation, but that is up to you.
The main method of my InvocationContext implementation are shown in the next listing
With the implementation of the InvocationContext described above, we need a collection of interceptor instances. In our project I used a configuration file (similar to the beans.xml where you have to define which interceptors should be loaded) where I defined the interceptor classes that should be loaded.
Creating an instance of a class by the fully qualified name of the class is trivial using reflection (i.e. Class.forName("...").newInstance()). But when you have a CDI container you want to let the container do the creation and further process the lifecycle of the the instance including dependency injection.
JEE6 itself does not provide the means for that but it defines an SPI. The Apache DeltaSpike project offers an implementation for that SPI (btw. it is developed by the same guys behind CDI in JEE6 itself). DeltaSpike allows to interact directly with the CDI container.
The following code snippet assumes, that you have already loaded the interceptor class and verified it is annotated with the @Interceptor annotation. It first checks, if a CDI environment is active, if not, the interceptor is instantiated the traditional way. If it is active, a BeanManager reference is obtained, an injection target is created using the interceptor class. This is needed to create the instance and inject dependencies to the instance. With the injection target, an interceptor Bean is created using the BeanBuilder of DeltaSpike. The Bean is a Contextual instance that is required by the manager to create a creational context. Having this context we can create a managed instance using the create method. DeltaSpikes contribution to the snippet is the BeanManagerProvider , the BeanBuilder and the DelegatingContextualLifecycle.
Before I dive into the details of the interception, I want to outline the reasons why client-side call interception might be useful.
Background
In our current project we aspired a RESTful component-based architecture. For each of the components it should be possible to integrate them in a service oriented architecture via WebService, deploy them in a JEE environment accessing it as JNDI-locateable services or access them via a RESTful lightweight interface. Each component should be deployable standalone and should be operational as long as their lower-level component dependencies are satisfied. To be RESTful, our architecture followed the seven principles of REST, described in the famous thesis of Roy Fielding.With JEE we could easily add caching behavior on the service side of a service consumer-provider relationship by adding an interceptor that serves a call with data from a cache and therefore reducing processing resource usage on the service side.
On the consumer side there is no such mechanism as to transparently intercept a service call before it is actually sent to the service. Such a client-side call interception could be of use for a range of use-cases
- caching, to reduce network resource usage
- error handling and fault tolerance
- logging
- security
Adding Interceptor support
In order to add call interceptors to the service client, we have to extend the invocation handler that delegates the service method invocation to the actual service by adding a stack of interceptors that are invoked consecutively.When a JEE interceptors is invoked an InvocationContext is passed to the interceptor. The interceptor may decide to fully intercept the request and not proceeding the invocation further. This is behavior is needed for caching or security concern. Alternatively, interceptors may execute some additional operations before or after proceeding with the invocation which is useful for logging or error handling.
The InvocationContext is an interface introduced by JEE6. I used my own implementation of this interface where the getter methods defined by the interface simply return the values that are passed to the InvocationHandler of the dynamic proxy (see the ProxyServiceInvocationHandler of the previous blog post), the getTimer() method returns null, as I don't really need it. The main functionality of the InvocationContext however resides in the proceed() method. I used a stack (Deque) to maintain a list of registered interceptors of which each is checked whether it may intercept the method invocation or not.
The check is done in the method isInterceptedBy and does check the class of the interceptor instance as well as the method whether they both are annotated with the same the InterceptorBinding annotation. I deviated a bit from the JEE6 standard as I allowed an interceptor without an explicit interceptor binding to intercept any method invocation, but that is up to you.
The main method of my InvocationContext implementation are shown in the next listing
class ProxyInvocationContext implements InvocationContext {
...
@Override
public Object proceed()
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
if (!interceptorInvocationStack.isEmpty()) {
final Object interceptor = interceptorInvocationStack.removeFirst();
if (isInterceptedBy(interceptor)) {
final Method aroundInvoke = interceptorMethods.get(interceptor);
return aroundInvoke.invoke(interceptor, this);
}
}
return this.method.invoke(target, this.parameters);
}
private boolean isInterceptedBy(final Object interceptor) {
boolean hasNoBinding = true;
for (final Annotation an : interceptor.getClass().getAnnotations()) {
if (an.annotationType().getAnnotation(InterceptorBinding.class) != null) {
hasNoBinding = false;
if (getMethod().getAnnotation(an.annotationType()) != null) {
return true;
}
}
}
return hasNoBinding;
}
}
Instantiating Interceptors in CDI Context using DeltaSpike
Now we want to create interceptors and put them into the interceptor stack. The JEE 6 standard already defines interceptors so we could simply re-use this specification. JEE6 compliant interceptors may be used in a CDI lifecycle, that means lifecycle methods annotated with @PostConstruct or @PreDestroy are executed as well as injection of dependencies.With the implementation of the InvocationContext described above, we need a collection of interceptor instances. In our project I used a configuration file (similar to the beans.xml where you have to define which interceptors should be loaded) where I defined the interceptor classes that should be loaded.
Creating an instance of a class by the fully qualified name of the class is trivial using reflection (i.e. Class.forName("...").newInstance()). But when you have a CDI container you want to let the container do the creation and further process the lifecycle of the the instance including dependency injection.
JEE6 itself does not provide the means for that but it defines an SPI. The Apache DeltaSpike project offers an implementation for that SPI (btw. it is developed by the same guys behind CDI in JEE6 itself). DeltaSpike allows to interact directly with the CDI container.
The following code snippet assumes, that you have already loaded the interceptor class and verified it is annotated with the @Interceptor annotation. It first checks, if a CDI environment is active, if not, the interceptor is instantiated the traditional way. If it is active, a BeanManager reference is obtained, an injection target is created using the interceptor class. This is needed to create the instance and inject dependencies to the instance. With the injection target, an interceptor Bean is created using the BeanBuilder of DeltaSpike. The Bean is a Contextual instance that is required by the manager to create a creational context. Having this context we can create a managed instance using the create method. DeltaSpikes contribution to the snippet is the BeanManagerProvider , the BeanBuilder and the DelegatingContextualLifecycle.
private <I> I createInterceptor(final Class<I> interceptorClass)
throws InstantiationException, IllegalAccessException {
final I interceptor;
if (BeanManagerProvider.isActive()) {
final BeanManager manager = BeanManagerProvider.getInstance().getBeanManager();
final InjectionTarget<I> target = manager.createInjectionTarget(
manager.createAnnotatedType(interceptorClass));
final Bean<I> interceptorBean =
new BeanBuilder<I>(manager)
.beanClass(interceptorClass)
.beanLifecycle(new DelegatingContextualLifecycle<I>(target))
.create();
interceptor = interceptorBean.create(
manager.createCreationalContext(interceptorBean));
} else {
interceptor = interceptorClass.newInstance();
}
return interceptor;
}
Conclusion
In this article I described how the Dynamic Service Client can be extended in order to provide client-side service call interception and how Interceptors (or Beans in general) can be instantiated in a CDI context using Apache DeltaSpike.
Labels:
cdi,
code,
deltaspike,
dependency injection,
howto,
java,
jee,
programming,
service,
service locator
Wednesday, July 23, 2014
Developing a dynamic JEE service client with CDI (part 1)
With JEE6 CDI was introduced in and standardized for the Java Enterprise world. The main scope for the CDI extension was for enterprise services as it simplified various mechanisms in the JEE world such as EJB lookup or invocation interception. Unfortunately the new features fall a bit short on the consumer side of services implemented with CDI, in particular the lookup or service locator pattern, and client side invocation interception.
In this first article I want to describe a dynamic service client that performs lazy service dependency resolution (lookup) and that can be injected into a CDI injection point.
It is a good base for being extended to use sophisticated configuration or error handling mechanisms.
The key to this problem is a lazy lookup, that is done first time the dependency is actually needed. But that is not supported by the @EJB annotation.
In our current project we solved the problem by implementing a dynamic service proxy that implements the interface of the service and performs the lookup using a JNDI lookup or another strategy on the first actual service call.
The creation of the instance itself is done by the static factory method shown in the first listing. The producer extends the DynamicServiceClient I described earlier and uses its static factory method. In order to keep the producer class simple, we need to extend some methods to the DynamicServiceClient.
The extended DynamicServiceClient that is shown in the following listing contains the logic for the actual service proxy instantiation and an abstract method returning the interface class of the service to be instantiated that has to be implemented by the producer.
To qualify an injection point and the producer method to create and inject instances of the service client that implement the service interface and not instances of the actual service, I used a qualifier as shown in the next listing.
Now we're ready to define a producer using the DynamicServiceClient as base class. The producer is relatively simple as it only contains two simple methods.
Instead of
In this first article I want to describe a dynamic service client that performs lazy service dependency resolution (lookup) and that can be injected into a CDI injection point.
It is a good base for being extended to use sophisticated configuration or error handling mechanisms.
Defining a Dynamic Service Locator
In JEE6 its quite easy to perform a JNDI lookup for an EJB using the @EJB annotation. Unfortunately this is done during construction of the service consumers. When you have a multi-module project where each module should be deployable independently from the others, deployment will fail if the dependencies defined by the @EJB annotation could not be satisfied, that is, the EJB lookup fails.The key to this problem is a lazy lookup, that is done first time the dependency is actually needed. But that is not supported by the @EJB annotation.
In our current project we solved the problem by implementing a dynamic service proxy that implements the interface of the service and performs the lookup using a JNDI lookup or another strategy on the first actual service call.
Creating a Proxy
Creating a dynamic proxy is relatively simple, you need a custom implementation of an InvocationHandler that performs the actual method invocation and need to specify the interfaces the dynamic proxy should implement. A factory method is used to create such a proxy instance. The the following code example shows such a factory method:public abstract class DynamicServiceClient {
public static <T> T newInstance(final Class T serviceInterface) {
return (T) java.lang.reflect.Proxy.newProxyInstance(
getClassLoader(),
new Class[] { serviceInterface },
new ProxyServiceInvocationHandler T(config));
}
private static ClassLoader getClassLoader(){
...
}
}
Invocation Handler
The invocation handler delegates all service call to an instance of the actual service. The service is kept as an instance field of the invocation handler that is initialized upon the first service call using a Service Locator. The invoke method of the Invocation Handler delegates the call to the service instance.class ProxyServiceInvocationHandler<T>
implements InvocationHandler {
/**
* The service reference that is lazily initialized
*/
private T service;
/**
* The service locator that performs the actual lookup
*/
private final ServiceLocator<T> locator;
...
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//do the lookup if not already done
if (this.service == null) {
this.service = this.locator.locate();
}
//do the actual service call and return the result
return method.invoke(this.service, args);
}
}
Service Locator
The service locator that is used in the the above listing performs the actual lookup. In our project I used an implementation that allowed to define a location strategy in a configuration, with the JNDI lookup being implemented in one of the strategies. The following example however shows a simple implementation that performs a straightforward JNDI lookup using a lookupName.public class ServiceLocator<T>{
/**
* the name for the JNDI lookup
*/
private String lookupName;
...
public T locate() {
final Context context = new InitialContext();
T service = (T)context.lookup(this.lookupName);
return service;
}
}
Service Injection
In order to use the dynamic service shown above and inject it via CDI, I used a producer method that creates instances of the dynamic service and a qualifier to distinguish the dynamic service client from the actual service implementation that might be available in the CDI container as well.The creation of the instance itself is done by the static factory method shown in the first listing. The producer extends the DynamicServiceClient I described earlier and uses its static factory method. In order to keep the producer class simple, we need to extend some methods to the DynamicServiceClient.
The extended DynamicServiceClient that is shown in the following listing contains the logic for the actual service proxy instantiation and an abstract method returning the interface class of the service to be instantiated that has to be implemented by the producer.
public abstract class DynamicServiceClient<T>{
/**
* Instance of the service client
*/
private T serviceInstance;
/**
* The method has to return the interface of the service
*/
protected abstract Class<T> getServiceInterface();
/**
* Creates a new instance of the service client.
*/
protected T getInstance() {
if (serviceInstance == null) {
serviceInstance = newInstance(getServiceInterface());
}
return serviceInstance;
}
/**
* The factory method to create a new service instance
*/
public static <T> T newInstance(final Class serviceInterface) {
return (T) Proxy.newProxyInstance(
getClassLoader(),
new Class[] { serviceInterface },
new ProxyServiceInvocationHandler());
}
}
private static ClassLoader getClassLoader(){
...
}
}
To qualify an injection point and the producer method to create and inject instances of the service client that implement the service interface and not instances of the actual service, I used a qualifier as shown in the next listing.
@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface ServiceClient {}
Now we're ready to define a producer using the DynamicServiceClient as base class. The producer is relatively simple as it only contains two simple methods.
public class MyServiceClientProducer
extends DynamicServiceClient<MyBusinessService> {
@Produces @ServiceClient
public MyBusinessService getInstance() {
return super.getInstance();
}
protected Class<MyBusinessService> getServiceInterface() {
return MyBusinessService.class;
}
}
To inject the dynamic service client into an injection point we simply have to define the Service interface class and use the qualifier. That's it.public class MyServiceConsumer {
@Inject @ServiceClient
private MyBusinessService service;
...
}
Instead of
public class MyServiceConsumer {
@EJB(lookup="...")
private MyBusinessService service;
...
}
Conclusion
In this article I described how to implement a dynamic service locator that can be used in a CDI container. The service locator performs a lookup upon the first call of a service method and therefore provides a mechanism for fault tolerant dependency resolving and further a foundation for implementing client-side service call interception - which I will a describe in a future post.
Labels:
cdi,
code,
dependency injection,
howto,
java,
jee,
lookup,
programming,
service,
service locator
Tuesday, April 29, 2014
JUnit Testing with Jackrabbit
Writing unit tests for your code is not only best practices, it's essential for writing quality code. In order to write good unit tests, you should use mocking of code not under test. But what if you're using a technology or an API that would require quite a lot of complicated mocks?
In this article I'd like to describe how you write unit tests for code that accesses a JCR repository.
At first I really tried to mock the JCR API using Mockito, but stopped my attempt at the point where I had to mock the behavior of the Query Object Model. It became apparent, that writing mocks would outweigh the effort to write the actual production code by far. So I had to search for an alternative and found one.
The reference implementation of JCR is the Apache Jackrabbit project. This implementation comes with a set of JCR Repository implementations, one of these is the TransientRepository. The TransientRepository starts the repository on first login and shuts it down on the last session being closed. The repository is created in memory which works pretty fast and makes it the best solution for unit testing. But nevertheless, a directory structure is created for the repository and unless not specified a config file is created as well.
For writing unit tests against this repository, we need the following:
Now let's create the directory for the repository. I recommend to locate it in a temporary folder so multiple test runs don't affect each other if cleanup failed. We use the Java TempDirectory facility for that:
Next, you require a configuration file. If you already have a configuration file available in the classpath, i.e. in src/test/resource, you should load it first:
Knowing the location and the configuration, we can create the repository:
If you ommit the config parameter, the repository is created in the working directory including the repository.xml file, which is good for a start, if you have no such file.
Now that we have the repository, we want to login to create a session (admin) in order to populate the repository. Therefore we create the credentials (default admin user is admin/admin) and perform a login:
With the repository running and an open session we can initialize the repository with our content model if require some extensions beyond the standard JCR/Jackrabbit content model. In the next step I import a model defined in the Compact Node Definition (CND) Format, described in JCR 2.0
All the code examples above should be performed in the @BeforeClass annotated method so that the repository is only created once for the entire test class. Otherwise a lot of overhead will be generated. Nevertheless, in the @Before and @After annotated methods, you should create your node structures and erase them again (addNode() etc).
Finally, after you have performed you test, you should cleanup the test environment again. Because a directory was created for the transient repository, we have to remove the directory again, otherwise the temp folder will grow over time.
There are three options for cleaning it up.
As fail-safe operation I prefer to add an additional shutdown hook that is executed when the JVM shuts down. This will delete the repository even when the @AfterClass method is not invoked by JUnit. I do not use the deleteOnExit() method of File as it requires the directory to be empty while I could call any code in the shutdown hook using my own cleanup implementation.
A shutdown hook can easily be added to the runtime by specifying a Thread to be executed on VM shutdown. We simply add a call to the destroy methode to the run() method.
Now you should have everything to set-up you Test JCR Repositoy and tear-down the test environment. Happy Testing!
In this article I'd like to describe how you write unit tests for code that accesses a JCR repository.
At first I really tried to mock the JCR API using Mockito, but stopped my attempt at the point where I had to mock the behavior of the Query Object Model. It became apparent, that writing mocks would outweigh the effort to write the actual production code by far. So I had to search for an alternative and found one.
The reference implementation of JCR is the Apache Jackrabbit project. This implementation comes with a set of JCR Repository implementations, one of these is the TransientRepository. The TransientRepository starts the repository on first login and shuts it down on the last session being closed. The repository is created in memory which works pretty fast and makes it the best solution for unit testing. But nevertheless, a directory structure is created for the repository and unless not specified a config file is created as well.
For writing unit tests against this repository, we need the following:
- a temporary directory to locate the directory structure of the repository
- a configuration file (unless you want one created on every startup)
- the repository instance
- a CND content model description to initialize the repository data model (optional)
- an admin session to perform administrator operations
- a cleanup operation to remove the directory structure
- the maven dependencies to satisfy all dependencies
<properties>
<!-- JCR Spec -->
<javax.jcr.version>2.0</javax.jcr.version>
<!-- JCR Impl -->
<apache.jackrabbit.version>2.6.5</apache.jackrabbit.version>
</properties>
...
<dependencies>
<!-- The JCR API -->
<dependency>
<groupId>javax.jcr</groupId>
<artifactId>jcr</artifactId>
<version>${javax.jcr.version}</version>
</dependency>
<!-- Jackrabbit content repository -->
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-core</artifactId>
<version>${apache.jackrabbit.version}</version>
<scope>test</scope>
</dependency>
<!-- Jackrabbit Tools like the CND importer -->
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-jcr-commons</artifactId>
<version>${apache.jackrabbit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
Now let's create the directory for the repository. I recommend to locate it in a temporary folder so multiple test runs don't affect each other if cleanup failed. We use the Java TempDirectory facility for that:
//prefix for the repository folder
import java.nio.file.Files;
import java.nio.file.Path;
...
private static final String TEST_REPOSITORY_LOCATION = "test-jcr_";
...
final Path repositoryPath =
Files.createTempDirectory(TEST_REPOSITORY_LOCATION);
Next, you require a configuration file. If you already have a configuration file available in the classpath, i.e. in src/test/resource, you should load it first:
final InputStream configStream =
YourTestCase.class.getResourceAsStream("/repository.xml");
Knowing the location and the configuration, we can create the repository:
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.jackrabbit.core.TransientRepository;
...
final Path repositoryLocation =
repositoryPath.toAbsolutePath();
final RepositoryConfig config =
RepositoryConfig.create(configStream, repositoryLocation.toString());
final TransientRepository repository =
new TransientRepository(config);
If you ommit the config parameter, the repository is created in the working directory including the repository.xml file, which is good for a start, if you have no such file.
Now that we have the repository, we want to login to create a session (admin) in order to populate the repository. Therefore we create the credentials (default admin user is admin/admin) and perform a login:
final Credentials creds =
new SimpleCredentials("admin", "admin".toCharArray());
final Session session = repository.login(creds);
With the repository running and an open session we can initialize the repository with our content model if require some extensions beyond the standard JCR/Jackrabbit content model. In the next step I import a model defined in the Compact Node Definition (CND) Format, described in JCR 2.0
import org.apache.jackrabbit.commons.cnd.CndImporter; ... private static final String JCR_MODEL_CND = "/jcr_model.cnd.txt"; ... final URL cndFile = YourTestCase.class.getResource(JCR_MODEL_CND); final Reader cndReader = new InputStreamReader(cndFile.openStream()); CndImporter.registerNodeTypes(cndReader, session, true);
All the code examples above should be performed in the @BeforeClass annotated method so that the repository is only created once for the entire test class. Otherwise a lot of overhead will be generated. Nevertheless, in the @Before and @After annotated methods, you should create your node structures and erase them again (addNode() etc).
Finally, after you have performed you test, you should cleanup the test environment again. Because a directory was created for the transient repository, we have to remove the directory again, otherwise the temp folder will grow over time.
There are three options for cleaning it up.
- Cleaning up in @AfterClass annotated method
- Cleaning up using File::deleteOnExit()
- Cleaning up using shutdown hook
import org.apache.commons.io.FileUtils;
...
@AfterClass
public static void destroyRepository(){
repository.shutdown();
String repositoryLocation = repository.getHomeDir();
try {
FileUtils.deleteDirectory(new File(repositoryLocation));
} catch (final IOException e) {
...
}
repository = null;
}
As fail-safe operation I prefer to add an additional shutdown hook that is executed when the JVM shuts down. This will delete the repository even when the @AfterClass method is not invoked by JUnit. I do not use the deleteOnExit() method of File as it requires the directory to be empty while I could call any code in the shutdown hook using my own cleanup implementation.
A shutdown hook can easily be added to the runtime by specifying a Thread to be executed on VM shutdown. We simply add a call to the destroy methode to the run() method.
Runtime.getRuntime().addShutdownHook(new Thread("Repository Cleanup") {
@Override
public void run() {
destroyRepository();
}
});
Now you should have everything to set-up you Test JCR Repositoy and tear-down the test environment. Happy Testing!
Monday, April 28, 2014
Configuring SLF4J with Log4J2 using Maven
In our current project we had to decide for a logging framework. As it apears to be a common standard to use the Simple Logging Facade for Java (SLF4J) on caller side, there were various options on the logging framework itself. In the end we decided to use Log4J 2 as logging framework, mainly for reasons of better performance in comparison to other frameworks (see The Logging Olympics).
The setup of this combination is fairly ease, and there are good examples how to add a SLF4J binding to your Maven project as in this good blog article. But as Log4J is rather new and no final release has been announced yet (current is release candidate 1), it's hard to find a definitive configuration example, so I decided to put down ours.
And a basic log4j configuration (located at your
The setup of this combination is fairly ease, and there are good examples how to add a SLF4J binding to your Maven project as in this good blog article. But as Log4J is rather new and no final release has been announced yet (current is release candidate 1), it's hard to find a definitive configuration example, so I decided to put down ours.
<properties>
<slf4j.version>1.7.6</slf4j.version>
<!-- current log4j 2 release -->
<log4j.version>2.0-rc1</log4j.version>
</properties>
...
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- Binding for Log4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- Log4j API and Core implementation required for binding -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
And a basic log4j configuration (located at your
src/main/resources path) could look like this
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
</Console>
</appenders>
<Loggers>
<Logger name="yourLogger" level="debug" additivity="false">
<AppenderRef ref="Console" />
</Logger>
<Root level="error">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</configuration>
Tuesday, April 1, 2014
Guard Conditions of UML Decision Nodes
In the beginning of the year I attended a requirements engineering class where we discussed - among other topics - activity diagrams. One element of an activity diagram is the decision node, the diamond shape, where you can branch the flow of activities depending on guarding condition for each outgoing edge. There we stumbled upon one - at least to me - completely new aspect on the guard conditions.
According to the UML specification the guard condition protects the entry of an edge. If the condition is not fulfilled, the edge is no entered. Before the above mentioned discussion I always assumed that an edge without a condition always evaluates to true and is always evaluated at last of all outgoing edged and is therefore entered only if none of the other edges' condition applies. But that is wrong!
The truth is, that according to the UML specification the order of the "processing" of the edges is not determined and therefore may be completely random. So if you define an outgoing edge of a decision node without a guarding condition, it may be the case, the edge is entered although another edge's condition may have been met but would be evaluated after the edge without a condition.
Conclusion is, if you want to have a determined behavior of your activities, always define all of the guard conditions of your outgoing edges of decision nodes.
According to the UML specification the guard condition protects the entry of an edge. If the condition is not fulfilled, the edge is no entered. Before the above mentioned discussion I always assumed that an edge without a condition always evaluates to true and is always evaluated at last of all outgoing edged and is therefore entered only if none of the other edges' condition applies. But that is wrong!
The truth is, that according to the UML specification the order of the "processing" of the edges is not determined and therefore may be completely random. So if you define an outgoing edge of a decision node without a guarding condition, it may be the case, the edge is entered although another edge's condition may have been met but would be evaluated after the edge without a condition.
Conclusion is, if you want to have a determined behavior of your activities, always define all of the guard conditions of your outgoing edges of decision nodes.
Subscribe to:
Posts (Atom)