Testing framework is not just for writing… tests

January 18th, 2012 3 Comments

Quick ques­tion – from the top of your head, with­out run­ning the code, what is the result of:

var foo = -00.053200000m;
var result = foo.ToString("##.##");

Or a dif­fer­ent one:

var foo = "foo";
var bar = "bar";
var foobar = "foo" + "bar";
var concaternated = new StringBuilder(foo).Append(bar).ToString(); 

var result1 = AreEqual(foobar, concaternated);
var result2 = Equals(foobar, concaternated);

public static bool AreEqual(object one, object two)
{
    return one == two;
}

How about this one from NHibernate?

var parent = session.Get<Parent>(1); 

DoSomething(parent.Child.Id); 

var result = NHibernateUtil.IsInitialized(parent.Child);

The point being?

Well, if you can answer all of the above with­out run­ning the code, we’re hir­ing. I don’t, and I sus­pect most peo­ple don’t either. That’s fine. Ques­tion is – what are you going to do about it? What do you do when some 3rd party library, or part of stan­dard library exhibits unex­pected behav­iour? How do you go about learn­ing if what you think should hap­pen, is really what does happen?

Scratch­pad

I’ve seen peo­ple open up Visual Stu­dio, cre­ate ConsoleApplication38, write some code using the API in ques­tion includ­ing plenty of Console.WriteLine along the way (curse who­ever decided Client Pro­file should be the default for Con­sole appli­ca­tions, switch to full .NET pro­file) com­pile, run and dis­card the code. And then repeat the process with ConsoleApplication39 next time.

 

The solu­tion I’m using feels a bit more light­weight, and has worked for me well over the years. It is very sim­ple – I lever­age my exist­ing test frame­work and test run­ner. I cre­ate an empty test fix­ture called Scratchpad.

scratchpad

scratchpad_fixture

This class gets com­mit­ted to the VCS repos­i­tory. That way every mem­ber of the team gets their own scratch­pad to play with and val­i­date their the­o­ries, ideas and assump­tions. How­ever, as the name implies, this all is a one-off throw­away code. After all, you don’t really need to test the BCL. One would hope Microsoft already did a good job at that.

If you’re using git, you can eas­ily tell it not to track changes to the file, by run­ning the fol­low­ing com­mand (after you com­mit the file):

git update-index –assume-unchanged Scratchpad.cs

scratchpad_git

With this sim­ple set up you will have quick place to val­i­date your assump­tions (and answer ques­tions about API behav­iour) with lit­tle friction.

scratchpad_test

So there you have it, a new, use­ful tech­nique in your toolbelt.

Approval testing – value for the money

January 16th, 2012 2 Comments

I am a believer in the value of test­ing. How­ever not all tests are equal, and actu­ally not all tests pro­vide value at all. Raise your hand if you’ve ever seen (unit) tests that tested every cor­ner case of triv­ial piece of code that’s used once in a blue moon in an obscure part of the sys­tem. Raise your other hand if that test code was not writ­ten by human but generated.

 

As with any type of code, test code is a lia­bil­ity. It takes time to write it, and then it takes even more time to read it and main­tain it. Con­sid­er­ing time is money, rather then blindly unit test­ing every­thing we need to con­stantly ask our­selves how do we get the best value for the money – what’s the best way to spend time writ­ing code, to write the least amount of it, to best cover the widest range of pos­si­ble fail­ures in the most main­tain­able fashion.

Notice we’re opti­mis­ing quite a few vari­ables here. We don’t want to blindly write plenty of code, we don’t want to write sloppy code, and we want the test code to prop­erly ful­fil its role as our safety net, alarm­ing us early when things are about to go belly up.

Test­ing conventions

What many peo­ple seem to find chal­leng­ing to test is con­ven­tions in their code. When all you have is a ham­mer (unit test­ing) it’s hard to hit a nail, that not only isn’t really a nail, but isn’t really explic­itly there to being with. To make mat­ters worse the com­piler is not going to help you really either. How would it know that Login­Con­troller not imple­ment­ing ICon­troller is a prob­lem? How would it know that the new depen­dency you intro­duced onto the con­troller is not reg­is­tered in your IoC con­tainer? How would it know that the pub­lic method on your NHiber­nate entity needs to be virtual?

 

In some cases the tool you’re using will pro­vide some level of val­i­da­tion itself. NHiber­nate knows the meth­ods ought to be vir­tual and will give you quite good excep­tion mes­sage when you set it up. You can ver­ify that quite eas­ily in a sim­ple test. Not every­thing is so black and white how­ever. One of diag­nos­tics pro­vided by Cas­tle Wind­sor is called “Poten­tially mis­con­fig­ured com­po­nents”. Notice the vague­ness of the first word. They might be mis­con­fig­ured, but not nec­es­sar­ily are – it all depends on how you’re using them and the tool itself can­not know that. How do you test that efficiently?

