Using Pex And Microsoft Code Digger To Better Understand And Test Your Code

In this article you will learn how to use Pex and Microsoft Code Digger to better understand and Test Your Code.

Code is a bit like an animal.

If a great deal of effort is placed into training the animal (through proper design practices, testing methodologies and reviews) then it can easily be domesticated by an experienced developer and can do just about any trick that its owner desires. In contrast, an untrained, untested and poorly written piece of code is the kind that you worry about when you leave the house and it proceeds to destroy everything you hold dear.

This is why testing is such a crucial part of software development and why it can often help to have any many tools as possible to help you train the animal within your code so it doesn't harbor bugs.

Microsoft Research's Pex team recently released the Microsoft Code Digger, which is a handy extension for Visual Studio 2012 that will allow you analyze all of the possible execution paths that a particular snippet of code could take. This can be extremely helpful when dealing with areas of complex code and to help better understand the code, discover why it behaves in a certain way and to uncover any bugs lurking within it.

About Pex

About Pex


Pex is one of the many wonderful things going on at Microsoft Research and it is intended to a tool to assist with automating white-box and unit-testing. It can help with generating all kinds of different inputs that can be thrown at a specific set of code and will display each of these execution branches along with the corresponding output of the function. It can provide an easy way for those that aren’t crazy about writing unit tests to simply test their code by letting the Pex Engine run through it.

Pex can provide an excellent way for you to find those small edge-cases that can so often plague software and the fact that the process is completely automated makes it even easier!

Let's Get Digging

To get started using the Code Digger, you’ll just need to go and download the extension from the following site:

After installing it, you should be good to go and ready to get started!

A minor caveat; Code Digger was very recently released and as a result currently only works for Visual Studio 2012 and can only target code that is contained within Portable Class Libraries. But fear not, as there are still numerous other ways that you can use Pex even outside of Visual Studio 2012, which will be covered later within this post.

Getting Started and Swimming with Sharks

Let's take a look at the Code Digger in action, which can help provide a much better explanation of what is going on behind-the-scenes and what makes Pex so magical!

Firstly, we will create a simple Portable Class Library file that we can use to create a very simple function and get an idea of how the Code Digger works.

Portable class liberary

You'll be prompted to select which environments that you want the code to be compatible with after. Since this is for demonstration purposes, just click OK. Then we will need to create a very simple function to begin with, such as summing an array of integers:

  1. // Simple method to sum an array of integers  
  2. public static int Sum(int[] values)   
  3. {  
  4.    return values.Sum();  
  5. }  
To actually put the Code Digger to work, all you will need to do is simply right-click on your function and select the Generate Inputs / Outputs Table option:

class

As you can see, the Code Digger provided the following valuable inputs that the function might receive as well as the different behaviors that it might exhibit. This information can be very useful in finding weaknesses and avoiding exceptions within our code as well as finding edge cases that may remain unseen:

run

Adding a bit more complexity

