“High” on “Complexity” and “Estimation” on a Friday night :-)

Guys, is it not all about Complexity? It’s not a complex task at all.. we all know it..

It’s just to change a few characters within a line… So why to raise the Story Points up just because the task consists of 40 such modifications? Each modification does the same.. In that way, shouldn’t the whole task weigh the same level of complexity as of any of those single modifications within the task?

Guys, come on.. shouldn’t we consider only Complexity when it comes to Estimation? Have we started worrying about the “Time” while we estimate? is that not completely against of Agile Estimation principles? Is that not why we use Story Points instead of hours?

Then someone countered ….

How can it be same, when you have to repeat the effort for “n” number of times? It should not be. Isn’t it common sense?

Then again…

Complexity, my friend… Is it not the same Complexity with each modification? Then why is it not the same for whole..

Thus, it had been going in a circle for quite some time 🙂

That is when someone came up with an interesting analogy… very logical… it went on like this….

I find that the driving in a Freeway for any distance bears the same level of Complexity – be it for 10 kilometers or 100 kilometers ..

It’s because, the the required driving skills stay all same.. And, the traffic signs mostly would stay same… Even the traffic density would stay same too…

But would that mean Estimation for both travels would stay same? Nah, it would proportionally increase with each kilometer. It would even go up exponentially may be after 30 kms because my concentration will come down with each kilometer.

So, if I consider only Complexity, how useful that Estimation going to be for me?

I estimate because I may have to check-in to a hotel on time.. How would this estimation be of any use to me if I consider only Complexity?

Should we not consider the “effort”?

Ok… now..

Yes, does that not make sense? Why can’t we consider other factors besides “complexity”? Can’t we consider Repetitiveness as a factor..

And then….

How about considering this… something like level of Uncertainty… In line with what is mentioned above, something like I don’t know the exact route for the trip… Yes, I don’t have a mobile phone or GPS 🙂 so, a chance that I might miss the route… how about considering that too while I estimate…

Suddenly…

Oh wait… Repetitiveness and Uncertainty… why do you consider all these as different from the concept “complexity”? Does it not sound like it wraps all such factors? So you essentially mean that complexity for a 100 km drive is more than a 10 km drive considering the factors repeatitiveness and uncertainty – did you not?

 

Is it? So the complexity for 40 such modifications are certainly more than one such modification, though each modification involves change in only a few characters and straight-forward, isn’t it?

There must have been better things to do on Friday nights 🙂

Jokes apart, I came across this write-up – http://pm.stackexchange.com/a/2766.

Cleaning meta-programmed Grails service object for each test method of Integration Test Class

Well, yes.. that was pretty much the problem I was combating with 🙂

It was to write an Integration test for a Grails Service. The Service talks to a REST end-point. I need to test the service behavior against the different types of responses returned from this End Point.

class MyService {
	def endPointAPI
	def process (def inputDataMap) {
        def parametersToEndPoint = manipulate(inputDataMap)        
		def endPointResult = endPointAPI.send (parametersToEndPoint)
		if (endPointResult == SOME_VALUE1) {
			return serviceLogicForSomeValue1 (parametersToEndPoint, endPointResult)
		} else if (endPointResult == SOME_VALUE2) {
			return serviceLogicForSomeValue2 (parametersToEndPoint, endPointResult)
		} else {
			return false
		}
	}
}

I have three different test cases for this Service class. The first for a value SOME_VALUE1 returned by End Point. I know that one such test would be good enough to cover the serviceLogicForSomeValue1 of the Service. Similary, the second should assume SOME_VALUE2 from End Point that helps to testserviceLogicForSomeValue1 of Service. Now, the third is to test the logic that gets executed for any value returned by the End Point other than SOME_VALUE1 and SOME_VALUE2.

So clearly, the first two tests do not require the flow to run the whole End Point logic, as it can assume the End Point values by stubing it through Groovy meta-programming. And, the third do not require any stubbing at all, since the test is OK with any value returned from the End Point. With this, there is an additional benefit of getting the original flow tested from the Service through to End Point.

So, here it goes the test cases.

class MyServiceTests extends BaseIntegrationTests {
	def myService

