Search And Destroy

Look out honey, ’cause I’m using technology!

Archive for the ‘Agatha’ Category

QuickNet : State of the Assembly

Posted by kilfour on June 16, 2010

Honestly, … I haven’t used QuickNet in a while.

I’ve been involved with some new projects in the last couple of months.
All of them started out Test-Driven. So I’ve been putting my efforts into unit testing patterns more than in the property-based stuff.

The source in the trunk should be pretty stable though, and I reckon it is already a huge improvement over the 0.5 release.
And ofcourse the generators have undergone a serious face-lift.

The latter brings me to the reason why there isn’t any QuickNet.Generators.Example solution yet.

There are issues with the generators (most of which have been hacked around).
And everytime I sit down and think about a solution to any issue I have with the generators, the simplest thing that could possibly work seems to be Inversion of Control.

As I’ve stated previously I reckon IoC and currying, address the same problem. And although the implementations are vastly different, the solutions are similar.
Haskell’s QuickCheck generators work magically, out of the box, plugging in random values of the correct type in the functions under test. Currying ( amongst a lot of other things) makes this possible.
I’ve been trying to achieve the same ease of use.
The code however, is not getting any prettier with each corner-case I discover, or each feature added.

And everytime I sit down and think about a solution to all this, the simplest thing that could possibly work seems to be Inversion of Control.

Also, …
I’m moving house, my dog died, I lost my drivers license, my girlfriend wants to have a sex-change operation, I’m stuck in rehab, my boss asked me to develop the DoomsDay.Device.Core library, I have to get my car fixed, I’m inbetween jobs,… excuses, excuses, ….

I do need to get my hands on a VS2010 urgently though, as Agatha has already migrated, and I haven’t been able to update the (last-time-I-looked) flawed QN-tests.

And as the Agatha community has been contributing features and accompanying unit tests, I am anxious in seeing how I could translate this into QN-tests… and hopefully uncover a bug or two ;-)

Posted in Agatha, QuickNet | Leave a Comment »

Agatha in Action

Posted by kilfour on May 1, 2010

public class ImportPresenter : Presenter<IImportView>, IImportPresenter
{
    public ImportPresenter(IImportView view) 
        : base(view) { }

    protected override void RegisterEventHandlers()
    {
        View.Loaded +=
            (s, e) => View.Populate(GetImportData());

        View.ProductValidated +=
            (s, e) => SendValidateProductRequest(EventArg.Parameter<long>(e));

        View.ProductInvalidated +=
            (s, e) => SendInvalidateProductRequest(EventArg.Parameter<long>(e));

        View.ValidationApplied +=
            (s, e) => View.Populate(ApplyValidation());
    }

    private ImportDto GetImportData()
    {
        return
            DispatcherFactory
                .CreateRequestDispatcher()
                .Get<GetImportDatatResponse>(new GetImportDataRequest()).Import;
    }

    private void SendValidateProductRequest(long productId)
    {
        var dispatcher = AsyncDispatcherFactory.CreateAsyncRequestDispatcher();
        dispatcher.Add(new ValidateProductRequest {ProductId = productId});
        dispatcher.ProcessRequests(
            response => { },
            exceptionInfo => { throw new InvalidOperationException(exceptionInfo.Message); });
    }

    private void SendInvalidateProductRequest(long productId)
    {
        var dispatcher = AsyncDispatcherFactory.CreateAsyncRequestDispatcher();
        dispatcher.Add(new InvalidateProductRequest { ProductId = productId });
        dispatcher.ProcessRequests(
            response => { },
            exceptionInfo => { throw new InvalidOperationException(exceptionInfo.Message); });
    }

    private ImportDto ApplyValidation()
    {
        return
            DispatcherFactory
                .CreateRequestDispatcher()
                .Get<ApplyValidationResponse>(new ApplyValidationRequest()).Import;
    }
}

Posted in Agatha, C# Musings | Leave a Comment »

Why Didn’t They Ask Evans?

Posted by kilfour on February 4, 2010

I haven’t been blogging a lot lately, and have not mentioned QuickNet recently.
Work has continued though. But as it’s still all quite experimental I’m reluctant to share it with the world.

