Search And Destroy

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

Archive for the ‘Property Based Testing’ Category

And Broken Guitar Strings

Posted by kilfour on April 19, 2011

Recently I had to write a rather tricky data migration.
Everything got developed tdd style and coverage was almost a 100%.

But it failed in the wild.

Trying to write unit tests in order to smoke out all the edge cases wasn’t working.
Looking up the culprit record (in a huge dbase IV db), tracing down all the relations and trying to recreate the arrange part was a pain.

So I tried a different approach.
I took me some effort to write a property based test (and even more effort in order to produce the ‘SimplestPossibleFailCase’), but once that was done the test pointed out each and every bug out to me with impunity.

Writing a unit test reproducing the bug after seeing it once, was trivial.

Fixing the bug, once it was identified, also, … trivial.

That always makes me happy, … hurray, …

Posted in Property Based Testing | Leave a Comment »

Real Bleeding Fingers …

Posted by kilfour on April 19, 2011

I started working on a new project, earlier this week.

It is very similar to the one I was involved with when I first came up with quicknet.

Even though there’s not that much (reusable) code to show for my bleeding fingers, learning and implementing property based testing techniques, has improved the quality of my work.

I reckon this project will allow me to consolidate some of ‘this code/these techniques’ into quickdotnetcheck.

Posted in Property Based Testing | Leave a Comment »

When to Use Generated Data ?

Posted by kilfour on March 23, 2011

– In unit tests to avoid repetitive builder code.
– In integration tests, where setting a convention is often easier than building a domain.
– During (automated) performance testing.
– During a spike, or even, … during a (frowned upon) debugging session.
– To (very) quickly demo an application.
It is a prerequisite for property based testing.
– …

I think that about 25% of my tests these days _depend_ on quickgenerate.
And there’s another 25% where I use it, just because it helps out.

Then there’s still fifty percent of the tests where you really don’t need generated data.
Using quickgenerate there, apart from a quick ‘Generate.One()’, is usually not a good idea.

Posted in Property Based Testing, Rants | Leave a Comment »

QuickGenerate Tests : Part II

Posted by kilfour on February 23, 2011

As I said in previous post : ‘reasonably painless’.

When I first decided to write a quickdotnetcheck test for quickgenerate, I figured I’d test something where I smelled something fishy going on.

In the code posted before, notice how the OneToMany declarations have a minimum value of 1.

The test I first wrote initialized this to zero and, ‘lo and behold’, the spec failed.

Well, actually the entire thing just went kaboom, which is why I didn’t post the results in the first place ;-) .

Still, this simple idea (property based testing), exposed a bug that I wasn’t able to smoke out using unit tests.
Because I hadn’t written a use case for an empty one to many.
Because I didn’t think about it.
Because I didn’t have enough time to switch hats maybe (KB), or whatever.

And probably, yes, I should have thought about all this when I wrote the unit tests.

But I didn’t.

Writing the spec really required me to put on the testing hat.
And testing for an empty list is an obvious case when you’re wearing the right hat.

Posted in Checking Stuff Out, Property Based Testing, Rants | Leave a Comment »

QuickGenerate Tests : Part I

Posted by kilfour on February 23, 2011

I used to have some QuickNet tests in there, but I removed them during a serious refactoring.
It was just easier to unit test stuff, after moving quickgenerate out of quicknet.

As a consequence most of the features recently developed are unit tested.

And today I have arrived at the point where the unit tests are starting to bug me.

Because of the nature of quickgenerate, interactions are very important.
I now have a test case for ‘almost’ every feature of the domain generator, but everytime I release it into the wild, I still have to write some new tests in order to solve bugs.
Bugs which arise mainly because of interactions between the different classes/methods.

Test maintainability is becoming a nightmare.
Not as much as so, as when maintaining something untested, … by several miles, … but still.
There’s even not that many tests in quickgenerate yet, and at the moment it is all still quite managable.

But then again, I do get annoyed quite easily.

So I tried quickdotnetcheck :

public class OneToManyTests : Fixture
{
    private readonly Type[] entities = FromAssembly.Containing<ILevel>().Implementing<ILevel>();
    private DomainGenerator domainGenerator;
    private ILevel result;
    private Func<ILevel> action;

    protected override void Arrange()
    {
        domainGenerator =
            new DomainGenerator()
            .Entities(entities)
            .OneToMany<LevelOne, LevelTwo>(1, 10, (one, many) => { one.NextLevel.Add(many); many.Parent = one; })
            .OneToMany<LevelTwo, LevelThree>(1, 10, (one, many) => { one.NextLevel.Add(many); many.Parent = one; });
        
        action =
            new Func<ILevel>[]
                {
                    () => domainGenerator.One<LevelOne>(),
                    () => domainGenerator.One<LevelTwo>(),
                    () => domainGenerator.One<LevelThree>()
                }.PickOne();
    }

    protected override void Act()
    {
        result = action();
    }

