Clojure: Default Unit Test Setup

Code for this project is on github.

So you want to test in Clojure, huh? Well good thing you found this oasis of awesomeness. Getting a test up and running is pretty easy, but involves a few simple steps that I will stretch out to the point of pain.

First off, start a new project. Again simple. Just let Linegen to do if for you:


Doing this should create a new project space age tubular frame:


Still with me? Good. Now for the test creation.


As you can see, I added a file with a test. What you might notice, or cause panic, is that I don’t have a file to test with this test file test. And that’s ok, because we’re @#$%ing this $@#% up Test First style. Basically, create a test, and then create what it’s supposed to test. I won’t get into Test First here, but just wanted to calm your concerns.

Now to run the test. This is done by opening up a command window, navigating to the root folder for your project (It will have a project.clj file in it), and typing

	lein test

Ruh roh. Looks like that file that isn’t in existence can’t be tested. Weird, right? Oh well, time to create it.


There are a couple points at this eh point. You will see that I added a file named “simple_math.clj” to the “test_example” folder.

Something I found out while I was creating this little gem of a tutorial; Apparently the convention for a folder is to use a _ where a class in a file uses a -. So as you can see, the folder “test_example” translates the namespace part “test-example”, and “simple_math.clj” becomes “simple-math”. From what I can tell, since I am pretty new to Clojure, lienigen will try to resolve the namespace of “test-directory.simple-math” to “test_directory/simple_math”. I assume this is part of the “convention over configuration” school of thought. Since I come from a .net background where conventions just don’t exist, it caught me off guard.

Anyways, since that is done, it’s time to run the test again.


One failure? Oh yeah, the junk test created by lienegin. Well, just get rid of that:


And run it again:


And things are looking a lot better.

F# and using strings for method and class/type names

So after about 2 months of jumping back and forth between languages (Including and not only: Ruby, Python, IronPython, Boo, Scala, and a lot more I don’t remember) I’ve finally settled on F# for more reasons than I will put in this post. BUT one thing that kind of blew me away, and I realize that doesn’t take much (I thought the ending to Terminator 3 was great), was the ability to name methods with string representations… eh wha?

Well I was writing unit tests and stumbled onto the FSUnit “library” (and by “library” I mean a single file). Well on the page there was an example that looked a sumthin’ like this:

[<TestFixture>]
type ``Given a LightBulb that has had its state set to true`` ()=  
  ...

Now if you haven’t used F# just replace “type” with “class”. Essential there is a string/text built name. Not something you see, or at least I haven’t, in any old language. So I went forth and was fruitful and multipled… with unit tests… gross.

[<TestFixture>]
type public ``When Adding``() =
    let returnThing = new MethodResult() :> IResult
    let randomTool = new RandomTool()

    [<Test>]
    member public x.``A Warning Message The Success Flag Is Set To True``() =
        returnThing.AddMessage(new MessageItem(randomTool.RandomString(10), MessageCategory.Warning)).Success |> should be True

And using Resharper’s unit test box thingy it gave a read out of:

  When Adding A Warning Message  
     The Success Flag Is Set To True             Success

Now I’m not sure how useful this is for non unit testing but I think it’s obvious it is to reading Unit Test results. Pretty nice.

Unit Testing 4.0 Web Forms Including Event Handlers Like Page_Load Using Dynamic

If you’re too lazy or just plain impatient, you can find the source code here.

So one of the biggest pains in a place that doesn’t lend itself well to be in pain has been trying to unit test web forms like how MVC controllers can be. Before 4.0, this was an aggrevation at the least. Something in between stubbing one’s toe and getting only chocolate icecrfeam when you ask for a @*&*ing swirl. Serious, how hard is it to pull the swirl lever? Really.

Anyways, so there are certain things in .net web forms that were pretty difficult to hande/mock/get around for testing. Let’s take session for instance. Session is a sealed class with a non public constructor. To make things more interesting, the Page class only has a get for the Session property. Now you could go through a lot of hell, mostly reflection, to get aroud this, but who wants to do that? Personally I gave web forms the ole one finger salute, but being that I am working with web forms again… yeah had to find a way to get around this. The answer? Stems from dynamic.

Basically what I had to do is create a class that has a Session property that is dynamic, and then replace the old Session call with a class that calls a property named Session. The effect to the code, as far as the immediate code behind is concerned, is just this simple adding of the class before the Session call. Far as the code to do this, it’s fairly easy too.

First I started with an interface since using an interface will help later if I need to mock.


This is the bread and butter. Basically we have a container that will hold the session object. Making the property dynamic allows it to be set to anything. All I have to worry about is that whatever I set it to has the functionality used by Session. This is started by implementing the interface fo use on the site:


