Mr Andersson

Archive for the ‘programming’ Category

Integration testing HTTP service caller using PostBin.org

leave a comment »

Problem: Post-Receive service hooks in GitHub are great. However, the lack all kind of flexibility chosing which commiters and/or branch of a repository the service hooks should be applied to. The other end, Hudson CI in this case, of the service hook call has the same problem.
Solution: As many other have, I started out to write a HTTP proxy which could provide some conditional logic for when to proceed with a Post-Receive call.

I started out driving the development of my proxy using TDD. My initial requirement was to NOT proceed with Post-Receive calls for certain commiters. So I started with the following failing end-to-end tests:

[Test]
public void GivenATargetAndAnIgnoredCommiter_WhenPostingPayloadWithCommitsByIgnoredUserOnly_ThenTargetWillNotBeCalled() {}

[Test]
public void GivenATargetAndAnIgnoredCommiter_WhenPostingPayloadWithCommitsWithAMixOfIgnoredAndNotIgnoredUsers_ThenTargetWillBeCalled() {}

After a while of hacking around I ended up with the following tests which tested my needs of the logic in my little service hook proxy:

[Test]
public void GivenATargetAndAnIgnoredCommiter_WhenPostingPayloadWithCommitsByIgnoredUserOnly_ThenTargetWillNotBeCalled()
{
	var postReceiveHook = GivenATargetAndAnIgnoredCommiter();

	Payload payload = PayloadWithCommitsByIgnoredUserOnly();
	postReceiveHook.Post(payload);

	Assert.AreNotEqual( payload, _testTarget.Received );
}

[Test]
public void GivenATargetAndAnIgnoredCommiter_WhenPostingPayloadWithCommitsWithAMixOfIgnoredAndNotIgnoredUsers_ThenTargetWillBeCalled()
{
	var postReceiveHook = GivenATargetAndAnIgnoredCommiter();

	Payload payload = PayloadWithCommitsWithAMixOfIgnoredAndNotIgnoredUsers();
	postReceiveHook.Post(payload);

	Assert.AreEqual( payload, _testTarget.Received );
}

But these tests, are they really end-to-end tests involving a Hudson CI instance?
Let’s take a look at the class behind the _testTarget field:

internal class TestTarget : IPostReceiveTarget
{
	public HttpStatusCode Call( Payload payload )
	{
		Received = payload;
		return HttpStatusCode.OK;
	}

	public Payload Received { get; private set; }
}

I don’t think so!
But do I want to bundle a complete Hudson CI instance with my NUnit test project? No! So where to draw the line?
Let’s try to find out what we actually want here.

  • Is it important to actually verify that the Hudson CI server can process the GitHub Post-Receive Service Hook JSON payload? Nah.
  • Is it important to verify that it can forward requests to different target URLs (Hudson jobs)? Nah.
  • Is it important to verify that it can receive a payload from GitHub and then resend the same payload to an arbitrary HTTP POST target? Yes!

Let’s take a look at the interface I wrote to separate the conditional logic from faking HTTP requests to Hudson CI in the previous tests:

public interface IPostReceiveTarget
{
	HttpStatusCode Call( Payload payload );
}

Right here I felt a bit bored because I started out writing the HTTP POST service call gateway, no tests involved.
Ended up with the following piece:

public class HttpPostTarget : IPostReceiveTarget 
{
	public HttpPostTarget( string targetUrl )
	{
		Url = targetUrl;
	}

	public HttpStatusCode Call( Payload payload )
	{
		var wc = new WebClient {Encoding = Encoding.UTF8};
		wc.Headers.Add( HttpRequestHeader.ContentType, "application/json" );
		try
		{
			wc.UploadString( Url, JsonConvert.SerializeObject( payload ) );
			return HttpStatusCode.OK;
		}
		catch ( WebException ex )
		{
			var response = ex.Response as HttpWebResponse;
			return response == null ? HttpStatusCode.BadRequest : response.StatusCode;
		}
	}

	public string Url { get; private set; }
}