Some QuickPreviews :
Me like this :

[Using(typeof(Login))]
[Using(typeof(Logout))]
public class NavigateSpecs : AcidTest<SecuredNavigatorState>
{
    public NavigateSpecs() : base(50, 10) { }

    [SpecFor(typeof(Navigate))]
    public Spec ThrowsSecurityExceptionIfUserIsNotLoggedOn(string input, IResource output)
    {
        return
            new Spec()
            .If(State.UserIsNotLoggedOn)
            .Throws<SecurityException>();
    }

    [SpecFor(typeof(Navigate))]
    public Spec ReturnsAResourceIfUserIsLoggedOn(string input, IResource output)
    {
        return
            new Spec(() => Ensure.NotNull(output))
            .If(State.UserIsLoggedOn);
    }
}

This is a rewrite of the example found on google code downloads. It defines specs on the navigate transition while still ‘using’ the login and logout transitions to get to certain states.

Also Agatha and QuickNet really play nice when it boils down to writing integration tests.
f.i. :
for the transition :

public class PrepareForGenerateOrderTransition : MetaTransition<PrepareForGenerateOrderRequest, PrepareForGenerateOrderResponse, State>
{
    public PrepareForGenerateOrderTransition(State state)
    {
        Precondition = () => state.Current == (state.Current & (States.Editing));
        GenerateInput = () => new PrepareForGenerateOrderRequest {Offer = state.OfferDto};
        Execute =
            i =>
            {
                var response = state.Dispatcher().Get<PrepareForGenerateOrderResponse>(i);
                state.Current = States.InGenerateOrder;
                state.OfferDto = response.Offer;
                return response;
            };
    }
}

And then the spec :
[SpecFor(typeof(PrepareForGenerateOrderTransition))]
public Spec PrepareForGenerateOrderNoException(PrepareForGenerateOrderRequest input, PrepareForGenerateOrderResponse output)
{
    return new Spec(() => Ensure.Null(output.Exception))
        .If(() => input.Offer.CurrentSalesRep2ID > 0);
}

This is the result :
TestCase 'PrepareForGenerateOrderTransition PrepareForGenerateOrderNoException'
failed: QuickNet.FalsifiableException : 
Expected : null.
Actual : An ExceptionInfo whose value is:
BusinessException: Line #1 in the offer has no edition yet.
   at ...
Output from PrepareForGenerateOrderTransition PrepareForGenerateOrderNoException:
  ----------------------------------------------------------
  PrepareForGenerateOrderTransition PrepareForGenerateOrderNoException
  Falsifiable after 6 test(s), 3 Transition(s).
  --------------------Simplest Fail Case--------------------
  1 : Transition : NewOfferTransition, Output : GetNewOfferResponse
  GetNewOfferRequest
  2 : Transition : PrepareForGenerateOrderTransition, Output : PrepareForGenerateOrderResponse
  PrepareForGenerateOrderRequest
  ----------------------------------------------------------

0 passed, 1 failed, 0 skipped, took 17,03 seconds.

As I said experimental, the bit operations will be abstracted f.i.

Posted in Agatha, QuickNet | Leave a Comment »

One, Two, Buckle My Shoe

Posted by kilfour on January 19, 2010

I’m currently on one of those projects that seem to have taken the coding guidelines from the paper I linked to in this post.

It started out as a web app, where most of the logic, including hard-baked sql statements was found in the aspx files. A rewrite was ordered by the customer. They also decide to go for a winforms application this time. Mainly for performance reasons, which I think are the wrong reasons, but…

So now we have a fat client. I did follow a lot of the well known patterns, including a service layer translating from business objects to dto’s and passing them on to the Gui, and back again. Every once in a while a reference to the business layer popped up in the frontend project though.

So a while ago when Agatha started supporting an In-Process service layer, I introduced requests, responses and handlers. These days almost all of the service layer is implemented using Agatha. With a funny side-effect : when things go smoothly the devs talk about their handlers and when things go wrong they talk about my dispatcher. Still trying to explain the concept of CollectiveCodeOwnership. ;-)