And then one for use with testing:


How are these used? Well if we take a base page:


So what this does is holds two constructors; One for use by .Net when it runs the site and one for the test class when it is testing the page functionality. The second is a way to stop all the stuff that happens in the Page class constructor when it’s time to unit test this [explitive]. This might look familiar to people who have used things such as Dependency Injection with MVC to help with Controller testing. If not, the idea is simple. It basically just gives the Page the test handler we need it to use when testing. If we aren’t testing, then we let it just use the default handler.

You might wonder why I didn’t instantiate the live version in the constructor, and the answer is: Session isn’t ready to be used at constructor time when doing the normal web site thing. Therefore, it will be set the first time the SessionHandler property is called. If it’s a test, well then it’s fine to set it in the constructor since it is bypassing the normal web site… thing.

The unit test looks something like this:


As you can see, a test version of the handler is created and the Session object is replaced with a Dictionary since that’s what Session is… well it has more to it but the most used feature is the key/value match and it happens to be the only part of Session I show in this example.

Since there is the second, test only, constructor on the page, we don’t have to worry about any asp.net stuff getting in the way when instantiating the page. The page will look like this:


As it can be see, the replacement of the Session call with SessionHandler.Session allows the features of Session but also the testability it lacked for so long. It’s true that if you want to use other features of Session, if there are any and I can’t remember, you’ll have to just add them to the test version so they can be called at test time. I can’t do everything for you.

Test Driven Development… A Simplified Start

So I went to a “doctor’s appointment” yesterday and was asked to do some pair(ed?) programming to solve a simple-ish request. Basically it was:

Get a number in a list of integers that is closest to 0.

Sounds easy enough, right? Well there are a few more rules but nothing game breaking:

  • If the list contains a 0 then return 0
  • If the list is null then throw ArgumentNullException
  • If list is empty then throw ArgumentException
  • If there is no 0 then get the number nearest 0
  • If the closest is the same for positive and negative (Say -2 and 2), return the positive

Again, fairly simple thing to work on.

Right off the bat I set about creating the method for doing this since my usual plan is:

  1. Create method
  2. Unit test
  3. ???
  4. #$@%!

The fourth step is actually repeated a couple times.

So after I had done the more brute force sort of way, and had a failing test, it was suggested I start over. This time stick with the TDD like mindset of

  1. Create test
  2. Fail test
  3. Add code to make it work
  4. Watch it succeed

Now the concept of TDD I have known about for a while, but never really had a chance to really jump into it. After all, most companies just want something done now, not done well. Beyond that, I had reservations of how it works and whether I was smart enough to pull it off. After all, I had always thought you have to be able to see the whole method before it’s written in order to create tests. Well after yesterday I can say I was wrong… at least about the second part.

When I started writing test methods I was told to make them each this way:

Always add to a method the most simple way to get a test to run.

Yeah ok, it sounded better when I heard it yesterday. However, I have examples.

So if we take the first requirement:

If listToCheck contains a 0 then return 0

Well what should I write as a test? Easy:


As you can see I am only checking to make sure there is a 0 returned. Side Note: You might notice that the method is red. This is because it hasn’t been created yet. That’s the next step. What should I put in the method? Remember I only want to put in the most simple way to get the test to pass.


Which gives me this guy:


Right now you’re probably thinking that test is the programing equivalent of Master of the Obvious. I mean, of course it passes because it always returns 0. The next unit test might help with seeing the bigger picture:


Ok so now I’m testing:

If the list is null then throw ArgumentNullException

So naturally I have a test that expects an ArgumentNullException to be thrown. I don’t have that yet in the method though so the expected result when running the test is:


Boom. Go figure. Next step is to add only what is necessary to make the unit test pass.


Now you can see that I have added an exception to be thrown if the list is null. Time to run the tests:


Now I know that the method does take care of the first two requirements. From here I go requirement by requirement and create unit tests to make sure the requirements are met and have them all fail at first. After the test fails, add in the minimal amount of code necessary to get the test to pass.

Eventually you will have a working method that is completely covered.

You might be wondering why this site still exists but you might also be wondering why you should go requirement after requirement adding just what’s needed. The answer is actually simple: It lets you know exactly what changes you make breaks any other test. You see, if you were to do the normal “build the method and test” and there’s a test failing, it becomes harder to track down the issue since the method is now a bunch of code. Since there are multiple points of failure when you start writing the tests, tracking down a specific error is hard.