Now that we know it will work for a simple integer values, let’s try passing in a more complex model and see what kind of results it provides:
  1. // More Complex Example  
  2. public static decimal CalculateCandyPricePerServing(IEnumerable < BagOfCandy > bagsOfCandy)  
  3. {  
  4.     return bagsOfCandy.Average(p => p.Servings / p.Price);  
  5. }  
  6. // A Bag of Candy  
  7. public class BagOfCandy  
  8. {  
  9.     public int Servings  
  10.     {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public decimal Price  
  15.     {  
  16.         get;  
  17.         set;  
  18.     }  
  19.     public BagOfCandy()  
  20.     {}  
  21. }  
Which yields the following :

build program

As you can see from the output, adding some additional complexity can also introduce other execution paths which require testing to be performed.

We will need to add the necessary checks within this statement to fix up some of these problems, which should be able to be done through a few simple logic checks:
  1. // A simple method to calculate the average price per   
  2. // piece of candy given several bags of candy  
  3. public static decimal CalculateCandyPricePerServing(IEnumerable < BagOfCandy > bagsOfCandy)  
  4. {  
  5.     // Rough attempt to fix several more of the issues   
  6.     // apparent in the first table  
  7.     if(bagsOfCandy == null || !bagsOfCandy.Any(p => p != null && p.Price != 0 && p.Servings != 0))  
  8.     {  
  9.         // Return -1 for invalid results  
  10.         return -1;  
  11.     }  
  12.     else  
  13.     {  
  14.         // Attempt to average the values otherwise  
  15.         return bagsOfCandy.Average(p => p.Servings / p.Price);  
  16.     }  
  17. }  
And now after running it, let's see what our results look like:

build

That's a slight improvement, however there are still a few errors. A little more tinkering with it could help get rid of those few remaining red errors:
  1. public static decimal CalculateCandyPricePerServing(IEnumerable < BagOfCandy > bagsOfCandy)  
  2. {  
  3.     // If the bags of candy are not null and contain any bags  
  4.     // that are not null  
  5.     if(bagsOfCandy != null && bagsOfCandy.Any(b => b != null))  
  6.     {  
  7.         // Gather the unempty bags with valid prices  
  8.         var unemptyBags = bagsOfCandy.Where(b => b != null && b.Price > 0);  
  9.         // If there are any of these bags - output the   
  10.         // average, otherwise -1  
  11.         return(unemptyBags.Any()) ? unemptyBags.Average(p => p.Servings / p.Price) : -1;  
  12.     }  
  13.     else  
  14.     {  
  15.         // Otherwise return -1  
  16.         return -1;  
  17.     }  
  18. }  
Which yields:

yields

As you can see, Pex is great and continually challenging your possible inputs to help you avoid errors. This also functions as a great method to teach yourself or others about unit-testing and how to properly develop methods (and hopefully develop solid habits so that you won’t have to do this for every one of your methods).

Don’t Have Visual Studio 2012? No problem!

Although the Microsoft Code Digger is the most recent tool released by the Pex Team, it isn't the only one out there. The team has previously released two of the components of the engine as Add-Ins for Visual Studio 2008 and Visual Studio 2010, which can be downloaded below:

 

  • Pex and Moles - A Pex Engine Power Tools Add-In for Visual Studio 2008 and 2010.

    Pex consists of the following tools and functions:

  • Pex command line (Visual Studio not required).
  • Pex Visual Studio Add-in, for Visual Studio 2008 and Visual Studio 2010.
  • API reference, tutorials and documentation.
  • Samples and Behaviors

    And Moles has the following features:

  • Lightweight test stubs and detours for .NET.
  • API reference, tutorials and documentation.
  • Samples and Behaviors.

These tools should be everything that you need to begin exploring, experimenting and hopefully more easily testing your code.

Note: In Visual Studio 2012, Moles has been replaced by the Fakes Framework. You can read more about handling and isolating your code using the Fakes Framework here.

Try it out yourself online!

If you aren't sure if the Code Digger, Pex or Moles are something that you would be interesting in, you should give it a try online using Pex for Fun!

pex

Pex for Fun is a learning tool and puzzle game designed using the basic concepts behind Pex. It features a very simplified version of Pex, which analyzes a given function and provides you information about the output and challenges you to place the appropriate logic within the function to solve the puzzle.

For example, you initial puzzle might look like this:

  1. using System;   
  2. public class Program {   
  3.    public static int Puzzle(int x) {  
  4.       return x;  
  5.    }  
  6. }  
Along with the following output:

output

Looking at this, you might think "Well since I know the output, I'll just use a switch statement”:
  1. using System;  
  2. public class Program  
  3. {  
  4.     public static int Puzzle(int x)  
  5.     {  
  6.         switch(x)  
  7.         {  
  8.         case 0:  
  9.         case 1:  
  10.         default:  
  11.             return x;  
  12.         case 2:  
  13.             return x + 1;  
  14.         case 3:  
  15.             return x * 2;  
  16.         case 7:  
  17.             return x * x + x;  
  18.         }  
  19.     }  
  20. }  
Nope! If you have ever been in a programming competition before, you will know this feeling:

programming competition

If you enjoy puzzles like these, you'll quickly figure out that the solution requires a bit of recursion:
  1. using System;  
  2. public class Program  
  3. {  
  4.     public static int Puzzle(int x)  
  5.     {  
  6.         if(x <= 1)  
  7.         {  
  8.             return x;  
  9.         }  
  10.         else  
  11.         {  
  12.             return Puzzle(x - 1) + ((Puzzle(x - 1) - Puzzle(x - 2)) + (Puzzle(x - 2) - Puzzle(x - 3)));  
  13.         }  
  14.     }  
  15. }  
And to the victor go the glorious, pixelated spoils:

You win

More than Pixelated Golden Medals

The Pex for Fun example as mentioned earlier displays the most very basic features of the Pex Engine and is really meant more for recreational and educational purposes.

The features and functionality that exists there however is quite powerful and if leveraged correctly could dramatically change the way that unit-testing is done (or it could at least act as a great supplement). I encourage you to try downloading any of the Pex packages mentioned throughout this post and try it out yourself.

If you want to access the same examples used within this post, you can download them below:

 

Perhaps with the incredible continuing progress of the Pex Team and the rest of the folks over at Microsoft Research, unit-testing can and will become more like a game and less like a chore.