It is a long time I did not post about simple Traffic Light experiment. I’ve ended with a super simple Domain with no Getters and no Setters, but there is still something I really do not like about that sample and it is represented by this test.

[Fact]
public void When_both_semaphore_are_red_one_become_green()
{

    //move all to yellow fixed
    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(1)))
    {
        sut.Tick();
    }
    _domainEvents.Clear();
    //now move again to both red
    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(10)))
    {
        sut.Tick();
    }
    _domainEvents.Should().Have.Count.EqualTo(2);
    _domainEvents.All(e => e.NewStatus == LightColor.Red).Should().Be.True();
    _domainEvents.Clear();
    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(1)))
    {
        sut.Tick();
    }
    //only one semaphore should be go to green state
    _domainEvents.Should().Have.Count.EqualTo(1);
    _domainEvents[0].NewStatus.Should().Be.EqualTo(LightColor.Green);
}

This test is quite ugly and it requires some initialization code, contained in the constructor of the test class.

public TwoTrafficLightFixture()
{
    DomainEvents.ClearAllRegistration();
    CommunicationBus.ClearAllRegistration();

    DomainEvents.Register<ChangedLightStatus>(this, e => _domainEvents.Add(e));
    sut = CrossRoadFactory.For(2.Roads()).Create();
    sut.Start();
}

The bad part about this code is that I want to test this situation: when both traffic light are in red state, only one of them can become green after a given amount of time passed. The awful part about this test is how I setup the fixture; to bring both the Traffic Light in the Red state, I need to create the CrossRoadFactory in the constructor of the test (this is because all tests share this common initialization), then I need to call Tick() several time simulating passing time and moving the system from the initial status to the status that represents the fixture (both light red).

This test is simply wrong, because if if fails you cannot tell if the failure is caused by the initialization code or the real part of the domain logic you want to test, because I’m actually exercising the SUT until it reach the status I want to test with my unit test and this can cause a failure in the Fixture. This is done because if the Traffic Light has no public properties and it is not possible to manipulate the status directly in the test.

To simplify the test I need a way to change the status of a Traffic Light, so I can simply fixture creation and the obvious solution is to use Event Sourcing. I do not want to evolve the Traffic Light to a full Event Sourcing enabled domain, but I wish to verify if having the ability to reconstruct the state of a Domain Object from domain events he raised in the past can solve my test smell. I decided to add a constructor on the TrafficLight domain class that permits to create an instance from a sequence of Domain Events.

public TrafficLight(params BaseEvent[] eventStream)
{
    ActualState = YellowBlinkingState.Instance();
    CommunicationBus.Register<MayITurnGreen>(this, MayITurnGreen);
    Load(eventStream);
}

public void Load(params BaseEvent[] eventStream)
{
    foreach (var eventInstance in eventStream)
    {
        HandleChangedLightStatus(eventInstance as ChangedLightStatus);
    }
}

This is really primitive, it is really far from being a real entity based on Event Sourcing, but the key concept is, I want to be able to reconstruct the private state of an entity simply passing a series of domain events that he raised in the past. Now the previous test can be modified to make it really simpler:

[Fact]
public void When_both_semaphore_are_red_one_become_green()
{

    TrafficLight first = new TrafficLight(new ChangedLightStatus(LightColor.Red, null));
    TrafficLight second = new TrafficLight(new ChangedLightStatus(LightColor.Red, null));
    CrossRoad theSut = new CrossRoad(
        new TrafficLightCreated(first),
        new TrafficLightCreated(second));

    using (DateTimeService.OverrideTimeGenerator(DateTime.Now.AddSeconds(1)))
    {
        theSut.Tick();
    }

    //only one semaphore should be go to green state
    _domainEvents.Should().Have.Count.EqualTo(1);
    _domainEvents[0].NewStatus.Should().Be.EqualTo(LightColor.Green);
}

Now I’m able to create two traffic light passing a ChangedLightStatus event that bring the Traffic Light to the status requested by the fixture, then I can create the CrossRoad class passing two TrafficLightCreated domain events and this is all the code I need to setup the fixture of my test. Now I can simulate that one second is passed, call Tick() function on the CrossRoad and verify that only one Domain Event is raised, because only one Traffic Light Should have changed the value of the light from Red to Green.