So what do you say? This code can’t be tested? Well, I could go down the road and write a test which utilizes the HttpListener and verify the payload received by the listener in the test. Doable, yes indeed, but earlier today I was wasting some hour or two on getting the HttpListener to work with Windows Firewall (a.k.a. the “netsh” ceremony) which totally failed since I was hosting the code on a network share on my Mac and trying to fire up the listener on the Windows 7 Parallels VM….Aaarghh! Frustration! I just want the simplest possible thing that could work out of the box!

Suddenly I remembered a web hook debug thingy I stumpled upon a couple of months earlier:

  1. Go to www.postbin.org and make a PostBin
  2. Your created PostBin’s URL is shown
  3. Start making HTTP POST requests to that URL
  4. See the result at your PostBin’s URL or access the Atom feed for it (append /feed to the URL)

Excellent!
So what is the most LOC effective and least ugly integration test I can make out of this which tests my HTTP POST code?
Here is what I ended up with:

[TestFixture]
public class HttpPostTargetPostBinTests
{
	[Test]
	public void GivenAPayloadAndAPostBinBucket_WhenCallingTheTarget_ThenPostBinReturnsThePostedPayload()
	{
		const string postBinBucket = "http://www.postbin.org/93483c01";
		var target = new HttpPostTarget( postBinBucket );
		var commitId = new Random().Next().ToString();
		Payload samplePayload = SamplePayload( commitId );
		var status = target.Call( samplePayload );

		var content = GetFirstEntryContentOfAtomFeed( postBinBucket + "/feed" );

		Assert.AreEqual( HttpStatusCode.OK, status );
		StringAssert.Contains( """ + commitId + """, content );
	}

	static string GetFirstEntryContentOfAtomFeed( string atomUrl )
	{
		XNamespace atom = "http://www.w3.org/2005/Atom"; 
		return XDocument.Load( atomUrl ).Descendants( atom + "content" ).First().Value;
	}

	private Payload SamplePayload( string commitId )
	{
		return new Payload { Commits = new[] { new Commit { Id = commitId, Author = new Author { Email = "foo@bar.tm", Name = "Foo Bar" } } } };
	}
}

Someone else can probably make it prettier and more effective but this just works out of the box, without adding any external library references except for NUnit.

Conclusion:
It is very easy to get into trouble when writing tests for problems which are closely tied up with or depending on some technical concepts. In my case I was trying to get away as far as possible from a data format (JSON) and a network protocol (HTTP). A good start seems to be to make the abstractions where you hit these techie stuff. Think of that before you find yourself extending the problem context; Do you really need that infrastructure or external library to deal with your current design issues? Stay in context. When time comes and you need to hit the outer limit of the context, proceed as always: Make the simplest possible thing that could work.

Note:
PostBin is a web site made by Jeff Lindsay. You can fork his work on GitHub.

Advertisements

Written by anderssonjohan

July 19, 2011 at 09:20

Posted in programming

Tagged with , , , ,

WordWrap function in c#

leave a comment »

Today I worked on a piece of code at RemoteX and needed a pretty simple word wrapping function in C# which:
1) breaks between words, if possible
2) breaks words, if they’re too long to fit on one line

I used the almighty code snippet resource but couldn’t find a quick fix for my need without digging further into the different solutions, so here is my contribution to the long list of word-wrapping functions posted around the web.
Just like I tried to use several of the code snippets I found on the web, you are free to use mine.

I take no responsibility for any bugs you may find in this code snippet may include. Please let the tests guide you!

https://github.com/anderssonjohan/snippets/blob/master/wordwrap/WordWrapTests.cs

Written by anderssonjohan

November 3, 2010 at 12:51

Posted in programming

Tagged with ,

Swedish Alt.Net UG Coding Dojo at Avega, Stockholm

with 2 comments

Yesterday I was at my very first Coding Dojo with my fellow collegues Morten and Sebastian. I was somewhat nervous before this event. Coding in group is not an every day occasion for me :). But it went very well and I can only concur on what Morten blogged about.