Enter approval testing

One pos­si­ble solu­tion to that, which we’ve been quite suc­cess­fully using on my cur­rent project is approval test­ing. The con­cept is very sim­ple. You write a test that runs pro­duc­ing an out­put. Then the out­put is reviewed by some­one, and assum­ing it’s cor­rect, it’s marked as approved and com­mit­ted to the VCS repos­i­tory. On sub­se­quent runs the out­put is gen­er­ated again, and com­pared against approved ver­sion. If they are dif­fer­ent the test fails, at which point some­one needs to review the change and either mark the new ver­sion as approved (when the change is legit­i­mate) or fix the code, if the change is a bug.

 

If the expla­na­tion above seems dry and abstract let’s go through an exam­ple. Wind­sor 3 intro­duced way to pro­gram­mat­i­cally access its diag­nos­tics. We can there­fore write a test look­ing through the poten­tially mis­con­fig­ured com­po­nents, so that we get noti­fied if some­thing on the list changes. I’ll be using Approval­Tests library for that.

[Test]
pub­lic void Approved_potentially_misconfigured_components()
{
    var con­tainer = new Wind­sor­Con­tainer();
    container.Install(FromAssembly.Containing<HomeController>());

    var han­dlers = GetPotentiallyMisconfiguredComponents(container);
    var mes­sage = new String­Builder();
    var inspec­tor = new DependencyInspector(message);
    fore­ach (IEx­poseDe­pen­den­cy­Info han­dler in han­dlers)
    {
        handler.ObtainDependencyDetails(inspector);
    }
    Approvals.Approve(message.ToString());
}

pri­vate sta­tic IHan­dler[] GetPotentiallyMisconfiguredComponents(WindsorContainer con­tainer)
{
    var host = container.Kernel.GetSubSystem(SubSystemConstants.DiagnosticsKey) as IDi­ag­nos­tic­sHost;
    var diag­nos­tic = host.GetDiagnostic<IPotentiallyMisconfiguredComponentsDiagnostic>();
    var han­dlers = diagnostic.Inspect();
    return han­dlers;
}

What’s impor­tant here is we’re set­ting up the con­tainer, get­ting the mis­con­fig­ured com­po­nents out of it, pro­duce read­able out­put from the list and pass­ing it down to the approval frame­work to do the rest of the job.

Now if you’ve set up the frame­work to pup-up a diff tool when the approval fails you will be greeted with some­thing like this:

approval_diff

You have all the power of your diff tool to inspect the change. In this case we have one new mis­con­fig­ured com­po­nent (Home­Con­troller) which has a new para­me­ter, appro­pri­ately named miss­ing­Pa­ra­me­ter that the con­tainer doesn’t know how to pro­vide to it. Now you either slap your­self in the fore­head and fix the issue, if that really is an issue, or approve that depen­dency, by copy­ing the diff chunk from the left pane to the right, approved pane. By doing the lat­ter you’re noti­fy­ing the test­ing frame­work and your team­mates that you do know what’s going on and you know it’s not an issue the way things are going to work. Cou­pled with a sen­si­ble com­mit mes­sage explain­ing why you chose to approve this dif­fer­ence you get a pretty good trail of excep­tion to the rule and rea­sons behind them.

 

That’s quite an ele­gant approach to a quite hard prob­lem. We’re using it for quite a few things, and it’s been giv­ing us really good value for lit­tle effort it took to write those tests, and main­tain them as we keep devel­op­ing the app, and the approved files change.

 

So there you have it, a new, use­ful tool in your toolbelt.

API design challenge – builder

December 31st, 2011 3 Comments

Now that Wind­sor 3 is released I can con­cen­trate on some of my other ideas and projects. While work­ing on one of them, called Car­tog­ra­pher, I encoun­tered an inter­est­ing API design problem.

 