    [Fact]
    public void VerifyAllSpecs()
    {
        new Suite(100, 10)
            .Register(() => new OneToManyTests())
            .Run();
    }

    [Spec]
    public void TotalNumberOfThingsInHierarchy_Equals_NumberOfGeneratedObjects()
    {
        Ensure.Equal(GetTotalNumberOfThingsInHierarchy(), domainGenerator.GeneratedObjects.Count());
    } 
}

Reasonably painless.

Posted in Checking Stuff Out, Property Based Testing, QuickDotNetCheck | Leave a Comment »

On What’s On My Mind, Reflections II

Posted by kilfour on November 22, 2010

Just as with unit-testing, property-based-testing is much easier if you start doing it from the word go and keep it up all the way through.

Posted in Property Based Testing, Rants | Leave a Comment »

Mr. Bad Example

Posted by kilfour on December 27, 2009

System under test :

public class BugHouse
{
    private int count;
    public bool Run(int a)
    {
        if (count++ >= 3 && a == 6)
            throw new Exception();
        return true;
    }
}

The AcidTest :
public class UsingGenerator : AcidTest
{
    static BugHouse bugHouse;
    public override void Setup()
    {
        bugHouse = new BugHouse();
    }

    class BugRun : MetaTransition<int, bool>
    {
        public BugRun()
        {
            Generator = new IntGenerator(0, 20);
            Execute = input => bugHouse.Run(input);
        }
    }

    [SpecFor(typeof(BugRun))]
    public Spec ShrinksIrrelevantInput(int input, bool output)
    {
        return new Spec(() => Ensure.True(output));
    }
}

The Output :
—— Test started: Assembly: QuickNet.Example.dll ——