	void testServiceLogicForSomeValueOne () {
		def inputDataMap = prepareInputDataMap ()
		myService.endPointAPI.metaClass.send = { def dataToSent ->
			return SOME_VALUE1
		}
		def processResult = myService.process (inputDataMap)

		assertEquals (expectedProcessResultFromServiceLogicForSomeValue1, processResult)
	}
	void testServiceLogicForSomeValueTwo () {
		def processInputArguments = prepareInputDataMap ()
		myService.endPointAPI.metaClass.send = { def dataToSent ->
			return SOME_VALUE2
		}
		def processResult = myService.process (inputDataMap)
		assertEquals (expectedProcessResultFromServiceLogicForSomeValue2, processResult)
	}
	void testServiceLogicIfNotSomeValueOneOrSomeValueTwo () {
		def processInputArguments = prepareInputDataMap ()
		def processResult = myService.process (inputDataMap)
		assertEquals (false, processResult)
	}
}

Now, run the test using “grails test-app :integration MyService”, and inspects the result. You would find that the first two test cases did run fantastically for you. But have you got confused with what you see with the result of the third?

In the third, you would see that myService.process is bringing in expectedProcessResultFromServiceLogicForSomeValue2( or expectedProcessResultFromServiceLogicForSomeValue1 based on which got modified last). Oh, why ?

Of course..  if the third still gets expectedProcessResultFromServiceLogicForSomeValue2 then it still keeps the reference to the stub injected by the second. But why?

ok then, let me ask you one thing.. why did you expect that it won’t retain the changes in the first place? Did you not presume for some reason that every test execution method starts with a clean service object.

Well, this is true for a Unit Test Case. GrailsUnitTestCase and GrailsUnitTestMixin classes provide in-built support for this through its registerMetaClass and tearDown methods. But not for Integration Test Framework !!!

Grails retains a singleton service class for one full run of the integration test class across all of its test methods – so are the metaclass modifications we applied to. Probably, what we may have got confused with the Grails feature of Transaction Demarcation ensured for every integration test method that reverts any database modification done by each test method.

Now, can I somehow mixin or inject the GrailsUnitTestCase within the Integration Test Execution ?  Test framework ensures that only one Test Scope is enabled for one test execution. So mixing-in or injecting won’t be an option, since then Grails would turn on the Unit Testing scope where we would not be having the features like transactional support that an integration test requires.

Ok, then how about this option? Let the test case store the references of to-be-metaprogrammed objects in its setup method, then subsequently let the tearDown method to nullify its metaclass so that the temporary changes will go off. You would have immediately realized the danger involved with this. Nullifying the metaclass would not only the removes the test class metaprogramming, but also any of the metaprogramming implemented the application flow. So, no.. not to go in this track down.

How about mimicking the behaviour of GrailsUnitTestCase within my testing framework? How about invoking those methods of GrailsUnitTestCase programmatically from my integration test case? GrailsUnitTestCase’s registerMetaClass method helps to register any Groovy class that undergoes metaprogramming which helps its tearDown method to revert the state of metaClass to the state before the changes. So theoratically speaking, I can copy those methods and its dependent internal logic to simulate the same. But this would be a very brittle one to go for. I have seen that the metaclass cleanup logic in Groovy 2.1.9 is drastically different from that in Groovy 1.8. So, it is not at all a good practice to copy the Groovy internal logic into our source code which can go broken during the upgrades.

Yes, this idea was driven out of academical curiousity to know how Groovy does all this metaclass cleanup – not a one I really expected to come out as a solution as such. At the same time, I wanted to ensure that I did not miss out to explore all the possible ways 🙂

Till now, our all thought process was in the direction of reverting the metaprogramming changes. Each of our solutions were rooted around it. How about taking a different track? Like, I don’t care what happened to the metaprogrammed instance – but make a new instance available to every test method – how about it?

But that would mean that I cannot depend on the singleton service spring bean created by Grails. If I am going to take care of the creation of that object with all of its dependencies, there wouldn’t be any thing worse than my day-to-day test case development cycle. Life is going to be more and more difficult as I go through more and more test classes.

World is with full of solutions 🙂  It was my team mate who took me through this line of thinking with an idea proposed by an article at http://naleid.com/blog/2011/03/07/creating-new-instances-of-spring-singleton-beans-with-grails-beanbuilder.

This article explains how can we create a grails service bean object using the Grails bean builder support. That would mean that, I don’t have to worry about its dependencies – which is already known to the Grails bean builder API.

At last.. gone are those dark clouds … and its bright shiny day again …. 🙂 Of course that poetic one is a copy-paste 🙂 But I don’t care, I felt the very same when I reached here 🙂

Still, there is one thing I did not get answer for. Why Integration Test Execution is treated differently from Unit Test Execution when it came to the service object life cycle? Anyway, not now – may be for another time 🙂

 

Story of loading Grails Config keys from Database :-)

We are familiar with externalising the configuration keys through flat files which could be introduced through Config.groovy. Primarily, this helps majorly in the production environment to customise the configuration keys without touching the WAR.

