Introduction
Some time has passed since we wrote our last blogpost about Apache NiFi where we pointed out what could be improved. It is very nice tool, so we are still using Read more
The enum class with instance method in Kotlin is quite similar to its Java version, but they are look a bit different Read more
The object
keyword in Kotlin creates singleton in a very convenient way. It can be used for example as a state of an operation. Spock Framework is one of the most expressive Read more
I am happy to announce a first release of my Sonar Gerrit plugin. This plugin reports Sonar violations on your patchsets to your Gerrit server. Sonar analyses full project, but only files included in patchset are commented on Gerrit. Please forward to project page for installation instructions.
This plugin is intended to use with Gerrit Trigger plugin for Jenkins CI server. Together they provide a great tool for automatic static code analysis.
At the moment you push a patchset to Gerrit, Jenkins is notified with a ssh event. It fetches a code with a patchset and it builds your changes. It quits when build or tests fail.
But if it succeeds, Sonar analase your project in a post-build action. This is a place where my Sonar Gerrit plugin shines. It asks Gerrit for changed files before analysis and after Sonar analysis is finished, plugin reports comments on these files as a Gerrit reviewer. Currently plugin always reports +1 for Code Review, as it's still in development. However, you should always treat these comments as hints to improve, not as direct errors.
I've released also a second plugin: Sonar File Alerts plugin. This plugin raises alerts on file level in Sonar. It extends default behaviour, which raises alerts only at root project level. It is useful when you create alert rules in Sonar like "Code Coverage < 60"
. Each file is checked against this rule!
If you use Sonar File Alerts plugin and an alert will be generated on some file, then a comment will be published on this file on Gerrit.
Please provide a feedback on these plugins. Feel free to submit issues on github or comment. It's still an early stage so your input is very welcome!
I am happy to announce a first release of my Sonar Gerrit plugin. This plugin reports Sonar violations on your patchsets to your Gerrit server. Sonar analyses full project, but only files included in patchset are commented on Gerrit. Please forward to project page for installation instructions.
This plugin is intended to use with Gerrit Trigger plugin for Jenkins CI server. Together they provide a great tool for automatic static code analysis.
At the moment you push a patchset to Gerrit, Jenkins is notified with a ssh event. It fetches a code with a patchset and it builds your changes. It quits when build or tests fail.
But if it succeeds, Sonar analase your project in a post-build action. This is a place where my Sonar Gerrit plugin shines. It asks Gerrit for changed files before analysis and after Sonar analysis is finished, plugin reports comments on these files as a Gerrit reviewer. Currently plugin always reports +1 for Code Review, as it's still in development. However, you should always treat these comments as hints to improve, not as direct errors.
I've released also a second plugin: Sonar File Alerts plugin. This plugin raises alerts on file level in Sonar. It extends default behaviour, which raises alerts only at root project level. It is useful when you create alert rules in Sonar like "Code Coverage < 60"
. Each file is checked against this rule!
If you use Sonar File Alerts plugin and an alert will be generated on some file, then a comment will be published on this file on Gerrit.
Please provide a feedback on these plugins. Feel free to submit issues on github or comment. It's still an early stage so your input is very welcome!
If you use IntelliJ IDEA for your Grails development you might encounter this error running integration tests:
Error Error generating web.xml file (Use --stacktrace to see the full trace)
The reason for this is that IDEA adds classpath by default on creating integration test run configuration. Unfortunately, sometimes it causes strange errors like this one. Follow these steps to resolve:
Even since I started to write tests for my Grails application I couldn't find many articles on using mocks. Everyone is talking about tests and TDD but if you search for it there isn't many articles.
Today I want to share with you a test with mocks for a simple and complete scenario. I have a simple application that can fetch Twitter tweets and present it to user. I use REST service and I use GET to fetch tweets by id like this: http://api.twitter.com/1/statuses/show/236024636775735296.json. You can copy and paste it into your browser to see a result.
My application uses Grails 2.1 with spock-0.6 for tests. I have TwitterReaderService
that fetches tweets by id, then I parse a response into my Tweet
class.
TwitterController
plays main part here. Users call show
action along with id
of a tweet. This action is my subject under test. I've implemented some basic functionality. It's easier to focus on it while writing tests.
Let's start writing a test from scratch. Most important thing here is that I use mock for my TwitterReaderService
. I do not construct new TwitterReaderService()
, because in this test I test only TwitterController
. I am not interested in injected service. I know how this service is supposed to work and I am not interested in internals. So before every test I inject a twitterReaderServiceMock
into controller:
Now it's time to think what scenarios I need to test. This line from TwitterReaderService
is the most important:
You must think of this method like a black box right now. You know nothing of internals from controller's point of view. You're only interested what can be returned for you:
TwitterError
can be thrownnull
can be returnedTweet
instance can be returnedThis list is your test blueprint. Now answer a simple question for each element: "What do I want my controller to do in this situation?" and you have plan test:
show
action should redirect to index if TwitterError
is thrown and inform about errorshow
action should redirect to index and inform if tweet is not foundshow
action should show found tweetThat was easy and straightforward! And now is the best part: we use twitterReaderServiceMock
to mock each of these three scenarios!
In Spock there is a good documentation about interaction with mocks. You declare what methods are called, how many times, what parameters are given and what should be returned. Remember a black box? Mock is your black box with detailed instruction, e.g.: I expect you that if receive exactly one call to readTweet
with parameter '1' then you should throw me a TwitterError
. Rephrase this sentence out loud and look at this:
This is a valid interaction definition on mock! It's that easy! Here is a complete test that fails for now:
You may notice 0 * _._
notation. It says: I don't want any other mocks or any other methods called. Fail this test if something is called! It's a good practice to ensure that there are no more interactions than you want.
Ok, now I need to implement controller logic to handle TwitterError
.
My tests passes! We have two scenarios left. Rule stays the same: TwitterReaderService
returns something and we test against it. So this line is the heart of each test, change only returned values after >>
:
Here is a complete test for three scenarios and controller that passes it.
The most important thing here is that we've tested controller-service interaction without logic implementation in service! That's why mock technique is so useful. It decouples your dependencies and let you focus on exactly one subject under test. Happy testing!
Our client requires that every entity in his Grails application has to be audited with detailed information: who and when did exactly what? It is a perfect opportunity to use Hibernate Envers! It turned out not as straightforward as I thought, so I want to share my experience with you.
I use latest release of Grails with version 2.1.0. I've created a sample application on github for you as an example - SpOOnman/enversdemo. All files and techniques mentioned here can be found inside it. If you have other experiences with Grails and Envers working together, please share in comments.
First I've searched for a Grails plugin. I've found one outdated on google code and a (more modern) on github. This plugin is created by Lucas Ward and it has great introductionary blog post by author. This is a great place to start.
Unfortunately Lucas Ward's plugin supports Grails up 1.3.7 and it comes with outdated Envers version. I've searched through forks and I've found most up-to-date fork by Matija Folnovic: https://github.com/mfolnovic/grails-envers-plugin. It supports Grails 2.1 out of the box. Edit: Matija pointed out that credit should go to Jay Hogan and Damir Murat for their work on upgrading Envers plugin to Grails 2.
Matija's plugin is not packaged nor published so you have to package it by yourself:
Copy grails-envers-0.3-SNAPSHOT.zip (and rename to envers-0.3-SNAPSHOT.zip) to your application's lib diretory or publish to your company maven repository if you have one. Last step is to include a plugin in your BuildConfig.groovy:
It's really easy to audit all entities with Envers. All you have to do is to use @Audit
annotation on entities. SpOOnman/enversdemo audits Hotels and Bookings:
Envers plugin comes with some handy methods. For example Hotel.findAllRevisions()
returns list of previous revisions. Once again I recommend a great blog post by Lucas Ward with many examples.
Grails has some glitches working with Envers. Envers is closely tied to database transactions. This means that it runs its listeners at the transaction end, when session is flushed. This is not always the case in Grails and it's the cause of some problems. You need to make some small modifications to your application to be sure that Envers works fine.
@Transactional
and for every save you need to flush a session manually, e.g. save(flush: true)
. Otherwise Envers may not be notified.static transactional = true
to be sure that this is not altered. I recommend to use session flushing on every save as well.static transactional = false
. Remember that your changes are commited to database. To fulfill a contract of an empty database for every test you need to take care of cleaning up a database manually. Here is my sample integration test.By default Envers comes with a DefaultRevisionEntity class and creates its instance for every change on audited instance. It keeps information about entity revision, date and modification type. It lacks information about a user that made a change. I want to extend it.
There is already a code inside a plugin (here and here) but it's not packaged with a plugin itself. I guess it's because it adds dependency to Spring Security. This not a problem for me since I already use Spring Security plugin already in my application. I decided to add missing classes inside my application.
First I need a domain class - UserRevisionEntity. New instance of this class is created for every revision saved by Envers. It is a simple domain class with some extra annotations:
Notice that I've made currentUser field nullable. There may be some actions that doesn't require user to be logged in. Also, there is no user while executing BootStrap.groovy script.
Annotations @RevisionNumber
and @RevisionTimestamp
are required by Envers as described in documentation. @RevisionEntity
annotation configures Envers to use non-default listener - SpringSecurityRevisionListener. It looks simple:
SpringSecurityRevisionListener's newRevision method fills each UserRevisionEntity instances with currently logged User.
Envers offers some configuration options listed on documentation page. Options can be set in persistence.xml. However in Grails there is no persistence.xml. You can add it (and Grails supports it), but I've found other way to configure properties. I use System.setProperties to configure Envers and I place it in grails-app/conf/spring/resources.groovy. This is an example to change Envers tables' prefix and suffix:
Testing Envers makes sense only with Grails integration tests. As I've mentioned earlier you must disable transactions that wrap your tests in order for Envers listeners to work. Also make sure you use withTransaction, session flushing and you've marked your controllers as @Transactional
. There rules all stand in integration tests too. Example integration test can look like this:
Hibernate Envers does a great job auditing my application. It is easy to use, despite all the small glitches I've mentioned here. Special thanks to plugin authors that package Envers library in a plugin that can be used out of the box. I really recommend it! It would be great to hear all your thoughts on Envers and Grails working together so I can improve this post for others too.
Lucas Ward has posted updaate entry on Grails Hibernate Envers plugin here: http://www.lucasward.net/2013/04/grails-envers-plugin-update.html. Thanks!