# Friday, January 01, 2010

In the previous post the fun of enhancing assertion messages, I eluded about CciSharp… but what is it really?

CciSharp is a post-compiler framework for .NET. (In a sense, it is just a sample of things that can be done with  Common Compiler Infrastructure (CCI) ). CciSharp was designed with the following idea in mind: enable to easily write assembly mutators and integrate them into the build. In that sense, CciSharp provides

  • A minimalistic layer on top of the CCI mutable source model.
  • Provide the MSBuild ‘plumbing’ to integrate into a build so you don’t have to worry about it.

Do you have some Mutators examples?

Are you wondering the kind of problems can you solve with a post-compiler? Let’s take a look at a bunch of example (the full source of those samples is available at http://ccisamples.codeplex.com):

  • Lazy Property: A lazy property computes its result once and caches it. Since it is not supported out of the box by C# or VB.NET, it requires boiler plate code to implement it. I’ve written mutator that takes a property makred with a [Lazy] attribute and implements this pattern. Here’s an example before and after of a property that returns the Environment.TickCount.
    image image
  • Weak Lazy Property: The way we cached the property result above has a dangerous side-effect: it bloats your memory. Instead of storing the result has a ‘hard’ reference, one can use a WeakReference instead. That way, the GC can reclaim the cached references whenever memory pressure becomes too high (the GC is really a great built-in caching mechanism in .NET). Again, it takes a bunch of boiler plate code to implement this pattern, which is generated automatically by the another CciSharp mutator. Here’s another before/after example:
    image image
  • ReadOnly Auto Property: Auto-properties are a great feature of C# but somehow I miss the ‘readonly’ keyword. The best that C# gives us is an auto-property with a private setter, which is not quite the same as ‘readonly’ fields. CciSharp contains a mutator that, given an auto-property with a getter and private setter,  (1) deletes  the setter, (2) makes the backing field readonly and (3) updates all the calls to the setter to direct access to the backing field. That way I get exactly what I want: a truly readonly auto-property. The snippet below shows the before/after transformation.
    image image

Those are a couple scenarios that tools like CciSharp enable. In the next post, we’ll look at the DependencyProperty pattern and how CciSharp can really help there.

HAPPY NEW YEAR!!!!

posted on Friday, January 01, 2010 10:35:54 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Wednesday, December 30, 2009

It is holiday time so I could spend some time to play with CCI. The result is a bunch of interesting assembly mutators. Let’s start with the first one: automatic rich assertion messages.

The problem with Assertions

When an assertion fails, the error message is usually insufficient to understand failure. The problem is that we are usually lacking the values in the expression to immediately diagnose the problem. Consider this example,

Assert.True(x == 123);

When this assertion fails, one would like to know what was the value of ‘x’. Of course, that value of x is not serialized in the test output since the assertion method only sees the ‘false’ value. What we would really like to get is something like ‘x (64) != 123’. A number of techniques have been developed to work around this issue.

Solution #1: Specialized Assertions

A common approach is to provide specialized assertion methods with enhanced logging. For example, a special method to test equality:

Assert.Equal(x , 123);

When this assertion fails, the Equal method has the value of both sides of the equality and can render it in the message: ‘expected 123, actual 64’. Unfortunately, expressions are more readable when you write them, and specialized assertions cannot cover all scenarios. This takes us to the next solution.

Solution #2: Expression Trees at Run time

Jafar Husain wrote a very interresting post on how to use Expression Trees to generate rich assertion messages (this is also supported in MbUnit).

Assert.True(() => x == 123);

Instead of taking a bool, the assert method takes an expression tree (Expression<Func<bool>>). Thus, when the expression evaluates to false, the expression tree can be traversed to extract interesting values (such as x) and generate a rich log of the failure.

Unfortunately, there is a major drawback to this technique: what used to be 3 MSIL instructions (ldloc.1, ldc.i4 123, ceq) to evaluate the condition becomes hundreds of methods calls, millions of instructions executed through the System.Linq namespaces. This performance is a overhead on the Pex whitebox analysis.

Jafar considers unit test frameworks as an extension of the compiler and uses expression trees to access what the compiler knows: expression and statements. Following his idea takes us to the CCI based solution.

Solution #3: Assembly Rewritter at Compile time

In the previous approach, expression trees were used to build a little compiler at runtime. A better solution would be to rewrite the expressions at compile time. In other words, we want to build an assembly mutator that takes the original method call and appends code that generates the logging:

Assert.True(x == 123, String.Format(“x == 123 where x = ‘{0}’”, x));

The assembly mutator extracts the expression sources from the pdb (‘x == 123’), collect the local/variable/field references by traversing the expression tree, generate a String.Format friendly message and replace the assertion method call to the assertion method that takes the additional string.

Hello Common Compiler Infrastructure (CCI) and CciSharp

Of course, to rewrite an assembly at compile time, we need a framework that can read and write MSIL, decompile expressions etc… This is where CCI (from http://ccimetadata.codeplex.com ) comes. It allows to manipulate .NET assemblies using an object model and save them back to disk. The assertion message mutator is just one of other mutations that have been or will be implemented as part of CciSharp, a post compiler for .NET that is built on top of CCI.

(There’s already a bunch of useful operators in CciSharp that i’ve been coding over the holidays: assigning the value of auto-properties, making auto-properties readonly or lazy (or weakly lazy), or even implementing the DependencyProperty stuff automatically. We’ll talk about this later.)

Where can I find it?

CciSharp binaries and sources are avaiable on http://ccisamples.codeplex.com/wikipage?title=CciSharp. Grab it!

posted on Wednesday, December 30, 2009 8:45:27 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Friday, December 18, 2009

We just released the version 0.20 of Pex. This version brings a Beavers, an extension of Stubs to write models, a global event view in Visual Studio and many bug fixes. Beavers are a small programatic models that build upon Moles…

  • Beavers: With stubs and moles, we provided a framework to write record/replay tests (i.e. mock-based tests) against any .NET type, interface or not. Beavers take you to the next level and allow you to write simple implementations with behavior (hence the ‘B’eaver) that can be used to replace the external system during testing. The benefit of using Beavers is that the resulting test cases are much more robust to code changes since the tests specify the state of the system, rather than a sequence of method calls and outcomes. We will talk a lot about Beavers in the future. Let’s take a look at an example. The following snippet uses Moles to redirect the constructor of a Bank class, then sets up the GetAccountById(int) method to return an instance of IAccount, etc… This is a typical test that is based record and replay. The problem with this technique is that it is really fragile with respect to code changes: if the code calls different methods, the test will break.
    clip_image002
    The same behavior can be specified using Beavers. Beaver are simple implementations that simulate that capture enough behavior of the original code for testing. Using Beavers, one can specify the state of the system. The functional behavior is re-factored away in a Beaver class and reused in all tests!
    clip_image004
  • Global Event View: when executing multiple explorations, it was cumbersome to go through each exploration to investigate the events (instrumentation, object creation, etc…). We have added a view in the Pex Explorer tree view that centralizes the events for the entire run.
    clip_image006
  • Beavers for SharePoint: The samples that come with Pex contains a number of Beavers for the SharePoint object model (SPList, SPListItem, SPField, etc…) that should help you get started with testing SharePoint with Beavers. As an example, you can compare a mole-based test (left) and a beaver-based test (right) for a simple SharePoint service:
    image image
  • Bug fixes and Improvements:
    • The HostType crashes non-deterministically.
    • Visual Studio 2010 crashes when loading with a ‘DocumentSite already has a site’ error message.
    • The Stubs code generator uses a lot of memory and may crash Visual Studio. The Stubs generator now runs out of process and does not take down Visual Studio when it runs out of memory.
    • The Stubs code generator detects version changes of the Stubs framework to regenerate the stubs assemblies.
    • The Pex execution produces less warnings. We’ve reviewed our warnings and moved some, who did not matter, as messages.
    • When a Contract.Requires is failed multiple time in a stacktrace, do not allow it.
    • The object factory guesser has partial support for internal types and internal visible to (signed assemblies not supported).
    • The ‘add’ and ‘remove’ of events can be moled to deal with events.
    • Digger does not work in Visual Studio 2010 when no test project exists.
  • Breaking Changes: The Beavers introduced a number of refactoring that might impact users of Stubs and Moles. The .stubx file should regenerate themselves automatically, otherwise right click on the file and select ‘Run Custom Tool’.
    • Most types of the Stubs framework have been moved to sub namespaces.
    • IStubBehavior was renamed to IBehavior
    • StubFallbackBehavior was renamed to BehaviorFallbackBehavior
    • PexChooseAsStubFallbackBehaviorAttribute was renamed to PexChooseAsBehavedFallbackBehaviorAttribute
    • PexChooseStubBehavior was renamed to PexChooseBehavedBehavior
    • PexExpectedGoalsAttribute and PexGoal.Reached(…) were renamed and refactored into PexAssertReachEventuallyAttribute and PexAssert.ReachEventually(…);
posted on Friday, December 18, 2009 6:14:57 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Thursday, December 17, 2009

Je viens du publier une video en francais sur les Code Contracts et Pex avec Manuel.

http://channel9.msdn.com/posts/Peli/Code-Contracts-et-Pex-pour-NET/

posted on Thursday, December 17, 2009 8:35:26 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Wednesday, December 16, 2009

I’ll be presenting the PDC talk on Code Contracts and Pex at on January 20th, 2010 in Celestijnenlaan 200A, Heverlee (Leuven). Things change fast, so there will probably a couple changes to the presentation as well. I’ll probably talk a little but more about the tools to mine Code Contracts, etc…

http://distrinet.cs.kuleuven.be/events/2010/2010-01-20%20Seminar%20Halleux.jsp

posted on Wednesday, December 16, 2009 3:22:06 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Tuesday, December 15, 2009

I give a visit to Jeffrey Van Gogh who works for the Reactive Extensions framework, where they have been using Pex and writing Parameterized Unit Tests to test it. See the full video on Channel 9 at

http://channel9.msdn.com/posts/Peli/Testing-Rx-with-Pex/

posted on Tuesday, December 15, 2009 9:36:19 AM (Pacific Standard Time, UTC-08:00)  #    Comments [2]
# Sunday, December 13, 2009

J’aurai le plaisir de presenter ‘Stubs, Moles and Pex’ au premier rendez-vous de DotNetHub 20 janvier 2010 a LLN. DotNetHub est une communaute .NET francophone recemment cree. Au programme, beaucoup de demo a propos de Pex, Stubs et Moles, et aussi d’un nouvel animal – les Beavers.

Ce sera ma premiere presentation 100% en francais, ce qui en soit est un challenge assez interressant!

ps: Pas d’accent sur les claviers qwerty, ce qui rend l’ecriture du francais beaucoup plus facile :)

posted on Sunday, December 13, 2009 8:39:18 PM (Pacific Standard Time, UTC-08:00)  #    Comments [4]
# Thursday, December 03, 2009

I’ll be presenting the latest development on using Moles and Pex to unit test SharePoint 2010 (or 2007) Services at the SharePoint Connnections in Amsterdam, 18th-19th of January.

MSC26: Pex - Unit Testing of SharePoint Services that Rocks!
SharePoint Services are challenging for unit testing because it is not possible execute the SharePoint Service without being connected to a live SharePoint site. For that reason, most of the unit tests written for SharePoint are actually integration tests as they need a live system to run. In this session, we show how to use Pex, an automated test generation tool for .NET, to test SharePoint Services in isolation. From a parameterized unit test, Pex generates a suite of closed unit tests with high code coverage. Pex also contains a stubbing framework, Moles, that allows to detour any .NET method to user-defined delegates, e.g. replace any call to the SharePoint Object Model by a user-defined delegate.

posted on Thursday, December 03, 2009 10:45:36 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0]
# Thursday, November 12, 2009