I have a class (a builder to be pre­cise) that has a task of set­ting up a cen­tral object (an IMap­per imple­men­ta­tion) in Car­tog­ra­pher (If you’ve ever used Aut­o­fac, it is some­what anal­o­gous to Con­tainer­Builder). What is inter­est­ing about it, is I have three goals for that class:

  1. Pro­vide API for high level con­fig­u­ra­tion and exten­sion points that are uni­ver­sal to and intrin­sic to any IMap­per implementation.
  2. Pro­vide API for low level con­fig­u­ra­tion of the default IMap­per imple­men­ta­tion that the builder cre­ates, that will meet the fol­low­ing criteria:
    1. Not force user to cus­tomize any­thing, as the default setup should be enough to get started in most cases.
    2. Allow users to eas­ily swap/extend parts of the depen­dency chain of the default mapper.
    3. Work well and be nat­ural both with and with­out IoC container .
  3. Be sim­ple and dis­cov­er­able to the users (and pro­vide good Intel­lisense experience).

How would you design the API for this class?

 

Oh, and happy new year.

Castle Windsor 3.0 is released

December 16th, 2011 9 Comments

Castle Windsor

After suc­cess­ful beta and RC releases final ver­sion of Cas­tle Wind­sor (as well as Cas­tle Core, and a whole set of facil­i­ties) has now been released. There are no major changes between final ver­sion and RC. The dif­fer­ence is some minor bug fixes, improved excep­tion mes­sages and some small improve­ments all over the place.

 

The pack­ages are avail­able now, on Nuget (with sym­bols), and via stan­dard .zip down­load.

 

Last but not least — thank you to every­one who down­loaded beta and release can­di­date and pro­vided feed­back. You guys rock.

Getting closer… Castle Windsor 3 RC 1

November 20th, 2011 5 Comments

Few weeks later than orig­i­nally expected but here it is – Cas­tle Wind­sor 3.0 (along with its facil­i­ties and Castle.Core) achieved release can­di­date status.

There is one major new fea­ture in this release: reg­is­tra­tion API gained abil­ity to spec­ify prop­er­ties to ignore/require. There are some sce­nar­ios where that’s use­ful, for exam­ple where inte­grat­ing with some 3rd party frame­work that forces you to inherit from a base class which exposes its depen­den­cies as prop­er­ties. Cre­at­ing pass-through con­struc­tors for each inher­ited class can be mun­dane. In those cases you can sim­ply mark those base class prop­er­ties as required, in which case Wind­sor will not allow them to be resolved unless all base prop­erty depen­den­cies are sat­is­fied. Prop­er­ty­Fil­ter enum sup­ports sev­eral other most com­mon sce­nar­ios, and for advanced cases there’s an over­load that gives you more control.

Container.Register(
    Classes.FromThisAssembly()
        .BasedOn<ICommon>()
        .Configure(c => c.Properties(PropertyFilter.RequireBase)));

To address per­for­mance hit at startup Wind­sor no longer enables per­for­mance coun­ters by default. Now, you have to do it explicitly:

var container = new WindsorContainer();
var diagnostic = LifecycledComponentsReleasePolicy.GetTrackedComponentsDiagnostic(container.Kernel);
var counter = LifecycledComponentsReleasePolicy.GetTrackedComponentsPerformanceCounter(new PerformanceMetricsFactory());
container.Kernel.ReleasePolicy = new LifecycledComponentsReleasePolicy(diagnostic, counter);

Full changelog is included in the pack­ages. Please, if pos­si­ble, take the time to upgrade to this ver­sion and if you find any issues report them so that the final release is rock solid. If no major issues are found, the final release will be pub­lished in two weeks.

The bina­ries are avail­able on Nuget right now, and soon on our web­site.

Connector: Simple, zero friction Github –> AppHarbor integration

September 18th, 2011 1 Comment

Recently to play with some new tech­nol­ogy I came up with an idea to build an inte­gra­tion layer between Github and AppHar­bor. What that means, is give you abil­ity to work with your Github repos­i­tory, reap­ing ben­e­fits of all of it’s VCS-centric fea­tures, and auto­mat­i­cally, con­tin­u­ously deploy your code to AppHarbor.

The actual sce­nario I had in mind is to be able to use that for deploy­ment of Open Source projects. AppHar­bor is fan­tas­tic, no-headache deploy­ment in the cloud, but Github is per­fect for keep­ing and devel­op­ing your code in the open, in social way. To have the cake and eat it too, Con­nec­tor was born.

Connector

I hope you find it use­ful. it is free, use-at-your-own-risk-and-don’t-sue-me-if-something-breaks soft­ware. There’s still some work to be done, feature-wise and a whole lot of pol­ish­ing but I decided to announce it early and get early feed­back. If you have any sug­ges­tions, ideas or (gulp) bugs, let me know!

link: http://connector.apphb.com/

Hope that helps.

Windsor 3 beta 1 – dozen of Nuget packages and SymbolSource.org support

September 4th, 2011 No comments