TestCase ‘BugRun ShrinksIrrelevantInput’ failed: System.Exception : Exception of type ‘System.Exception’ was thrown.
D:\DotNetDev\QN\QuickNet.Example\SimpleTransitionShrinking.cs(16,0): at QuickNet.Example.BugHouse.Run(Int32 a)
D:\DotNetDev\QN\QuickNet.Example\SimpleTransitionShrinking.cs(58,0): at QuickNet.Example.UsingGenerator.BugRun.b__3(Int32 input)
D:\DotNetDev\QN\QuickNet\Transition.cs(55,0): at QuickNet.Transition`2.PerformTransition(TestRunReport report)

Output from BugRun ShrinksIrrelevantInput:
———————————————————-
BugRun ShrinksIrrelevantInput
Falsifiable after 1 test(s), 40 Transition(s).
——————–Simplest Fail Case——————–
Transition : BugRun, Output : True
Transition : BugRun, Output : True
Transition : BugRun, Output : True
Transition : BugRun, Output : True
6
———————————————————-

Posted in Property Based Testing, QuickNet | 2 Comments »

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 »

Hush, Little Baby, Don’t Say a Word

Posted by kilfour on November 20, 2009

I’ve been using QuickNet at work lately. Almost always to reduce the amount of repetitive code tests.
We make pretty heavy use of Rhino.Mocks in our tests. Unfortunately the code is not in the best of shape, so sometimes test setup, defining stubs, expectations, etc… is quite a lot of work. Yesterday I wrote a test that asserts a domain object to dto transformation. After coding the first simplest case I already had a lot of tests. Thinking about the corner-cases I still needed to code, being a bit of a lazy person, I got disheartened and decided to see if quicknet could help me out here.
“I’m a pretty lazy person, and am prepared to work quite hard in order to avoid work.” – Martin Fowler
So I translated the tests I allready had, and stumbled onto a happy accident :

[SpecFor(typeof(FromDomainObjectToDto))]
public Spec WithProduct(Offer offer, OfferDto dto)
{
    return new Spec(
        () => repository.VerifyAllExpectations())
        .If(() => offer.Product != null)
        .DoBefore(
        () =>
        {
            repository = MockRepository.GenerateMock<IProductRepository>();
            repository
                .Expect(r => r.GetAvailabilityDatesForProduct(offer.Product.Id))
                .Return(listOfAvailabilityDates);
            mapper = new OfferMapper(repository);
        });
}

[SpecFor(typeof(FromDomainObjectToDto))]
public Spec NoProduct(Offer offer, OfferDto dto)
{
    return new Spec(
        () => repository.VerifyAllExpectations())
        .If(() => offer.Product == null)
        .DoBefore(
        () =>
        {
            repository = MockRepository.GenerateMock<IProductRepository>();
            repository
                .Expect(r => r.GetDefaultProductAvailabilityDates())
                .Return(listOfDefaultAvailabilityDates);
            mapper = new OfferMapper(repository);
        });
}

Here’s the kind of transition I was working on :

class FromDomainObjectToDto : MetaTransition<Offer, OfferDto>
{
    public FromDomainObjectToDto()
    {
        Generator = new OfferGenerator();
        Execute = input => mapper.FromDomainObjectToDto(input);
    }
}

Posted in Property Based Testing, QuickNet | 2 Comments »

Logging In

Posted by kilfour on November 2, 2009

After coding the AcidTest and it’s accompanying Alchemist, integration with xunit.net pretty much worked. I’d still rather see the Specs in the GuiRunner, and thus being able to select which ones to Ensure, instead of looking at the VerifyAll Fact-decorated method, but this is a minor gripe compared to the gained benefits regarding readability.

I then sat down and thought about creating some examples that are slightly closer to real life than the Calculator toy example, without having to post production code or having to write a complicated model.
I looked around the net and came up with two candidates.

The first is based on a blogpost by ‘a former co-worker of mine’.
Davy mentioned he was going to post about these tests himself, so I’m going to let the more unbiased party go first on this one. Except I’d like to say that multi-threaded testing is something that should be supported by quicknet itself, and in hacky sort of way, it allready does.

The second example is based on this post by Ayende.
QuickNet started out as an integration test framework, and is not aimed at unit testing. It would be nice if it were usable for TDD, but it has not been a main goal. The kind of tests proposed in above article, looked quite familiar though.
A Scenario could be regarded as a couple of Transitions, the Scenario executer is the QuickNet.TestRun, Test model is the AcidTest derived class and Test code itself : the SpecFor methods.
Something else which I found interesting was the argument raised by Frans Bouma, saying that using the scenario based technique, you are only sure that your application works for the specific scenarios you’ve tested for.

As an acid test for the moment needs to have the transitions defined as nested classes, I took the easy approach and seperated Test model, and Test Code by putting it in different files and using a partial class. If this syntax sticks, it will be formalized, but for now, bear with me.

public partial class LoggingInSpecs
{
    private static IAuthenticationStore doorman;
    private static LoginModel model;

    private const string UserId = "my-user";
    private const string CorrectPassword = "this will get you in";

    private static User user;
    private static bool userLoggedOn;

    int badLoginCount = 0;

    public LoggingInSpecs() : base(100, 5) { }

    public override void SetUp()
    {
        SystemTime.Now = () => new DateTime(2000, 10, 10);
        doorman = MockRepository.GenerateStub<IAuthenticationStore>();
        doorman.Stub(s => s.VerifyPassword(UserId, CorrectPassword))
            .Return(true)
            .WhenCalled(s => userLoggedOn = true);

        model = new LoginModel(doorman);
        user = new User { UserId = UserId };
        userLoggedOn = false;
    }
}

The doorman is mocked as I didn’t feel like writing a full app for this. The LoginModel is actually the system under test. There’s a couple of sugaring methods like LoginWasSuccessFull, LoginFailed, not shown above, that pretty much just use the private members to expose state to the Specs.
Only one transition in this test :
class Login : MetaTransition<string, Unit>
{
    public Login()
    {
        Generator = new PassWordGenerator();
        Execute =
            input =>
            {
                user.Password = input;
                model.Login(user);
                return null;
            };
    }
}

Input is the password, randomly chosen, it can be good or bad.

That’s our context set up, now, lets have a look at the Specs :

public partial class LoggingInSpecs : AcidTest
{
    [SpecFor(typeof(Login))]
    public Spec WillUpdateLoginDateOnSuccessfulLogin(string input, Unit output)
    {
        return new Spec(
            () => Ensure.AreEqual(SystemTime.Now(), user.LastLogin),
            LoginWasSuccessFull);
    }

    [SpecFor(typeof(Login))]
    public Spec WillNotUpdateLoginDateOnFailedLogin(string input, Unit output)
    {
        return new Spec(
            () => Ensure.AreNotEqual(SystemTime.Now(), user.LastLogin),
            LoginFailed);
    }

    [SpecFor(typeof(Login))]
    public Spec WillUpdateBadLoginCountOnFailedLogin(string input, Unit output)
    {
        return new Spec(
            RememberBadLoginCountBeforeLoggingIn,
            () => Ensure.AreEqual(badLoginCount + 1, user.BadLoginCount),
            LoginFailed);
    }

    [SpecFor(typeof(Login))]
    public Spec WillAuthenticateUserOnSuccessfulLogin(string input, Unit output)
    {
        return new Spec(
            () => Ensure.IsTrue(user.IsAuthenticated),
            LoginWasSuccessFull);
    }

    [SpecFor(typeof(Login))]
    public Spec WillNotAuthenticateUserWithBadLoginCountOfThreeOrHigher(string input, Unit output)
    {
        return new Spec(
            () => user.BadLoginCount >= 3,
            () => Ensure.IsFalse(user.IsAuthenticated));
    }
}

Using this approach we are testing a lot of scenario’s as they are randomly generated. Data aswell is randomly generated.
The syntax on spec definition could be improved, we’re thinking fluent interface builder…

Posted in Property Based Testing, QuickNet | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.