Now, what if I keep my configuration keys externalised through Database? How to load these into the Configuration Context before the Grails Runtime start making use of those?

Remember.. many keys are even used for the construction of some of the spring bean objects that belong to the plugins within my project. So, loading from BootStrap.groovy won’t be an option which happens a little late in the life cycle for me. So, we somehow need to get hold of the configuration context right after Grails initialised it.

How do we know when Grails has done with its configuration context loading? Notifying the needy of something happened do indicate of the observer-observable pattern. And in Grails, as we know, the way to listen to Grails Life Cycle notifications is through the eventListeners placed in _Events.groovy.

Now that could be interpreted rightly that if there is an event that Grails fires to indicate the completion of configuration context loading, then we can comfortably place the respective event handler in _Events.groovy. This event handler then will help us to merge those configuration keys read from the Database with the ones in the Grails configuration context that are accessible through grails.util.Holders.config API. Now we need to find out if there is such an event exist?

Grails portal documentation at http://grails.github.io/grails-doc/2.3.x/guide/commandLine.html#events did not leave any clue about it. Some serious head-down debugging through the Grails source code, using Intellij IDEA breakpoints, helped me to zero-in on GrailsProjectPackager.createConfig method. This does the parsing of Config.groovy including its links to the externalised config flat files. It eventually notifies the BuildEventListener about the completion of configuration loading. I was happy to see that I get notified about this through the eventAppCfgEnd event handler placed within the _Events.groovy. As it is not documented in the Grails document, I am not sure if it is not intended for development purposes.

But twist happened next when my team mate informed me that the event handler he placed in his _Events.groovy do not getting notified of it. Further debugging revealed that mine was test-app execution environment, while his was run-app. The set of events to be triggered are chosen by the execution environment and that varies between test-app and run-app. I couldn’t check it for WAR yet, but I expect the same as of run-app.

As a matter of fact, there was an open Grails 2.3.7 issue that complains of parsing the configuration files multiple times during the run-app (https://github.com/grails/grails-core/issues/4925). One of the comments under this issue had explained that the configuration files would be parsed two times in a non-forked mode – first time to load the log4j configuration, and the latter during web-app context initialization. However, my personal experience was that it parses 4 times with 2.3.7 instead of just 2 – anyway that is a different topic altogether. Doesn’t matter 2 or 4, my point here was that if that could be the reason why run-app was decided not to throw “eventCfgEnd”. And if then, there could be some other event to indicate the log4j configuration loading and web-app configuration loading?

Further debugging showed up that the first config loading happens right after the “eventCompileEnd” but before “eventConfigureServerContextPathEnd”. While the second happens right after “eventPackageAppEnd”; but before “eventStatusUpdate (“Running Grails Application”)”. However, I noticed that there is an if-check within the createConfig method not to proceed if there is context alredy available due to which the second one do not really enter inside. So, I decided to depend upon “eventConfigureServerContextPathEnd”. However, like the eventCfgEnd, this too was not documented under Grails portal.

Anyway I along with my team determined to proceed with this approach. Idea was to load Database keys into Holders.config through the event handler I placed in _Events.groovy for “eventConfigureServerContextPathEnd”. Then we have injected this key into a Spring Bean property through resources.groovy which would complete loading-accessing user story. But here we stumbled upon another hurdle.

The grails.util.Holders API uses a class Holder.groovy to manage the storage of configuration context keys. This ensures that the accessors and the loaders of the keys should be loaded by the same classloader instance. In our case, _Events.groovy was loaded during the build cycle by a class loader which seemed to be different from the one used for the remaining. So, a configuration key set dynamically through Holders.config.someKey = “someValue” from _Events.groovy file won’t be available to use within the classes, loaded after the build-cycle – say resources.groovy.

So, I have to go through a little dirty way to create a customHolder class that maintains a private static ConfigObject within it to store the dynamically populated config keys from _Events.groovy – like CustomHolder.config.someKey = “someValue”. Also added a getConfig API for this class to return a ConfigObject.merge of this private ConfigObject with Holder.config that ensures the super set of keys. The calls in resources.groovy then can use CustomHolder.config.someKey.

I know that this contradicts the design concept around Holder.groovy to access-restrict around the class-loader. But I do not see that it will affect my user stories anyway. More than that, I was surprised to see such a restriction imposed upon the classes belong to the same Grails application. In my opinion, for a rapid web application development framework like Grails, a Grails developer should never had to run against class-loading related issues to work within the same JVM. But that does not seem to be the case here.