Slower than Reflection; meet StackTrace

I was entertaining the idea of contextual components that would act differently depending on who called them. System.Diagnostics.StackTrace is the class that allows you to traverse the call stack, and see who called your method. There’s one catch though – it is painfully slow. And by painfully, I mean this:

StackTrace

Those two methods are by no means comparable in regard of what they’re doing. They are mere examples of simple tasks: one involving Reflection, and one involving StackTrace. The fact that the difference in performance is nearly two orders of magnitude, should make you think twice before you go down the StackTrace path. Especially considering the fact, that you can’t really cache it.

Technorati Tags: , ,

Testing collections with NUnit

How do you test collections for equality of their elements? I often used to write my own custom assert for that, something like:

public void AssertCollectionElementsAreEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
    var first = expected.GetEnumerator();
    var second = actual.GetEnumerator();
    int count = 0;
    while(first.MoveNext())
    {
        if(second.MoveNext())
        {
            Assert.AreEqual(first.Current,second.Current);
        }
        else
        {
            throw new AssertionException(string.Format("Collection has less elements than expected: {0}", count));
        }
        count++;
    }
    if(second.MoveNext())
    {
        throw new AssertionException(string.Format("Collection has more elements than expected."));
    }
}

I thought it’s just plain to common task to not be included in the framework itself, so I read the manual, and I found CollectionAssert.AreEqual() method that does exactly that.

Then Charlie Poole, made me realize there is even simpler way.

using System.Collections.Generic;
using NUnit.Framework;
 
namespace NUnitAreEqualSample
{
    [TestFixture]
    public class CollectionsEqualitySampleTests
    {
        [Test]
        public void DifferentTypesOfCollectionsShoudBeEqualIfElementsAreEqual()
        {
            var list = new List<string> {"foo", "bar"};
            var array = new[] {"foo", "bar"};
            Assert.AreEqual(list, array);//notice this
        }
    }
}

This produces following result:

nunit_areEqual_passed

Simple Assert.AreEqual() does the job. Sweet.

Technorati Tags: , ,

On generics limitations

I wish generics in C# were more powerful. Why this is not legal?

public class ServiceHost<TService> : ServiceHost where TService : class
{
    public ServiceEndpoint AddServiceEndpoint<TServiceInterface>(Binding binding, string address)
        where TService : TServiceInterface
    {
        return AddServiceEndpoint(typeof(TServiceInterface), binding, address);
    }
}

Technorati Tags:

Can you spot a bug?

Can you spot a bug here?

Took me 20 minutes to find it.smile_whatchutalkingabout

 

private List<string> GetLanguages(string path)
{
    var languages = new List<string>();
    if(File.Exists(path))
    {
        using(var reader = new StreamReader(path,_encoding))
        {
            var dscReader = new DscReader(reader);
            while(dscReader.Read())
            {
                string language = dscReader.Item.Language;
                if (!string.IsNullOrEmpty(language) && !language.Contains(language))
                    languages.Add(language);
            }
        }
    }
    return languages;
}
Technorati Tags:

Simplifying Rhino.Mocks, Round III: kinds of mocks

My last two posts regarding Rhino.Mocks, attracted quite a lot of attention. Focusing on solution I proposed for limiting complexity around creation different kinds of mocks, one thing was pointed out by few people as not the best solution. Ayende called it “in your face! API design”, that is stating the kind of mock you want to create explicitly, via method parameter.

I don’t think that doing it via method name is any less explicit, but let’s not go there. Instead, let’s think for a while – why do we need 4 kinds of mocks anyway?

All differences boil down to one thing – how the mock handles unrecorded calls:

  • StrictMock (_repo.CreateMock overloads), any unexpected call results in exception being thrown.
  • DynamicMock (_repo.DynamicMock overloads), any unexpected call returns default(T), where T is return type, that is null or 0 for value types.
  • PartialMock (_repo.PartialMock overloads), this works only for classes and any unexpected call is not intercepted but forwarded to the actual method of that class.
  • Stub (_repo.Stub), this is similar to DynamicMock with addition, that if you assign a value to a property, it remembers that value.

Those are all very important differences but I’d say quite subtle. Subtle to a point, that I am willing to agree that specifying them upfront either via explicitly named creation method, or via explicit parameter is throwing “in your face!” decisions that you shouldn’t have to be concerned about at this point.

Morten Lyhr noticed this as well, and he suggested the following solution:

public class LoginPresenterFixture
{
   private MockRepository _mockRepository;
   private LoginPresenter _loginPresenter;
   private LoginView _loginView;
   [SetUp]
   public void Init()
   {
      _mockRepository = new MockRepository();
      _loginView = _mockRepository.DynamicMock<LoginView>();
      CreateLoginPresenter();
   }
   private void CreateLoginPresenter()
   {
      _loginPresenter = new LoginPresenter(_loginView);
   }
   [Test]
   public void Strict_Test_Not_As_Often_Used()
   {
      //Override default mock kind
      _mockRepository.StrictMockBehaviour(_loginView);//this is important
      using (_mockRepository.Record())
      {
         Expect.Call(_loginView.ShowView);
      }
      using (_mockRepository.Playback())
      {
         _loginPresenter.Show();
      }
   }
}

It’s some way of dealing with it but it still requires you to explicitly assign behavior to mock object.

It’s still incorrect level of granularity though: instead of class level (different class per different mock kind) we now deal with it on object level (different kind per object).

I’d however move it yet one step further, to method level (different kind per method).

It might look something like this:

   [Test]
   public void Strict_Test_Not_As_Often_Used()
   {
      using (_mockRepository.Record())
      {
         Expect.Call(_loginView.ShowView);
         //Decide what to do with unexpected calls:
         Expect.For(_loginView).NothingElse();//this is important
      }
      using (_mockRepository.Playback())
      {
         _loginPresenter.Show();
      }
   }

Again, difference is very subtle, but important: instead of explicitly deciding about kind of mock, we decide about what to do about unexpected calls, which is more natural and closer to the actual problem. Different kinds of mocks, are just proposed solutions. The ‘kind’ is no longer a property of the mock object.

It also makes it easier to start with mocking framework: decision about what to do about unexpected calls is not thrown at your face at the very first lines, hidden behind terms like “Partial” or “Dynamic”. Instead you make that decision explicitly (and this time it’s a good thing) in last responsible moment that is in the actual test.

Technorati Tags: , , ,

Simplifying Rhino.Mocks

[UPDATE]: Example code is updated. I realized that Kind.Multi is not needed, since you can infer that from passed parameters (when ctorArgs are present, user obviously wants to create MultiMock). I also changed default Kind to Relaxed, since this is the most common one.

Ayende wrote today about his ideas for new version of Rhino.Mocks. I like the new syntax (looks similar to what MoQ offers), but there’s one more change I’d like to see.

Here’s the list of all methods of MockRepository, used to create some kind of mock:

 

public T CreateMock<T>(params object[] argumentsForConstructor);
public object CreateMock(Type type, params object[] argumentsForConstructor);
public T CreateMockWithRemoting<T>(params object[] argumentsForConstructor);
public object CreateMockWithRemoting(Type type, params object[] argumentsForConstructor);
public T CreateMultiMock<T>(params Type[] extraTypes);
public object CreateMultiMock(Type mainType, params Type[] extraTypes);
public T CreateMultiMock<T>(Type[] extraTypes, params object[] argumentsForConstructor);
public object CreateMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor);
public T DynamicMock<T>(params object[] argumentsForConstructor);
public object DynamicMock(Type type, params object[] argumentsForConstructor);
public T DynamicMockWithRemoting<T>(params object[] argumentsForConstructor);
public object DynamicMockWithRemoting(Type type, params object[] argumentsForConstructor);
public T DynamicMultiMock<T>(params Type[] extraTypes);
public object DynamicMultiMock(Type mainType, params Type[] extraTypes);
public T DynamicMultiMock<T>(Type[] extraTypes, params object[] argumentsForConstructor);
public object DynamicMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor);
public static T GenerateStub<T>(params object[] argumentsForConstructor);
public static object GenerateStub(Type type, params object[] argumentsForConstructor);
public T PartialMock<T>(params object[] argumentsForConstructor) where T : class;
public object PartialMock(Type type, params object[] argumentsForConstructor);
public T PartialMultiMock<T>(params Type[] extraTypes);
public T PartialMultiMock<T>(Type[] extraTypes, params object[] argumentsForConstructor);
public object PartialMultiMock(Type type, params Type[] extraTypes);
public object PartialMultiMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor);
public T Stub<T>(params object[] argumentsForConstructor);
public object Stub(Type type, params object[] argumentsForConstructor);

26 methods including 2 static methods (most of them in 2 flavors: generic and 1.1-like). I guess that’s a lot. I can imagine this can be a little overwhelming for new users.

I understand that tearing interface of MockRepository would not be the best idea, but I think that creating a Facade to it might simplify things a lot.