Adding to that I must say it were so popular that we needed to split up into two conference rooms. Each room was equipped with a projector, a decent table with room enough for about 15 people.
However, even though we split up into two teams (that focused on the same Kata, see link in Morten’s post), we were just too many people around the table. I’m not sure about the exact head count but I guess we ended up with about 9 or 10 people. The most disappointing thing was that one guy was “rolling his own private solution” on his machine during the session. No hard feelings though; I believe this is a sign that we had too many participants in each group.
Worth to say is that each rotation was time limited to 4 minutes with a break of 15 seconds. That means each 4 minutes you rotate around the table and the next person takes the keyboard and continues where the last person left off. The person to the left of the person at the keyboard is the navigator in the pair.
Really nice experience and very nice and bright people in the user group! Thanks Avega (especially Joakim Sundén and his collegues) for hosting the meeting at their office here in Stockholm.
Today I couldn’t resist thinking of how we could do this internally at work (we’re 6 persons writing code at RemoteX so it seems to be just too perfect). Oh, so much cool code to write, so little time. 🙂

Written by anderssonjohan

November 11, 2009 at 23:01

Posted in events, programming

Tagged with , , ,

Switching component implementations in Castle Windsor

leave a comment »

Problem: Test suite for a system for which I need to replace (inject) the behavior of a certain component. The system is using Castle Windsor with an XML configuration file.

In this system integration test I want to use the real container configuration except that I want to switch out a component that does authorization using a database.

The replacement for the real component is as simple as:


public bool IUsernamePasswordVerifier.VerifyPasswordFor( string username, string password )
{
return true;
}
Solution: Tried this, which failed on me. But with a little help from a tiny facility used by the test suite I can now “re-wire” service implementations in the container.
There are probably several other solutions on how one could accomplish the same thing, but this one worked out very well for me.

ComponentRewriterFacility.cs:


using System;
using System.Collections.Generic;
using Castle.Core;
using Castle.Core.Configuration;
using Castle.MicroKernel;

namespace ServiceTests.Service
{
public class ComponentRewriteFacility : IFacility
{
readonly IDictionary<Type, Type> _rewrites;

public ComponentRewriteFacility()
{
_rewrites = new Dictionary<Type, Type>();
}

public void AddRewrite<I, T>() where T : I
{
_rewrites.Add( typeof(I), typeof(T) );
}

public virtual void Init( IKernel kernel, IConfiguration facilityConfig )
{
if( kernel == null )
throw new ArgumentNullException( "kernel" );
kernel.ComponentRegistered += ComponentRegistered;
}

public void Terminate()
{
}

void ComponentRegistered( string key, IHandler handler )
{
if( !ShouldRewrite( handler.ComponentModel ) )
return;
handler.ComponentModel.Implementation = _rewrites[handler.ComponentModel.Service];
}

protected virtual bool ShouldRewrite( ComponentModel componentModel )
{
return _rewrites.ContainsKey( componentModel.Service );
}
}
}

And in our test suite initializer we add the “re-write rule” like this:


IWindsorContainer container = new WindsorContainer();
container.AddFacility<ComponentRewriteFacility>( f => f.AddRewrite<IUsernamePasswordVerifier, AnythingGoesUsernamePasswordVerifier>() );
container.AddFacility<WcfFacility>();
container.Install( Castle.Windsor.Installer.Configuration.FromXmlFile( "Windsor.xml" ) );

Like it? Not? Have a better solution? Please let me know!

Written by anderssonjohan

October 28, 2009 at 19:34

Posted in programming

Tagged with , , , ,

Food, Code, Time and Quality

leave a comment »

Being an enthusiastic software developer is not without its battles. As an metaphor I would like to illustrate this particular (kind of) battle I think of, with some of my own experience as a parent and a bit of a cooking “enthusiast”.