Even with this super simple example you can understand that Event Sourcing simplify your tests, because they give you the ability to recreate a specific state of the domain under test from a stream of Domain Events.

Gian Maria.

Tags:

No comments

If you are using the TfsPreview (Tfs on azure), you can notice that the login page is drastically changed.

image

Even if this seems only a simple and stupid change, it shows one of the advantage of using TfsService over having it on-premise: the automatic update process made periodically by Microsoft. The change in the login page is only a fancy change of an update that was deployed last week on TFS Service, this actually means two distinct advantage:

  1. Upgrade to new TFS version is automatic and painless (update of on-premise is now really simple, but still requires some work)
  2. TFS Service will have a more frequent upgrade, you can have bugfix and new feature without the need to wait for Service Pack or for next major version

For Small teams, avoiding any risk and time needed to update On-Premise TFS can be a good advantage over an on-premise installation.

Gian Maria

Tags:

No comments

I always strive myself to write testable code, but it is not always easy, especially if you do not follow TDD red-green-refactor mantra. Code written without Unit Testing in mind is usually not so easy to test and when is time to modify code written by other, if you want to create a safety net of Unit Tests to avoid breaking code it is usually an hard task. The main problem is hardcode dependency from static functions because you cannot test a single function or method in isolation, forcing you to use pattern like Back door manipulation that makes test difficult to read, write and maintain. Lets take this code as example

    public class PerformHeavyTask
    {
        private DateTime lastExecutionTime = new DateTime(1900, 1, 1);

        private Int32 intervalInMinutes;

        private Action task;

        public PerformHeavyTask(Int32 intervalInMinutes, Action task) {

            this.intervalInMinutes = intervalInMinutes;
            this.task = task;
        }

        private Boolean CanExecute() {

            return DateTime.Now.Subtract(lastExecutionTime).TotalMinutes >= intervalInMinutes;
        }

        public void Execute() {
            if (CanExecute())
            {
                lastExecutionTime = DateTime.Now;
                task();
            }
        }
    }

This is a simple and stupid example class that is used to execute an action no more than once every X minutes. The main problem is dependency from the DateTime.Now static function because it create a dependency to the concept of “passing time” that is almost impossible to manage in a test. Suppose that the logic of CanExecute method is complex and depends not only from DateTime.Now or uses some strange algorithm based on time, how can you write a unit test that is capable of testing this algorithm simulating the time that pass? The only solution is being able to change at runtime the behavior of the DateTime.Now static function, a trick that is possible using various external library, but that is now natively available in Visual Studio 11.

This functionality is derived from Pex and Moles project, but now it is fully integrated in VS11, with small differences. First of all you need to right click the reference to the system assembly and choose to Add Fakes Assembly; this creates a special folder called Fakes, with a single file called system.fakes.

26-04-2012 19-40-41

Figure 1: Adding a fake assembly for the System assembly.

Now you can write this simple test that is capable of changing the value of the DateTime.Now static property at runtime

[Fact]
public void Verify_do_not_execute_task_if_interval_is_not_elapsed()
{
    using (ShimsContext.Create())
    {
        Int32 callCount = 0;
        PerformHeavyTask sut = new PerformHeavyTask(10, () => callCount++);
        DateTime startDate = new DateTime(2012, 1, 1, 12, 00, 00);
        ShimDateTime.NowGet = () =>  startDate;
        sut.Execute();
        ShimDateTime.NowGet = () => startDate.AddMinutes(9);
        sut.Execute();
        Assert.Equal(1, callCount);
    }
}

As you can see this code is written in xUnit because VS11 is capable of running Unit Test from external framework if there is the corresponding adapter, so I’m not restricted to use MSTest if I want to use some UnitTesting specific feature of Visual Studio. The first interesting line is the ShimsContext.Create() call, used to create a scope where we can use Shims and isolate calls to non-virtual functions. The concept of Isolation is being able to change how a static property or method behave without the need to change the original code. As you can see I create an instance of the PerformHeavyTask class, with 10 minutes interval and with a function that basically only increment a local variable to have a count of how many times the function is executed. Now to test that the function is not called a second time if not enough time is passed I need to isolate the call to DateTime.Now to return predetermined values.