public class MockRepositorySlim
{
    private static readonly Dictionary<Kind, Func<MockRepository, Type, object[], Type[], object>> _mockMethods =
        new Dictionary<Kind, Func<MockRepository, Type, object[], Type[], object>>(9)
            {
                {Kind.Relaxed,(r, t, cp, et) => et.Length > 0 ? r.DynamicMultiMock(t, et, cp) : r.DynamicMock(t, cp)},
                {Kind.Strict, (r, t, cp, et) => et.Length > 0 ? r.CreateMultiMock(t, et, cp) : r.CreateMock(t, cp)},
                {Kind.Stub, (r, t, cp, et) => r.Stub(t, cp)},
                {Kind.Partial,(r, t, cp, et) => et.Length > 0 ? r.PartialMultiMock(t, et, cp) : r.PartialMock(t, cp)},
                {Kind.Strict | Kind.WithRemoting, (r, t, cp, et) => r.CreateMockWithRemoting(t, cp)},
                {Kind.Relaxed | Kind.WithRemoting, (r, t, cp, et) => r.DynamicMockWithRemoting(t, cp)}
            };
 
    private readonly MockRepository _repo = new MockRepository();
 
    public TTypeToMock Mock<TTypeToMock>()
    {
        return Mock<TTypeToMock>(Kind.Relaxed, new Type[0], new object[0]);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind)
    {
        return Mock<TTypeToMock>(mockKind, new Type[0], new object[0]);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind, params object[] ctorArgs)
    {
        return Mock<TTypeToMock>(mockKind, new Type[0], ctorArgs);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind, params Type[] extraTypes)
    {
        return Mock<TTypeToMock>(mockKind, extraTypes, new object[0]);
    }
 
    public TTypeToMock Mock<TTypeToMock>(Kind mockKind, Type[] extraTypes, params object[] ctorArgs)
    {
        if (extraTypes == null) throw new ArgumentNullException("extraTypes");
        if (ctorArgs == null) throw new ArgumentNullException("ctorArgs");
 
        if (mockKind == Kind.WithRemoting)
            mockKind &= Kind.Strict;
        else if (!_mockMethods.ContainsKey(mockKind))
        {
            if ((mockKind & Kind.WithRemoting) != 0)
                throw new ArgumentException("This kind of mock does not support remoting.");
            throw new ArgumentException("Invalid mock kind.", "mockKind");
        }
        //NOTE: possibly with lock in this call
        var mock = (TTypeToMock) _mockMethods[mockKind](_repo, typeof (TTypeToMock), ctorArgs, extraTypes);
        return mock;
    }
}
internal static class KindExtensions
{
    public static bool IsSet(this Kind kind, Kind value)
    {
        return (kind & value) == 0;
    }
}
 
 
[Flags]
public enum Kind
{
    Strict=0,
    WithRemoting=1,
    Relaxed=2,
    Stub=4,
    Partial=8
}

Now we have only 5 methods, 4 of which call the 5th one. I guess that’s simpler solution. Is it any better?

Technorati Tags: , ,

Beautiful code

Ok, maybe this title is a little bit too catchy. However, I simply love the expressiveness of this little piece of code I wrote today.

   1:          public bool RegisterAll( Assembly assembly, Func<object, bool> isValidMessage )
   2:          {
   3:              if( assembly == null )
   4:              {
   5:                  throw new ArgumentNullException( "assembly" );
   6:              }
   7:              if( isValidMessage == null )
   8:              {
   9:                  throw new ArgumentNullException( "isValidMessage" );
  10:              }
  11:              var messages = from t in assembly.GetTypes()
  12:                             where t.HasAttribute<MessageAttribute>() &&
  13:                                   isValidMessage( t )
  14:                             select t;
  15:              return messages.All( Register );
  16:          }

 

Technorati Tags: ,

I want that in C# 4.0

I’ve been playing with Boo recently and I find it to be very powerful language. One little thing I like particularly is, that I can do this:
name = "Krzysztof"
print "Hello, ${name}, on the beautiful day of ${date.Today}"
And get this:
boo
Can I please have this in C# 4.0?
Technorati Tags: , ,

Mocking with Moq and Rhino.Mocks

Last week I’ve read quite a few new blogposts about Moq mocking framework. I had looked at it once, when it was first released, but I didn’t find it interesting back then. Now that version 2.0 was released I decided to give it a go once again.

Here’s very simple model I created:

model

It’s a class with one method that uses helper object to obtain a value and possibly raise an event.

Here’s the whole code:

public interface IHelper
    {
        int Param { set; }
        string SomeMethod();
    }
    public class MyClass
    {
        public MyClass(IHelper helper)
        {
            Helper = helper;
        }
 
        public IHelper Helper { set; private get; }
 
        public event EventHandler MyEvent = delegate { };
 
        public void DoSomething(int parameter)
        {
            Helper.Param = parameter;
            string result = Helper.SomeMethod();
            if (result != null)
                MyEvent(null, EventArgs.Empty);
        }
    }