If you go requirement by requirement, test by test, you can easily find anything that breaks the created tests since you are only working one requirement at a time. I the first three requirements are met and tested when you work on adding the fourth and for some reason what you added to the method is breaking one of the successful test, you know exactly where the issue is.

I have the code here if you want to look at it as I’ve I’ve commented a lot of the code. It is in VS 2010 though. However I don’t think there’s anything that couldn’t work in 3.5.

I admit it’s kind of a different way of looking at it, but I found it incredibly useful in it’s simplicity.

MVC3, Entity Framework, jQuery… Everything example

How would you like to have a project that has these features?

Dependency Injection
Entity Framework 4.0 with POCO
Inversion of Control with Castle
The IResult
jQuery
jQuery Ajax Posts
jQuery Custom Css
jQuery Validation
Mocking with Rhino Mocks
MVC 3/Razor
MVC Annotation Based Validation
What I call the Repository Pattern
Unit Tests - Integration With Entity Framework
Unit Test - MVC Controller Actions

And more s--t I can't think of right now!

What’s the price of this gem? Just your time which is worth nothing!

Where can you find it? Right here!

Requirements:

Visual Studios 4.0
Mvc 3
To open the solution and do a search and replace on "Tutorial" to set your directory paths.
A real f--king need to learn!

Act now, operators aren’t in existence since this is hosted on a website, but if they were they would be standing by!

Disclaimer:

This may or may not hit you with a wave of awesome. Be prepared for the worse case awesome scenario. I am in now way responsible for any heart stoppage due to the shock and awe power of the project.

C#: Create Dynamic Image For Byte Array Data

So you have a unit test, but maybe for some reason you need to create an object that has a constructor that needs a byte array. Maybe for some reason that byte array needs to have more than 0 length. Maybe you don’t have any of this and you are just curious. Maybe I’ve said maybe too much.

Well in any case, here’s a way to do this:

using System.Drawing;
using System.IO;

    private byte[] GetBitmapData()
    {
      //Create the empty image.
      Bitmap image = new Bitmap(50, 50);

      //draw a useless line for some data
      Graphics imageData = Graphics.FromImage(image);
      imageData.DrawLine(new Pen(Color.Red), 0, 0, 50, 50);

      //Convert to byte array
      MemoryStream memoryStream = new MemoryStream();
      byte[] bitmapData;

      using (memoryStream)
      {
        image.Save(memoryStream, ImageFormat.Bmp);
        bitmapData = memoryStream.ToArray();
      }
      return bitmapData;
    }

And presto you have a fake image to send through. Can’t get much easier than that. Well maybe it could but not in this example. Why are you judging me? I’m just trying to help. You know what? Go away. I don’t want you around here anymore. You and those beady, judging eyes. Always looking… Never stopping… WHY DON’T YOU LEAVE ME ALONE?!?!?

Python / Pylons: Unit Testing a Controller And Unit Testing a Json Response

Nice thing about Python and Pylons is the complete lack of finds on the google. Basically anything you search on gets you the same 5 links… helpful or not.

This is a quick one though, and by quick I mean quick for you after it took me a f— load of time to get the f—ing thing right. Forgive me for swearing… even though I do it all the time… but in this case I really wanted emphasize how f—ing annoying it was to get this right.

So here’s the thing, you want to unit test a controller. Great. Now the nice thing is it’s actually pretty easy with what’s built into the TestController which is found in the __init__.py file in yourProject/tests. Imported simply by :

from yourProject.tests import *

Provided you didn’t move the tests folder.

Take the start of this method:

   def test_loginUser_bad_input(self):
          #Here is the call to the controller and the return response
          response = self.app.post(url(controller='security', action='loginUser', email='null', password='null' ))

Now here’s the interesting thing, response is actually a response object. Can you belee dat? At first I thought it was just whatever the controller method would return if called by a method and not during some web request. Turns out that self.app.post actually acts like a real request. Go f—ing figure. I like. So simple yet so capable. It’s like a long lost brother of mine. You know, the long lost brother that is simple yet capable… and is a method. I’m not sure any of that makes sense.

Now the second part of this debacle is how to work with a json response. For this example I am using jsonpickle but in reality the only thing to take from this is WHERE the stupid json actually is:

    jsonResponse = jsonpickle.decode(str(response.body))

Yeah so at first I thought it would be just jsonpickle.decode(response) but kept getting all sort of unhappiness. Now like I noted up top, the response is an actually object return that holds all sorts of information. (including header information.. yay?) So the next guess was what you see right above. Go figure what I was looking for was in the .body attribute.

See, told you it was simple. Painful for me, but in the end you win. And I bet you like that. Sadist f—.