The line ShimDateTime.NowGet = … permits me to intercepts the getter of the static Now property of DateTime Class and specify the function that will be used instead of standard getter. Shim library works with some convention and since I’ve created a Fake Assembly of the standard System reference, the Shim library will create for me a Shim class for every type in the Assembly prepending the world Shim to the original name. Since I need to change the behavior of the Now static property of DateTime class, I need to use the ShimDateTime class (created for me with the Add fakes assembly command) and use the NowGet property to isolate the Getter of the static property Now. To isolate the getter I simply specify the lambda function to call whenever any code calls DateTime.Now.

The test simple calls the Execute() method the first time, then change isolation function to returns a DateTime that is 9 minutes greater than the previous value, finally I call the Execute() method again and verify that the taks passed to PerformHeavyTask was executed only 1 time, because when I invoked Execute() the second time not enough time has passed and the function should not be executed.

Gian Maria.

Tags: ,

5 Comments

This morning I need to work on an old Visual Studio 2008 project, and since I do not have VS2008 in my machine I decided to convert to VS2010, all projects converts well, but one of them have this error during conversion

SNAGHTML7a5ec4

Figure 1: The strange error during project conversion

I never had such a problem in this installation, moreover the project was a WPF 3.5 project, and there also another WPF 3.5 project in the same solution that works perfectly. So I decided to open the project file to understand what can be wrong.

image

Figure 2: The property of the project file that caused the problem

As you can see in figure 2 I Have a TargetFrameworkSubset in the project that refuse to convert and I do not have the same property in the other WPF project that converted with no problem. Once that property was removed, I was able to reload the project and work with it with no problem.

Gian Maria.

Tags:

1 Comment

Example can be downloaded here.

I previously described a scenario where the customer needs a really basic Request Response service in WCF, the goal is being able to take advantage of a request / response structure, but with an approach like: “the simpliest thing that could possibly works”. This technique is usually needed to introduce new architectural concepts in a team without requiring people to learn a huge amount of concepts in a single shot, a scenario that could ends in a  team that actively fight the new architecture because it is too complex.

Once the team is used to the basic version of the Request/response service and understand the advantage of this approach, it is time to evolve it towards a more mature implementation, and since the grounding concepts are now clear, adding a little bit of extra complexity is usually a simple step. This is the concept of Evolving Architecture or Emergent Design, the goal is to introduce functionality and adding extra complexity only to answer a requirement need and not for the sake of having a Complete/Complex architecture. After a little bit of usage of the basic version of the Request Response service, some new requirements lead to an improvement of the basic architecture. The very first problem of the actual basic architecture is: contract and implementation are contained in the same class.

Class diagram of a sample Request class

Figure 1: Class diagram of a sample Request class

In Figure 1 you can see a sample request, it is called AddTwoNumber and it contains both the contract definition and the business logic that execute the request. This coupling is too high and the new requirement ask to separate contract from the business logic and also requires to evolve the architecture to make it possible loading contracts and business logic from separate assembly using the concept of Plugin.

This new requirement can be solved easily with MEF, a library that will take care of everything about discovering and loading all request / response / handler objects that compose our service. I started removing the Execute method from the basic Request class and moving it to another class Called Handler, that will take care of the execution of a request.

New version of the base Request and Response classes

Figure 2: New version of the base Request and Response classes

As you can see from Figure 2 Request and Response class are now only just base contract classes, with no method related to execution; they contains only properties. To execute a request and return a Response we need another class called Handler, that is capable of Handling a request and returning a response. The key concept is that for each request we have a separate handler that is capable of executing that request

image

I decided to introduce a basic abstract class with no generic, this base class is able to handle a Request object and then I inherited another abstract class called Handler<T> capable of handling a specific type of request, here is the full code.

[InheritedExport]
public abstract class Handler
{
    public Response Handle(Request request)
    {
        return OnHandle(request);
    }

    protected abstract Response OnHandle(Request request);

    public abstract Type RequestHandledType();
}

public abstract class Handler<T> : Handler where T : Request
{

    protected override Response OnHandle(Request request)
    {
        return HandleRequest((T) request);
    }

    protected abstract Response HandleRequest(T request);

    public override Type RequestHandledType()
    {
        return typeof(T);
    }
}