Now there was one thing which the web app handled far more easily than the win app : the uploading of files to a server. The webapp was deployed on the server where the files needed to be, so it could just drop the uploaded files in the destination folder. Doing this in the winapp we would have to resort to some kind of ftp stuff, which means setting up a site, managing users from different domains or impersonating, etc…

So I figured I’d try to write an Upload WCF Service. The idea is to seperate the service layer from the frontend at some point in the future, so this service would also serve as a spike to see if this migration could be done incrementally.

Writing the Agatha handler was pretty easy.
Setting up the service in IIS was a breeze.
Getting the client configured was a bit tricky as there’s no example on how to have two Dispatchers (one in-process and one using a proxy) in the Agatha project and up untill now I had only used out-of-the-box configuration features. But it did not take too long to figure it out.

I’m not entirely sure if this the preferred way of doing this, but this is how it currently works for me :

After doing the normal configuration in the client I added the following :

public interface IUploadServiceRequestProcessor : IAsyncRequestProcessor{}
public class UploadServiceRequestProcessor 
	: AsyncRequestProcessorProxy, IUploadServiceRequestProcessor
{
}

public interface IUploadServiceRequestDispatcher : IAsyncRequestDispatcher{}
public class UploadServiceRequestDispatcher 
	: AsyncRequestDispatcher, IUploadServiceRequestDispatcher
{
    public UploadServiceRequestDispatcher(IUploadServiceRequestProcessor requestProcessor) 
    	: base(requestProcessor) { }
}

And then just added those to my container :

Common.IoC.Container.Register(
    Component.For<IUploadServiceRequestProcessor>()
        .ImplementedBy<UploadServiceRequestProcessor>()
        .LifeStyle.Transient);

Common.IoC.Container.Register(
    Component.For<IUploadServiceRequestDispatcher>()
        .ImplementedBy<UploadServiceRequestDispatcher>()
        .LifeStyle.Transient);

Now resolving IRequestDispatcher gets me the in process one, and resolving IUploadServiceRequestDispatcher gets me the WCF one.

And as an added bonus migrating one of the handlers from the one service layer to the other, means moving it from one project to another and changing the dispatcher in the client. Pretty easy, so it looks like we can do aforementioned migration incrementally :-) .

Posted in Agatha, C# Musings | 1 Comment »

You Were Just a Painted Face on a Trip Down to Suicide Road

Posted by kilfour on January 13, 2010

I just refactored the Agatha RequestProcessorTest.ExceptionHandling AcidTest to take advantage of the new QuickNet features and it is throwing a failure.

This might be a bug in QuickNet.
This might be an erroneous spec definition.
This might be a bug in Agatha.

I’m hoping for the latter ;-) .

I added the new features in order to deal with problems I face in a production environment.
Agatha, however, is a totally different thing. We’re testing a framework/lib, not an app.
Apart from the fact that definitely something is going wrong somewhere, this test clearly exposes some weaknesses of the newly implemented features.
F.i. :
– Shrinking does not seem to produce the minimal fail case.
– Reporting is too confusing.

I will have to fix this first in order to be able to determine whether the bug is in QuickNet, in Agatha, or in the spec definition.

And that, my friends, gets me all excited.

Posted in Agatha, Hey Man Now You're Really Living, QuickNet | Leave a Comment »

The Murder Mistery

Posted by kilfour on December 12, 2009

A short while ago Davy Brion posted the first Agatha QuickNet tests.
The first version was the initial attempt, the second a refactoring. There’s a small difference in philosophy between both versions.
I was quite curious about the comments on these pieces of code for obvious reasons, but not a lot of them were forthcoming.
One of the main reasons for this is IMO this one :
Too much magic for my taste. I don’t understand any of those tests / specifications.

So let’s remedy that and walk you through another Agatha test.

The RequestProcessor test.

It asserts the way Agatha’s default serverside IRequestProcessor implementation deals with exceptions that could be thrown by the IRequestHandler implementations it calls.

Setup and context for the Agatha tests are quite complicated and QuickNet could surely do with a bit of work on this issue, but here goes :

First I coded some concrete implementations of a Request and Response and declared a handler interface.