Now, to the fun part:

Let’s see how we can verify that when SomeMethod returns null, MyEvent is indeed not raised. First with Rhino.Mocks

   1:          [Test]
   2:          public void DoDomething_should_NOT_raise_MyEvent_when_helperSomeMethod_returns_null_Rhino()
   3:          {
   4:              var helper = _mocks.CreateMock<IHelper>();
   5:              var subscriber = _mocks.CreateMock<IEventSubscriber<EventArgs>>();
   6:              using (_mocks.Record())
   7:              {
   8:                  Expect.Call(helper.Param = 3);
   9:                  Expect.Call(helper.SomeMethod()).Return(null);
  10:                  DoNotExpect.Call(() => subscriber.Method(null, EventArgs.Empty));
  11:              }
  12:              using (_mocks.Playback())
  13:              {
  14:                  var sut = new MyClass(helper);
  15:                  sut.MyEvent += subscriber.Method;
  16:                  sut.DoSomething(3);
  17:              }
  18:          }

18 lines of code (you could cut that down to 13 simply by using ReplayAll() instead of Record() and VerifyAll in TearDown method instead of Playback, but I prefer it this way. My code is clean and quite well serves as documentation: Especially thanks to explicit usage of DoNotExpect.

The only awkward thing, is that whereas in both Expect call, I insert bare calls, in DoNotExpect.Call I had to use lambda. It’s a small inconsistency.

Now how would the same test look like with Moq?

   1:          [Test]
   2:          public void DoDomething_should_NOT_raise_MyEvent_when_helperSomeMethod_returns_null_Moq()
   3:          {
   4:              var helper = new Mock<IHelper>(MockBehavior.Strict);
   5:              var subscriber = new Mock<IEventSubscriber<EventArgs>>(MockBehavior.Strict);
   6:              helper.Expect(h => h.Param = 3);
   7:              helper.Expect(h => h.SomeMethod()).Returns((string)null);
   8:   
   9:              var sut = new MyClass(helper.Object);
  10:              sut.MyEvent += subscriber.Object.Method;
  11:              sut.DoSomething(3);
  12:          }

12 lines including one empty to visually divide setup part from testing part. Nice. There’s however one BIG problem with this code: it won’t compile. As I said earlier, You can’t have assignment in Expressions, and that’s what Moq is using, so if you want to set some properties on your mock… well – you’re out of luck. I also don’t like the fact that I have to cast null, to string. This seems redundant, but it’s only a small annoyance.

Bigger problem is that I can’t explicitly state that I expect MyEvent not to be raised.

Another thing, I couldn’t find a way to get hold of event raiser. I guess it’s just not there, so if you want to test events… you’re out of luck too.

Moq is interesting project for sure, it’s simple (simplistic) syntax made me think, about how complicated Rhino.Mocks became. Sure it’s orders of magnitude more powerful, but some unification of interfaces, even for a price of breaking some old code would be highly desired. I can imagine that for a newcomer current learning curve may seem steep. Especially the fact of using static classes makes API much less discoverable.

So I will stick to Rhino.Mocks, as it Moq is still to simple for serious use, but I’m glad it’s there. It brings some fresh ideas to the table, and there’s nothing better than a little competition.

Technorati Tags: , , ,

Building dynamically look up table of classes with LINQ and Reflection

Here’s the problem: Having some ID, get a new instance of some class corresponding to this ID. All classes implement the same common interface (by which we will use them).

So we need to be able to write something like:

public IMessage DoSomethingWithMessage(Id id)

{

    IMessage message = MessageFactory.CreateMessage(id);

    message.DoSomething();

}

Now, how to actually implement MessageFactory, knowing that it needs to be really fast, and without having to explicitly change its implementation when new messages are added, Ids change and so on? And how to bind IDs to Messages?

Here’s my idea for the solution, and comments and improvements are more than welcome.

Each Message has its ID known beforehand, so it seems logical that the only place where this knowledge is kept should be the class itself. Now, I could define this ID as const, or static readonly field in each class, but this seems a little bit awkward to me.

First, I don’t gain anything by it, I can’t enforce a class to have a static field for once, and it doesn’t seem to belong there. It’s not used anywhere else than as a way to identify a class that should be instantiated in this one place, so it’s more like metadata on a class, rather than actual class’ data. That’s why I declared IdAttribute class that I decorate each Message class with.

Next thing: actual registration. How to have the cake (have all the types registered properly) and eat it (not having to change MessageFactory’ implementation each time I change a message). Since I’m already using reflection to get to each message’ Id, it seems reasonable to hit two birds with one stone, and get the types via reflection as well. Finally I came up with this LINQ query:

private static readonly IDictionary<int, MessageCreator> messages =

    (from t in Assembly.GetExecutingAssembly().GetTypes()

     where t.IsClass && !t.IsAbstract && t.Implements<IMessage>() && t != typeof (EmptyMessage)

     select t).ToDictionary(t => t.Attribute<IdAttribute>().Id, c => c.GetCreator());

Please ignore MessageCreator and other custom extension methods. We’ll get to them in a second.

Another problem is the actual instantiation. As I said, it needs to be very fast, so based on Oren‘s recent study, I decided to go where the dragons live and use DynamicMethod. It adds little overhead when the program starts to build methods, but it happens before the program gets under heavy fire of requests, so it’s fine.

I created delegate declaration for my creation methods

public delegate IMessage MessageCreator();

And then the actual method for creating certain type of Message (GetCreator extension method from above LINQ query).

public static MessageCreator GetCreator(this Type type)

{

    var method = new DynamicMethod("Create" + type.Name, type, new Type[0]);

    ILGenerator gen = method.GetILGenerator();

    ConstructorInfo ctor = type.GetConstructor();

    gen.Emit(OpCodes.Newobj, ctor);

    gen.Emit(OpCodes.Ret);

    return (MessageCreator)method.CreateDelegate(typeof (MessageCreator));

}

GetConstructor is extension method that gets default constructor.

Here’s the entire code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Reflection;

using System.Reflection.Emit;

 

 

namespace Creation

{

    class Program

    {

        static void Main(string[] args)

        {

            IMessage message = MessageFactory.CreateMessage(1);

            Console.WriteLine(message.Write());

            IMessage empty = MessageFactory.CreateMessage(-1);

            Console.WriteLine(empty.Write());

        }

    }

 

    public class MessageFactory

    {

        private static readonly IDictionary<int, MessageCreator> messages =

            (from t in Assembly.GetExecutingAssembly().GetTypes()

             where t.IsClass && !t.IsAbstract && t.Implements<IMessage>() && t != typeof(EmptyMessage)

             select t).ToDictionary(t => t.Attribute<IdAttribute>().Id, c => c.GetCreator());

 

        private static readonly IMessage empty = new EmptyMessage();

 

        public static IMessage CreateMessage(int id)

        {

            if (messages.ContainsKey(id))

                return messages[id]();

            return empty;

        }

    }

 

    public delegate IMessage MessageCreator();

 

    public interface IMessage

    {

        string Write();

    }

    

    [Id(1)]

    public class Message1:IMessage

    {

        public string Write()

        {

            return ToString();

        }

    }

 

    [Id(2)]

    public class Message2:IMessage

    {

        public string Write()

        {

            return ToString();

        }

    }

 

 

    public class EmptyMessage:IMessage

    {

        public string Write()

        {

            return ToString();

        }

    }

 

    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]

    public sealed class IdAttribute : Attribute

    {

        private readonly int _id;

        public IdAttribute(int id) {

            _id = id;

        }

 

        public int Id

        {

            get { return _id; }

        }

    }

 

    public static class TypeExtensions

    {

        public static bool Implements<IInterface>(this Type type)

        {

            return type.GetInterfaces().Contains(typeof (IInterface));

        }

        public static TAttribute Attribute<TAttribute>(this Type type) where TAttribute:Attribute

        {

            return (TAttribute)type.GetCustomAttributes(typeof (TAttribute), false).Single();

        }

        public static ConstructorInfo GetConstructor(this Type type)

        {

            return type.GetConstructors().Single(c => c.IsPublic && c.GetParameters().Count() == 0);

        }

 

        public static MessageCreator GetCreator(this Type type)

        {

            var method = new DynamicMethod("Create" + type.Name, type, new Type[0]);

            ILGenerator gen = method.GetILGenerator();

            ConstructorInfo ctor = type.GetConstructor();

            gen.Emit(OpCodes.Newobj, ctor);

            gen.Emit(OpCodes.Ret);

            return (MessageCreator)method.CreateDelegate(typeof (MessageCreator));

        }

    }

}

There are few things I don’t like about this solution however.

Conventions. It’s a convention that each Message must have Id attribute, with unique value, and it’s a convention that each must have default public constructor. In the actual code GetConstructor and Attribute<TAttribute> methods throw descriptive exceptions when those conventions aren’t met, but it happens at runtime, not during compilation.

Reflection. It seems to be reasonable choice, but if there was some other solution…

Anyway, I’m open for suggestions on how to improve/change that.

Technorati Tags: , , ,