The key point in this structure is: the base Handler class has MEF Specific InheritedExport attribute, that basically tells to MEF engine to automatically Export all types that inherit from this base type. The basic Handler class has a RequestHandledType() method to specify the concrete Request class executed by this handler, this permits me to override it in the Handler<T> just returning typeof(T). The same InheritedExport attribute is then added to Request and Response class to make them loadable by MEF. The cool part is that everything related to discovering Requests, Responses and Handlers is done by MEF. All MEF functionalities are shielded by a simple MefHelper class.

public static class MefHelper
{
    private static CompositionContainer theContainer;
    private static DirectoryCatalog catalog;

    static MefHelper()
    {
        catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
        theContainer = new CompositionContainer(catalog);
    }

    public static void Compose(Object obj)
    {
        var cb = new CompositionBatch();
        cb.AddPart(obj);
        theContainer.Compose(cb);
    }

    public static T Create<T>()
    {
        return theContainer.GetExportedValue<T>();
    }

    public static CoreService CreateService()
    {
        return Create<CoreService>();
    }
}

Code is minimal, I simply create a MEF catalog to scan all assemblies that are in the same directory of the executing assembly and a couple of helper methods to simplify composition and exporting value. The key method here is the CreateService() that internally uses MEF to create a concrete implementation of the CoreService class, where CoreService is the class that is exposed as a WCF service.

[Export(typeof(ICoreService))]
public class CoreService : ICoreService
{
    #region ICoreService Members

    private Dictionary<Type, IList<Handler>> HandlerForTypes = new Dictionary<Type, IList<Handler>>();

    private IList<Handler> GetHandlersForType(Type type) {
        if (!HandlerForTypes.ContainsKey(type)) {
            HandlerForTypes.Add(type, new List<Handler>());
        }
        return HandlerForTypes[type];
    }

    [ImportingConstructor]
    public CoreService([ImportMany(typeof(Handler))] IEnumerable<Handler> handlers)
    {
        foreach (var handler in handlers)
        {
            GetHandlersForType(handler.RequestHandledType()).Add(handler);
        }
    }

CoreService class was modified to use this new architecture, first of all I added the Export attribute to tell MEF that this class is an Export for the ICoreService class service, then I added a simple Dictionary to associate each request with the corresponding handler and finally I added a Cosntructor with the ImportingConstructorAttribute and the ImportMany attribute on the single parameter of IEnumerable<Handler>. This specific constructor tells MEF that CoreService class needs the list of all Handlers discovered by MEF and it is the magic attribute that permits you to make MEF scan all dll in the current directory to find every class that inherit Handler basic abstract class. In the constructor there is a simple foreach used to associate each handler to the concrete Request that it is capable to handle, this is accomplished with RequestHandledType() discussed previously.

public Infrastructure.Response Execute(Request request)
{
    try
    {
        var handlerList = GetHandlersForType(request.GetType());
        if (handlerList.Count == 0)
            return new Response() { IsSuccess = false };
        if (handlerList.Count == 1)
            return handlerList[0].Handle(request);

        throw new NotSupportedException();
    }
    catch (Exception ex)
    {
        return new Response() { IsSuccess = false, ErrorMessage = "Exception during execution" };
    }
}

The execute method is really simple, for each request I verify if an appropriate Handler was available, if I have no handler I return an error, if I have a single Handler I simply use it to execute the Request and finally if I have more than one single Handler I throw an Exception because this is an unsupported scenario for this version. Thanks to MEF and very few lines of code I was able to evolve the basic structure in a more complex architecture where the CoreService dynamically loads Request/Response/Handlers of the concrete implementation.

Now you can take the old AddTwoNumber request from previous example and evolve it to fit this new architecture. The only operation we need to do is removing the Execute() method from the request and move in an appropriate Handler as shown in this simple snippet.

public class AddTwoNumberHandler : Handler<AddTwoNumberRequest>
{
    protected override Response HandleRequest(AddTwoNumberRequest request)
    {
        return new MathOperationResult(request.FirstAddend + request.SecondAddend);
    }
}

The code to implement a business operation is really minimal, just inherit from Handler<AddTwoNumber> override the Handle request and let the infrastructure takes care of everything else. A working example can be downloaded here and in future posts I will explain all the other parts of this infrastructure related to MEF and runtime discovering of plugin.

Gian Maria

Tags: , ,

1 Comment