public class FirstRequest : Request { }
public class FirstResponse : Response { }
private static IRequestHandler<FirstRequest> handlerForFirstRequest;

There’s actually three of these in the code. A way to make this more dynamic needs to be devised. This probably means adding an assembly to the solution specifically for containing test data.
private static IRequestProcessor requestProcessor;
private static ServiceLayerConfiguration serviceLayerConfiguration;

The IRequestProcessor is our system under test and it takes a ServiceLayerConfiguration in it’s constructor. The RequestProcessor uses the serviceLayerConfiguration to determine which type of exception is the Business exception and which type of exception is the Security exception.
public RequestProcessorSpecs() : base(10, 20) { }

The test’s constructor. This means it will run two hundred tests. In QuickNet terms : ten tests, containing twenty transitions each. As you’ll see later there’s only one transition ‘RequestProcessor.Process()’ in this fixture. So the alchemist calls the Setup function (see below) and then executes the transition twenty times. It then calls setup again, reinitializing state, etc… It does this ten times as defined by the first int parameter in the constructor.
public override void SetUp()
{
    IoC.Container = new Agatha.Castle.Container();

    serviceLayerConfiguration = MockRepository.GenerateStub<ServiceLayerConfiguration>(null, null, IoC.Container);
    serviceLayerConfiguration.BusinessExceptionType = typeof (BusinessException);
    serviceLayerConfiguration.SecurityExceptionType = typeof(SecurityException);

    requestProcessor = new RequestProcessor(serviceLayerConfiguration);

    handlerForFirstRequest = MockRepository.GenerateMock<IRequestHandler<FirstRequest>>();
    handlerForSecondRequest = MockRepository.GenerateMock<IRequestHandler<SecondRequest>>();
    handlerForThirdRequest = MockRepository.GenerateMock<IRequestHandler<ThirdRequest>>();

    IoC.Container.RegisterInstance(handlerForFirstRequest);
    IoC.Container.RegisterInstance(handlerForSecondRequest);
    IoC.Container.RegisterInstance(handlerForThirdRequest);
}

The test’s setup function initializes an IoC container as the RequestDispatcher uses this to resolve the RequestHandlers, the mocked RequestHandlers are then registered. ServiceLayerConfiguration is stubbed and we set BusinessExceptionType and SecurityExceptionType.
And ofcourse we instantiate the RequestProcessor.
public class BusinessException : Exception { }
public class SecurityException : Exception { }
public class UnknownException : Exception { }
public class AnotherUnknownException : Exception { }

private static List<Exception> exceptionsThrown;

Some context. We define some exceptions, two of which have been used in test setup, and we declare a list which we’ll use to store state.

Next there’s a bit of complicated code needed to define input, which needs to be refactored and will probably look a lot simpler if we go for above mentioned strategy of defining test data in another assembly. I’ll spare you that for now ;-) . I was having fun writing it though.
The important bit is the following :

IGenerator<Action<IList<Exception>>> actionGenerator =
    new ChoiceGenerator<Action<IList<Exception>>>(
        new Action<IList<Exception>>[]
            {
                list => list.Add(null),
                list =>
                    {
                        Exception exception = new BusinessException();
                        list.Add(exception);
                        throw exception;
                    },
                list =>
                    {
                        Exception exception = new SecurityException();
                        list.Add(exception);
                        throw exception;
                    },
                list =>
                    {
                        Exception exception = new UnknownException();
                        list.Add(exception);
                        throw exception;
                    },
                list =>
                    {
                        Exception exception = new AnotherUnknownException();
                        list.Add(exception);
                        throw exception;
                    }
            });

This generator randomly chooses one of the functions defined in the list so that the transition can plug it into the RequestHandler when it’s Handle function is called. As you can see there’s one that does nothing, one that throws an exception that is defined in the ServiceLayerConfiguration as a business exception, one that throws an exception that is defined in the ServiceLayerConfiguration as a security exception, and two that throw an unknown exception. These functions store the exception they throw (or null) in the test’s ‘context’, the exceptionsThrown list.
class Process : MetaTransition<ProcessInput, Response[]>
{
    public Process()
    {
        Generator = new ProcessInputGenerator();
        Execute = 
            input =>
                {
                    int ix = 0;
                    exceptionsThrown = new List<Exception>();
                    foreach (Type key in input.RequestsAndHandlers.Keys)
                    {
                        input.RequestsAndHandlers[key].StubIt(input.Actions[ix], exceptionsThrown);
                        ix++;
                    }
                    return requestProcessor.Process(input.Requests);
                };
    }
}