Ok, so you come home late with the kids and you have just had a great time in the park playing around all afternoon. The kids are happy and you feel you have a nice quality moment in life. You also feel quite satisfied with your big dinner plans. Tic-tac-tic-tac. Time flies and you hurry to get home in time for..
Next stop: Dinner.
You: Really enthusiastic about good cooking, nutricious food etc.
Time: Just too late. There is no time to prepare a nice meal of food from the ground up with hungry kids running around, soon screaming and beaten up by each other..
Solution: What was the phone number to that near by pizza/burger/salad/indian/china restaurant again?

If you think of situations like this but with defect software in production, you might have taken one of the following paths what regards the “solution” part:

“- Hey, let’s solve this by increasing the disk space for now so that Windows Error Reporting doesn’t fill up the system volume with error logs”

“- Request timeout? Let’s add another web node so we can continue with our big deployment. Let’s investigate the timeout issue later.”

Depending on your current situation you may right now feel “yeah, what’s wrong with all that?” or “Stop procrastinate! I would ever never do such things – fix the real problem instead”.
Of course you want to start from the ground up and build quality in, but when the shit already have hit the fan, what would YOU do?
I’m not saying that eating fast food or cutting corners in systems development are good things to do all the time. However, there are differences of having a failing/defect system in production and when you are in “experimentation mode” (a.k.a building new features).

For both cases of experimenting/developing with cooking and doing software development, you don’t know for how long you need to experiment to get it “feature completed”. What you DO know is that you for sure want to “get it right”, but again, not necessarily “feature complete”. Therefore you have to do timeboxing to deliver on time without any loss in quality.

To avoid being in the park with the kids too long in the afternoon I can easily add some more automated tests. I can set up my mobile phone to buzz a sound. I could also check the azimuth of the sun, look at the clock tower, use a wrist watch and what not to get a signal when it is time to get started with the dinner.
But even though these tests are valuable and can reveal defects, they are no good if I just ignore to use them.
As I said before, it’s probably not a problem if this happens one or two times. But if you continue doing this you will have a quite dissatified customer (the family).

Or would you? Really?
It certainly depends on how you define what quality time with your family is about.
(yes, believe me when I say my own and my common-law spouse’s definition of “quality” DO differ when the shit already hit the fan in terms of cooking dinner in the weekdays :))

The same goes for computer systems running in production. You and your team may have a higher tolerance (for what some people would call) defects in production.
Maybe you aren’t a “timebox” person and maybe you define quality in other means than the number of automated tests / automated test coverage percentage.

When development tools mature, people changes their minds and/or gets replaced, the definition of describing “good quality” of a particular system may also change alot during the lifetime of the system.
The challange is not just about more automated tests. It’s about developers and managers (a.k.a. people), LOCs, test coverage, tools, time and process.

Further reading:
* The engineering manager’s lament
* Choose Two – The Project Triangle
* We Need More Automated Tests

Written by anderssonjohan

September 15, 2009 at 20:42

Posted in programming, software

How to inject XSL stylesheet reference in WCF service response using a Message encoder

leave a comment »

In order to shape up the presentation of the responses from a RESTful WCF web service to clients such as Firefox, you’ll need to add an XSL stylesheet reference.
In order to do this, the most straight forward thing to do is to hack into your XML serializable classes and implement this using IXmlSerializable.
Since we want to control this in our service, based on the endpoint URI, this approach was not suitable for our needs.
Also, we don’t like cluttering down our serializable entity classes with “presentation logic”/encoding stuff. 🙂

I posted a question about this in MSDN Forums and got a pretty nice answer from Marco Zhou. He has written a message encoder which injects the XSL stylesheet reference on a lower level which is exactly what we wanted to do.

Thanks Marco!

Written by anderssonjohan

May 7, 2009 at 16:13

Posted in programming

Tagged with , ,

Castle Windsor 2.0 RTMed

leave a comment »

Oh yeah! Castle Windsor 2.0 is RTMed!

I just can’t wait ’til we upgrade RemoteX Applications.

Written by anderssonjohan

May 5, 2009 at 12:05

Posted in programming

Tagged with , ,