As promised, I released Nuget pack­ages for beta 1 of Wind­sor 3. This is my first major roll­out of Nuget pack­ages, so please report any issues work­ing with them.

Nuget and beta packages

Nuget is quickly evolv­ing and get­ting more use­ful with each release. How­ever one fea­ture it’s miss­ing right now is sup­port for pre-release pack­ages (this is com­ing in the next ver­sion).

davidebbo

This is not really a big deal, how­ever it means there are a few things you should be aware of.

Rec­om­mended version

Since the new pack­age is a pre-release, while I would really like for every­one to start using it imme­di­ately and report all issues they find, I quite under­stand that many peo­ple will rather pre­fer to stick to the last offi­cial ver­sion for the time being. To accom­mo­date that the new pack­ages are not made rec­om­mended ver­sions, so your Nuget explorer will still point to the last sta­ble (2.5.3) ver­sion if you search for Wind­sor, Castle.Core or any other pre-existing package.

nuget_explorer 

If you go to com­mand line and install one of the pack­ages with­out spec­i­fy­ing ver­sion num­ber, it will install the lat­est, that is beta 1 version.

nuget_commandline

SymbolSource.org and debug­ging into Windsor

Folks at SymbolSource.org added recently sup­port for Nuget (and Open­Wrap as well) and the new Cas­tle pack­ages take advan­tage of that. What it gives you, is you can now eas­ily debug into Windsor’s code, just like .NET frame­work ref­er­ence source (there’s a sim­ple guide at Sym­bol­Source on how to do it).

After you’re all set you can step into any of Cas­tle meth­ods in your debug­ger and watch the magic hap­pen. Very cool thing, even if I say so myself.

windsor-source-debugging

 

List of packages

Here’s the full list of v3 beta 1 pack­ages (notice those are not all Cas­tle pack­ages, just those that were pub­lished as v3 beta 1 roll­out of Windsor):

 

I hope this will make it eas­ier for every­one to test drive Wind­sor. And if you find any issues, have any sug­ges­tions or ideas, do not hes­i­tate to bring them up, either on our google group, or issue tracker.

Simple guide to running Git server on Windows, in local network (kind of)

August 20th, 2011 2 Comments

Last year I found myself in a sud­den and quick need to set up work­ing envi­ron­ment for a team of four, and as I like Git very much, I wanted to use it as our VCS. The prob­lem was, we weren’t allowed to use any third party provider, so GitHub was off the table. As I searched the Inter­net there were a few guides to set up team Git envi­ron­ment on Win­dows, but they all seemed very com­pli­cated and time con­sum­ing. For our mod­est needs we exper­i­mented a lit­tle and came up with a solu­tion that was very sim­ple, didn’t require any addi­tional soft­ware to be installed any­where and worked like a charm.

Recently I used it again on my cur­rent engage­ment, and one of my col­leagues sug­gested I should blog it, so here goes.

Ready, steady, go

The guide assumes you already have your local Git set up. For that, there are plenty of resources on the Inter­net, includ­ing my own blog­post about Win­dows Git tool­ing.

The entire tricks works like this – expose folder con­tain­ing your shared Git repos­i­tory as Win­dows net­work share.

Step one – bare git repository

There are two twists to the entire solu­tion – one of them is – your shared repos­i­tory needs to be ini­tial­ized with –bare flag.

git_bare_repository

Step two – Win­dows share

Sec­ond step is to expose the folder with our newly cre­ated repos­i­tory on the Win­dows share. You also use your stan­dard Win­dows mech­a­nisms to con­trol and limit access to the folder (make sure you give the devel­op­ers write access!).

Step three – Map the share as net­work drive

This step is per­haps not exactly nec­es­sary but I couldn’t get it to work oth­er­wise, so here comes the sec­ond twist. In order for your devel­op­ers to be able to access the shared folder via Git they need to map it as net­work drive.

sshot-10

Step four – Add remote repos­i­tory in Git and code away

Last step is the stan­dard Git pro­ce­dure – every devel­oper on your team needs to add the repos­i­tory sit­ting under their newly cre­ated net­work drive as remote. Notice the use of “file:///” pre­fix in front of the mapped drive name.

sshot-11

Step five

That’s all. I hope you find it use­ful, and if you know a way to elim­i­nate step three, let me know in the comments.

Windsor 3 beta 1 is released (along with other goodies)

August 15th, 2011 7 Comments

The title says it all. If you can’t wait grab the bina­ries here (Wind­sor with Cas­tle Core and facil­i­ties) and here (just Core). Nuget pack­age will hope­fully fol­low soon.

What’s in it?