The transition, our function under test. The ProcessInputGenerator is responsible for jumbling the handler functions randomly into a list of RequestsAndHandlers which are part of the ProcessInput class. Before running the transition we clear the exceptionsThrown list and set the Rhino.Mocks stubs for each of the handler mocks. Here’s the function that does the latter and is part of afore-mentioned complicated bit :
public void StubIt(Action<IList<Exception>> action, IList<Exception> exceptionsThrown)
{
    RequestHandler
        .Stub<IRequestHandler>(r => r.Handle(Request))
        .Return(Response)
        .WhenCalled(arg => action(exceptionsThrown))
        .Repeat.Once();

    RequestHandler
        .Stub<IRequestHandler>(r => r.CreateDefaultResponse())
        .Return(Response)
        .Repeat.Once();
}

Now with all that setup we can finally start defining specs.

Here’s the first one, in case no exception is thrown by any of the handlers :

[SpecFor(typeof(Process))]
public Spec ProcessRequestsWithoutException(ProcessInput input, Response[] output)
{
    return new Spec(
        () => output.ForEach(
                  r => Ensure.Equal(ExceptionType.None, r.ExceptionType)))
        .IfAfter(() => !exceptionsThrown.Exists(e => e != null));
}

The IfAfter part is a ‘PostCondition’. This means the specs ‘Invariant’, defined in the constructor, is only evaluated if the postcondition holds. In this case it says that the exceptionsThrown list should only contain null values.
The invariant then Ensures that all Response instances in the output have their ExceptionType correctly set to ExceptionType.None.

[SpecFor(typeof(Process))]
public Spec ProcessRequestsWithBusinessException(ProcessInput input, Response[] output)
{
    Predicate<Exception> predicate = 
        exception => exception != null && exception.GetType() == typeof(BusinessException);

    return new Spec(
        () =>
            {
                int ix = exceptionsThrown.FindIndex(predicate);
                Ensure.Equal(ExceptionType.Business, output[ix].ExceptionType);

                Ensure.Equal(exceptionsThrown[ix].Message, output[ix].Exception.Message);
                Ensure.Equal(exceptionsThrown[ix].StackTrace, output[ix].Exception.StackTrace);
                Ensure.Equal("Tests.RequestProcessorSpecs+BusinessException", output[ix].Exception.Type);
            })
        .IfAfter(() => exceptionsThrown.Exists(predicate));
}

This spec only fires if any Handler threw a BusinessException, looks up which one was the first one and Ensures some stuff on the corresponding Response.

There’s a similar spec for a Security Exception and another two for the ‘unknown’ exceptions.
Finally here’s the spec that ensures that all responses after the failing one have ExceptionType EarlierRequestAlreadyFailed.

[SpecFor(typeof(Process))]
public Spec ProcessRequestsWithExceptionFailsAllFollowingRequests(ProcessInput input, Response[] output)
{
    Predicate<Exception> predicate =
        exception => exception != null;
    return new Spec(
        () =>
            {
                int ix = exceptionsThrown.FindIndex(predicate) + 1;
                for (int i = ix; i < output.Length; i++)
                {
                    Ensure.Equal(ExceptionType.EarlierRequestAlreadyFailed, output[ix].ExceptionType);

                    Ensure.Equal("EarlierRequestAlreadyFailed", output[ix].Exception.Message);
                    Ensure.Null(output[ix].Exception.StackTrace);
                    Ensure.Equal("System.Exception", output[ix].Exception.Type);
                }
            })
        .IfAfter(
        () =>    exceptionsThrown.FindIndex(predicate) >= 0
              && exceptionsThrown.FindIndex(predicate) >= exceptionsThrown.Count - 1); 
                 // excluding cases where only last request fails 
                 // as this wouldn't ensure anything but the spec would have been considered to hold
}