We just released the Pex 0.19.41110.1 just in time for TechEd session. This version brings an updated support for Visual Studio 2010 Beta2 and .NET 4.0 and many improvements to the Moles.

  • Better Dev10 Beta 2 support! We’ve upgraded our support for Visual Studio 2010 Beta 2. This includes full support for .NET 4.0 Beta 2, the Visual Studio Unit Test HostType and the Visual Studio integration.
    Known Beta 2 issues: 1) When running Pex for the first time, the path to Visual Studio Unit Test is not found. You need to specify the Visual Studio ‘PublicAssemblies’ path (“c:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies”), 2) Don’t run Pex on v2 projects, Pex will crash.
  • Smooth generation of Stubs and Moles: when you create a stubs and moles assembly that is not a project reference, like one of the system assemblies, the stubs and moles code generator will automatically compile it into an assembly and add it to the project. This dramatically increases the performance of projects using Stubs and Moles.
    image
  • Stubs and Moles for VisualBasic.NET: the Stubs and Moles may be used in VisualBasic.NET projects. In that case, they are embedded as a compiled assembly.
  • Moles support for NUnit, xUnit.Net and others: Unit tests involving Moles require the Pex profiler to work. We’ve added a new mode to our command line runner that allows to execute your favorite unit test framework runner under Pex. For example, the command “pex /runner=xunit.console.exe tests.dll” will launch the xunit runner for test.dll under Pex. x64 assemblies are still not supported.
    image
  • Nicer Moles Syntax: we’ve added some little tweaks to the Moles API, such as an implicit conversion operator to the moled type, that simplifies the syntax. Here is a small example that showcases the current syntax: step 1 moles the Bank constructor, step 2 moles the GetAccount method and returns a mole of Account, step 3 moles the getter and setter of the Balance property.
     image
  • Fluent Mole Binding: The Bind method returns the mole itself which allows it to be used in a fluent fashion. Interface binding is specially useful when you need to mole custom collections – just attach an array! For example, we attach an array of integers to a the MyList type that implements IEnumerable<int>.
     image
  • Breaking Changes in Stubs and Moles:
    • The stubs and moles code generator tool is now ‘StubsGenerator’. You need to path this value in the property pages of your .stubx pages.
    • No more AsStub and AsMole: the AsStub and AsMole helpers were confusing and pretty useless so we decided to reduce the amount of generated code by removing them.
    • The naming convention for Stubs delegate fields always mangles the parameter types of the stubbed method, i.e. Foo(int) yields to a field called FooInt32. We used to be smart about adding parameters but we decided to make the scheme stable and symmetric with respect to the Moles.
    • The ‘FallbackBehavior’ property has been renamed to ‘InstanceFallbackBehavior’ in both Stubs and Moles to make it more explicit.

As usual, we’ve also fixed a number of bugs and added features that were reported through our MSDN forums.

posted on Thursday, November 12, 2009 11:57:20 AM (Pacific Standard Time, UTC-08:00)  #    Comments [3]
# Sunday, October 25, 2009

I’ll be presenting Stubs and Moles at the Visual Studio User Group on November 3rd. See you there…

Stubs is a lightweight framework for test stubs and detours in .NET that is entirely based on delegates, type safe, Refactorable, debuggable and source code generated.
Stubs also allows to replace  any .NET method with a user-defined delegate, including non-virtual/static methods in sealed types. Stubs is fully integrated into Pex , an automated white box test generation tool for .NET.
http://research.microsoft.com/en-us/projects/stubs/

posted on Sunday, October 25, 2009 2:45:44 AM (Pacific Daylight Time, UTC-07:00)  #    Comments [2]