This is a major release and there’s quite a lot of new fea­tures, as well as some sig­nif­i­cant changes under the cov­ers. There’s a high level overview of high­lights for the release in the wiki, so please have a look there. More detailed changelog, and list of break­ing changes is avail­able as part of the package.

Remem­ber it’s a beta release. Doc­u­men­ta­tion and sam­ples are still being updated and some fea­tures are not yet imple­mented or not fully baked. How­ever it is very impor­tant that you don't wait for the final release to upgrade, so that we can find and fix all the issues before final release. I'm not ask­ing you to use it in pro­duc­tion, but I'd really appre­ci­ate if you'd take the time to branch your apps, try to upgrade, run your unit tests, play with new ver­sion, and report any issues you may find. And ask your col­leagues, friends and ran­dom peo­ple on the street to do the same!

And if you find any issues, do report them.

Have fun and happy cod­ing,
I hope you like it

What's new in Windsor 3: Container debugger diagnostics improvements

April 25th, 2011 3 Comments

As we're near­ing the release date of Cas­tle Wind­sor 3.0 (code­name Wawel) I will be blog­ging about some of the new fea­tures and improve­ments intro­duced in the new version.

In the pre­vi­ous post I intro­duced one new diag­nos­tic, and in this post we’ll explore other improve­ments in this area.

Overview

In the screen­shot below (and all other) the upper win­dow is Wind­sor 2.5, lower win­dow is Wind­sor 3. All screen­shots were taken run­ning one of open source applications.

image

As you can see there are some addi­tional diag­nos­tics present in the new ver­sion. Alto­gether the num­ber rose from 4 in pre­vi­ous ver­sion to 7 in Wawel (you’re not see­ing all of them in the screen­shots above because some of them only acti­vate if they have some­thing to show). The new ones are:

  • Default com­po­nent per ser­vice – if you have mul­ti­ple com­po­nents expos­ing one ser­vice this will show you which one of them is the default (that is which one will be used pri­mar­ily to sat­isfy depen­den­cies of that type).
  • Poten­tial Ser­vice Loca­tor usage was dis­cussed pre­vi­ously

Objects tracked by release policy

image

This one is pretty self explana­tory. It shows you all objects tracked by release pol­icy in your con­tainer, grouped by com­po­nent. Do not under­es­ti­mate the value of it. This is a fan­tas­tic tool for locat­ing objects with mis­man­aged life­time (in other words – objects that should have been released but weren’t). If you see a num­ber next to any of your com­po­nents is sus­pi­ciously high or ris­ing you may have just dis­cov­ered a flaw in life­time man­age­ment in your app.

It is worth not­ing that there were some sig­nif­i­cant changes around release poli­cies in Wind­sor 3 and what is tracked by the pol­icy has changed as well. Those changes will be cov­ered in a future post.

Com­po­nents view

Most of the debug­ger views deals with show­ing com­po­nents and there are some improve­ments in this area. Let’s go through most notable of them.

image

  • Top level view no longer shows a sequence num­ber as “Name”. The num­ber had no real mean­ing and we’re show­ing instead a much more impor­tant infor­ma­tion – lifestyle of the component.
  • If lifestyle was not set explic­itly (and Wind­sor falls back to its default for it) there will be an addi­tional star (*) next to the lifestyle, like the “Now” com­po­nent on the screenshot.
  • How we dis­play the com­po­nent was also greatly sim­pli­fied to make it much more readable.
    • We’re not show­ing the name Windsor’s using for the com­po­nent, unless you explic­itly set it. Oth­er­wise it’s just noise.
    • We’re show­ing C#-ified names of types so that they are much eas­ier to read.
    • To show open generic ser­vices we put dots (·) around generic para­me­ters, so that they stand out from nor­mal types.

Sev­eral other more minor improve­ments were intro­duced as well, but I won’t go into too much detail here.

Access­ing diag­nos­tics in code

Ever since the fea­ture was intro­duced there were requests to pro­vide pro­gram­ma­ble access to those diag­nos­tics. It is now pos­si­ble. Thanks to changes in inter­nal infra­struc­ture you can use new IDi­ag­nos­tic<> inter­face (and it’s subin­ter­faces) to write code like this:

var host = Container.Kernel.GetSubSystem(SubSystemConstants.DiagnosticsKey) as IDiagnosticsHost;
var diagnostic = host.GetDiagnostic<IUsingContainerAsServiceLocatorDiagnostic>();
var serviceLocators = diagnostic.Inspect();
Assert.IsEmpty(serviceLocators);

I hope you’ll find all of those improve­ments useful.