Conclusion :
I agree it’s not the easiest code to read (or write ;-) ), and that it might look like a lot of work, but there’s a bonus : Every possible combination of exceptions thrown is tested. I don’t have to think about all the possibillities, QuickNet does that. Now Agatha is pretty stateless, but even then, not completely, during a request (or batch thereof) there is state kept in the objects. Which is why in the second version of the tests in Davy’s post I modelled the Response.Error and Response.Result properties as different transitions. If there are bugs arising from keeping state in an incorrect fashion they will surface.
Also QuickNet specs are conclusive, unit tests aren’t. If I define a spec and there is a case in which it doesn’t hold, QuickNet will tell me and I would have to add a pre- or postcondition to make the spec pass. Makes things far more explicit, even though context and setup is harder to read.
And for you Code Coverage Fanatics out there, this type of testing easily gets that stat up to a hundred percent whereas using the unit testing approach I usually have to duplicate a lot of test code in order to get there.

Posted in Agatha, Property Based Testing, QuickNet | 3 Comments »

A Taste of Mistery

Posted by kilfour on December 9, 2009

Recently I got involved with the Agatha open-source project.

Mainly because the lead dev of it wanted to use QuickNet in order to test it.

I follow his blog and it looked like a promising lib. In the past I had to jump some of the hurdles dotnet distributed development throws at you, and almost always implemented a non-traditional solution in order to avoid them. The way Agatha handled this stuff seemed better (cleaner), and definitely more reusable than anything I had done.
The project I’m working on right now however is not a distributed app. So even though I have written a test for Agatha, up untill today I didn’t really have the time to get an actual implementation up and running.

So what’s changed ?

This.

My project gets audited by an external firm that the customer has hired specifically for this purpose. This is something some of my co-workers find a total nuisance, but I think getting a second opinion is almost always a pretty good idea. And in this case it has paid off.
I must admit that I almost always agree with their recommendations and that it has allowed me to introduce stuff, that without this external pressure would have been close to impossible.

Now, where using a very DDD-like approach (using our ‘service-layer’ as an anti-corruption layer ) and during the last code review one of the remarks that came back was : ‘Compile the interface definitions of your service-layer into a seperate dll so that it would become easier to switch from an in-process app to a distributed one.
I figured that even if we do that it would still be quite a task to migrate, and configure. Agatha promises (and as far as I can tell it delivers on this promise) an almost painless transition. So I decided to migrate our service layer to Agatha.

At first I just included the sample HelloWorld Request/Response into the project and tried to get it to compile and run.
It got that working in under five minutes.

As I was adding the first ‘real’ request, a translation of something that was allready there, it struck me that I didn’t have to configure the handler in the IoC container. I know it’s on the blog, and I’ve read it, but you only get to appreciate this once you’ve actually tried it.
My co-workers, most of whom had never even heard of an IoC container before, always forget about this and spend a lot of time trying to figure out what the hell is going on.

I remember once getting complaints from the guy sitting next to me, as his code compiled but he couldn’t start up the app. He forgot to register a new component in the service layer. As I pointed out the required line and explained why it needed to be there, he said : ‘What do you mean ? We actually have to type code to make this thing work?’. He was quite impressed with the way the IoC container handled things and removed a lot of infrastructure code, so that when he realized his mistake he started joking about the stuff you still had to pay attention too.

After implementing the first few Agatha handlers I turned to him and asked : ‘Do you remember your remark about having to register dependencies ?’.
He answered : ‘Yes, and because you ask I’m assuming we don’t have to do that anymore’.

That’s right. And it’s a time-saver.

When I read about this it looked good. After one day of using it, I’m impressed, … really impressed.

It doesn’t use a lot of fancy patterns, just some tried and tested basic OO stuff, and it forces you to abide by these rules.
And because you are using this, you end up thinking in a more OO way about the problem at hand, leading to far more cleaner code.

Need I say it again ?

I really like this lib.

Posted in Agatha, C# Musings | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.