Wednesday, July 14, 2010

Introducing Cone

NUnit is one of the most widely used and mature .Net Unit testing frameworks out there. Anyone doing TDD on .Net has heard of and probably used it. I've been tempted to use other excellent alternatives like MbUnit and someone once forced me to use Visual Studio Unit Testing Framework, the only good thing about that one is that the name tells you a lot about the experience. It's long, it's integrated, it's going the opposite direction of everyone else.

But for one reason or another I always come back to by old byddy NUnit. It's probably the familiarity and that the features that once did draw me to MbUnit like parameterized/data-driven tests are now available with NUnit.

All that being said, there's some stuff that always kinda irked me with NUnit, and most of the apply to the others to.

  1. Test cases are named after their fixture, not after the thing they're verifying.
  2. Nesting fixtures to provide context and logical grouping don't really work.
  3. Test names tend to duplicate part of the code since assertion messages tells me the values, but not how they were obtained

1) Test case names

The majority of unit-tests written are either targetting a single class, or targetting that class in some context. Fixture names tend to be akin to "FooTests" or "FooWhenBarTests" and are dutifully rendered as such often including a namespace with "Tests" in it. Quite typically it looks like this when looking at a single test case
Acme.Tests.BowlingTests.Score_should_return_0_for_gutter_game

Now that's just plain silly! Because what happens is that for every single such case we go and mentally remap the class under test to "Acme.Bowling", so why not show that instead? Maybe providing some extra context on the side?

2) Nested Fixtures

If you've ever tried to nest fixtures in NUnit to create a logical grouping for tests then you're familiar with testnames like
"Acme.Tests.FooTests+BarTests.oh_my_god"
oh, these also end up not being nested but as sibling to all your other tests.

3) Test Name duplicate assertions, because assertions only gives you the values

If you lean to classicist state based testing this happens quite a lot, in order to give enough context to make a failing test immediately obvious you either have to write a custom assert message or add something to your test name, depending on your asserts/test either works, both feels like a hack.

Since I'm having a vacation and renovating. I spent a few hours watching the paint dry and hacking a NUnit addin to solve those issues. The result, henceforth called Cone, solves those issues for the majority of cases. The picture below should give you a feel for how it looks and feel. Things worth noting:

  • Fixture names are derived from the Described type, not from the fixture name
  • Underscores are translated to whitespace to aid scanability
  • The actual failing expression "bowling.Score" is shown in the Assertion message
My initial experience have been very pleasant, but that could just be me being enamored with my own idea. That's where you come in. Please tell me what you think about the idea, is it worth persuing further and packing up properly and release it? If so, is there any obvious use cases that you couldn't live without?

Wednesday, May 5, 2010

The Fallacy of the Ever-Green Build

The fallacy of the ever green build is built on top of good intentions and hyperbole. Let's start with getting some of the preliminaries clear, these behaviors are strictly "not ok"
  • Checking in code that is known to be broken.
  • Not taking responsibility for fixing the build once broken, by yourself or by asking for help.
  • Not helping a team-mate stuck on how to fix the build.
Given that these clearly defective behaviors aren't present, and under the assumption that you have a normally stable build process and a decent enough build machine, the fastest machine affordable is a good advice. Then given the commandment "thou shalt never break the build" or "when you break the build God kills a kitten", most don't respond with enlightenment, they figure out "good" ways to not break the build:
  • Writing fewer tests, tests not present never breaks the build
    • prime example is not verifying behavior of common components or leaving them underspecified.
  • Delaying checkins far longer than necessary "to make sure", waste full since it squanders time that could have been used for better things
  • Not working, no work = no code = no broken build.
If you're using the fastest machine in the building to display a green light, you're not making good use of that investment. On the other hand, if you use it to find valuable but seldom occurring problems in a way that is less costly than the alternative then it's a good investment. That basically entails loosing up a bit on the "run every test we got! never break the build" in favor of "run the fast, high coverage tests most likely to yield sufficient certainty the soundness of your commit". There's learning to be had from every build failure, the only thing you learn from "green" is that you're probably hiding problems. Now I'm talking about a small controlled amount of high information build failures, missing files and not bothering to spend a couple of minutes to run the tests for the area just changed don't qualify.

Friday, January 8, 2010

Did I just μBDD in NUnit?

 

Have a look at this picture, what do you see?

uBDD-NUnit

 

Yup, that’s the old familiar “no frills we mean business and are professional about our testing” looking NUnit GUI. But have a look at the test names, they look like some dynamic-typing loving hippie wrote them! What are they doing in my NUnit!?

The answer is, they’re lending a BDD-like Given/When/Then flavor to our old workhorse, in a way that’s fully compatible and complementary to the standard NUnit model. Does it require magic and fairy-dust? Nope not really, just some creative use of the TestCaseDataSource attribute, the test fixture looks like this:

uBDD-Fixture

GWT doesn’t always make sense, but when it do it can lead to some really communicative tests.

If you want the small (~40 lines) source for the Scenario class just leave a comment.

Tuesday, November 17, 2009

Visual Resharper

I've been using Visual Studio 2010 Beta 2 at home for a while and truly it really rocks. But something has been nagging me, there just seems to be so much stuff borrowed from everyones favourite plugin, Resharper. And I belive I've found the reason. If you take a screenshot of the new logo and reverse the red and blue channels something quite familar appears.

Wednesday, November 4, 2009

How to reset registry and file permissions.

If you somehow manage to get into trouble with registry or file permissions and feel that the only sane way out would be to reset them. Here's the magic incantation to put into the black box:
secedit /configure /cfg %windir%\repair\secsetup.inf /db secsetup.sdb /verbose

Friday, July 10, 2009

Using NUnit with VS2010 Beta and .NET Framework 4.0

I've been test driving Visual Studio 2010 Beta recently and it comes with, and defaults to, .NET Framework 4.0, exciting stuff all around until you realize that if you target the 4.0 Framework you end up with this when trying to run your tests. Let's call this, less than helpful. Some googling turns up one solution, rebuild NUnit from source. Now while that is a viable solution you should never just go for the first solution that enters your mind. After some pondering I came to think of the metadata storage signature defintion present in all .NET Assemblies and how it actually does contain the desired framework version.

Using your hexeditor of choice (I like XVI32) simply open "nunit.exe" and search for "v2" it should turn up something like the screenshot below:

Notice the "BSJB" just preceding the version string, that's the metadata signature basically telling us we're in the right place. Now change "v2.0.50727" into "v4.0.20506" save and start NUnit. It will now run under the 4.0 framework instead, happily running your tests.

Oh, if you think that't both rebuilding from source, and hacking metadata is maybe not really "the right solution (tm)" you could just configure it instead.

Sunday, July 5, 2009

Thinking in context.

There has been som general hubbub about establishing WIP limits in the Kanban community latly, some have gone so far as to claim that it is wasteful. Or more exactly that they are wasteful since if you're mindfull you can see the same bottlenecks without them. And theoretically I think that is true. But this is one of thoose times theory just won't help.

In my, not so humble, oppinion establishing WIP limits helps us the same way a budgets do. It help us set clear priorites and makes us think about our general goals. It also works as a clear leading indicator for when things are getting out of hand. One could make the claim that having a budget is waste, and if you're really disciplined I guess that is a viable option. But for me, it's not that I strictly need it, it's just way simpler than the alternatives.

Twitter via @hiranabe provided this gem: Kuroiwa-san(ex-Toyota mgr) concluded speech by emphasizing "Thinking for yourself in your context" is the heart of Lean

This is another very tangible postive effect of imposing limits, they help us establish context. The heart of lean and agile processes is thinking in context, anything that helps us faster establish context and be present have a great positive impact on the speed of communication. Thereby helping us improve, reflect, adjust and evaluate. That in turn helps us deliver more value faster, and sustain those improvements over time.

Thinking is not the key, thinking about the right stuff is. Establishing context is vital for that.

Tuesday, June 30, 2009

Ownership, Responsibility and Sharing.

Im a big fan of collective code ownership. This is my attempt to clear up one common point of confusion. Responsibility does not imply ownership. Making everyone responsible for the whole codebase most often fails miserably for the same reasons very few can keep any sufficently large system wholy in their heads. If everyone is responsible, most often nobody or a select few is. My current thinking about this is that people should be responsible for a slice of functionality or a module depending on your circumstances. But they're responsible, they don't own it. Anyone can, and should be encouraged to, change the code. The responsible guardian for that part should monitor changes, clarify conceptual missunderstandings, know his part of the system on a sufficent depth to be able to detect at a structural and conceptual level when duplication is creeping in to other parts of the system. Having responsibility does not mean soly working on that part, it means shepherding it and making sure that peers adhers to agreed conventions.

I've seen tremendous benefits from this, it lets people get really good at one part of the system, giving them both pride and the ability to at a much deeper level draw parallels to other parts during pairing sessions and work on other parts. It avoids the "everyone knows almost nothing about everything"-problem thereby reducing waste due to relearning and rediscovery. It sets expectations and builds team spirit, if we know that someone will be checking our work we tend to take greater care. And noone want to let a team-mate down. Theese effects augument conventional practices like pair programming in a very positive way.

Thursday, June 25, 2009

Wednesday, May 27, 2009

Microsoft - You're doing it right!

I'm generally not known for being a big Microsoft fanboy. But I have to say that my recent experinces have left me happy. I've been using the F# CTP since it came out and currently running the Visual Studio 2010 beta. Both are great products but that's not what this post is about.

This post is about how pleased I am with their handling of submitted bugs. The F# team is extremly friendly, quick to respond and equally good at providing updates and responding in a timely manner. Maybe not shocking given that it seems to be a small dedicated team. What mandates this post is that the VS2010 beta team also exhibits theese qualities. Submitting a bug is easy and painfree and they seem to be handled in a very good manner providing timely updates as it flows through the process.

So all thumbs up for the awsome F# and VSEditor teams!

Friday, April 24, 2009

Fake - The future of .NET build tools?

Tired of XML based build systems?
Thought so. That's why I spent a few minutes hacking togheter the basis for my own build system. I call it Fake. And looks like this:
let clean = task "Clean" (fun () ->
    Console.WriteLine("Cleaning."))

[<Default>]
let build =
    task "Build the lot" (clean => fun () ->
        Console.WriteLine("Building.."))

let loadTestData =
    task "Load some test data" (fun () ->
        Console.WriteLine("Loading test data..."))

let test =
    task "Test it" ([build; loadTestData] => fun () ->
        Console.WriteLine("Running Tests...."))
Then simply
x:\..\>fake test
Cleaning.
Building..
Loading test data...
Running Tests....
x:\..\>
Is this idea worthwhile? Tell me in the comments.

Tuesday, April 21, 2009

Team Foundation vs Subversion and Bazaar - Round 1: Update my workspace.

I usually work with Subversion or Bazaar but currently I'm on a project using Team Foundation Server. Today I got the silly idea of updating my workspace using the command line interface. Assuming that you are standing in the directory you want to update this task can be accomplished as follows:
SubversionTeam Foundation
svn uptf get .\* /version:T /recursive
Now one of theese is sane, the other is complelty insane. I won't tell you wich is wich.

Wednesday, April 8, 2009

RED - Re Evolutionary Development

Something is happening in devloperland, if you put your ear to the tubes of the blogosphere you can hear a faint message. The Software Craftmanship movement is gathering momentum with a simple message, and one of the high priests of XP has abdicated.

There's a new focus comming and it cuts right through all excuses, the message is simple.
YOU are responsible.

No one else is going to give you the mandate to work in a fashion you know you really ought to, no one else is going to educate your peers for you, and no one else is going to fix your broken process. Yes I know it's horrible. The business demands the impossible and your cow orkers are all a bunch of imbicils. That's exactly why it's your problem. You're the only sane, educated, competent, levelheaded person around, it's your responsibility to do something about the madness.

We need to stop trying to blame everyone else for our problems, we need to stop discussing what's wrong with "other people" and actually start taking action. Every single day, strive to improve, learn and share!

I'll dub this "Re Evolutionary Development" or RED for short and as all good philosophies it needs a set of principles the first one simply is:

RED Principle #1

Each day ask yourself.
  • What did I learn?
  • What did I share?

Monday, March 9, 2009

The Care and Feeding of your Build - Stability.

Having an automated, fast, repeatable build provides the heartbeat of the project. Sadly it's often neglected and viewed as tedious to set up, boring to maintain and the only time it actually does get any attention is when it doens't work. Good build systems exhibit a few key charecteristics, today Im going to talk about one of the finer points, stability.

What is stability?

The stability of a build can be stated as:Unless something changed, do nothing.
Or as Ant best practices item "14. Perform the Clean Build Test" puts it:

Assuming your buildfile has clean and compile targets, perform the following test. First, type ant clean. Second, type ant compile. Third, type ant compile again. The third step should do absolutely nothing. If files compile a second time, something is wrong with your buildfile.

Why stability?

Stability is important since it has a direct effect on the length of your build/test cycle. Any inefficency introduced grows both with the project and with the number of team members. This means that unless you keep your build stable every compile will cost you a small amount of time, for every team member, over time this adds up to substantial amount.

Easy ways to fail.

There's a few ways that almost every build system I've worked with failed the stability test the most common offenders I've found are.

Unconditional Post Build xcopy

It's often convinent and sometimes neccessary to copy output files to some other directory. Often this is done to create smaller solutions/projectfiles for the IDE and more stable projects are simply built and copied to a folder with precompiled binaries and referenced from there. This is a good strategy. The problem arise when the copy is unconditional since this often forces a rebuild of all dependent projects even though the shared library did not change! If you're using Visual Studio, unless you got a really really good reason always use "When the build updates the project output" option for "Run the post-build event:". If you're using Ant/NAnt/Rake/ and have a target that does compile+copy always check before copying.

Unguarded build targets

Common offenders in this category is test/coverage targets, creation of installation packages and "zip tasks", care should always be taken to ensure that something actually did change before redoing theese procedures. Often this can be accomplished by comparing timestamps for the source and destination files. If no tangible output is generated by default it can make sense to introduce a marker file and touche it on completion of the task.

Summary

Keep your build fast by avoiding redundant work, take care to never do work unless something actually did change.

Saturday, March 7, 2009

Manifesto for Software Craftmanship

Ever felt that there's something missing from the Agile Manifesto? Feeling left out in all the management fluff? Ever wondered, but where's the focus on my craft? I sure have.

There's a old, new, movement on the raise, a movement for software craftmanship. Sign the Manifesto for Software Craftmanship and help us raise the bar.

Saturday, February 21, 2009

Pizza Points - story estimation made round!

There's two commonly used methods for agile estimation Story Points and Ideal Programming Somethings, commonly days or hours. Both methods have their merits with some bias towards Story Points (SP) from Mike Cohn and various other well known names although Ideal Programming Somethings seems to be more commonly used by the teams I've spoken to.

There seems to be quite a bit of confusion regarding how they relate and how both terms relate to hours. To remedy some of this I want to propose a new system, Pizza Points, that is driven by an easy to explain intuitive and rich metaphor.

Lets look at the similarities between work and pizza as used in the following discussion.

  • Pizza is round, work tends to be circular.
  • Pizza can be filling and deeply satisfying, as can work.
  • Pizza comes in different sizes, as does stories and tasks.
  • Pizza can have lots of varying and interesting fillings, work can be filled with many intresting things.
  • As we mature we can eat more pizza and as we learn a domain and tools we can tackle bigger tasks.

Depending on the peculiarities of your favourite pizza parlour the size and form may vary, maybe you have children, normal and family, maybe the range is small, medium, large, and extra-large often it's round and sometimes you get oddly square bites. There's no guarantee that a small pizza is the same size between to different places and there's likewise no sense in assuming that a pizza point is equally sized between two teams. That said, if you stick to one place, keep your team intact, any given size will overtime be quite consistent.

So how do we get started using Pizza Points?

We have to start by establishing some sort of baseline size, no diffrent from the initial sizing of story points. Find a fairly small, easily graspable story discuss the criterias for done and label it "children", "small" or why not, one. Continue estimation by thinking about the relative *size* not filling, give them descriptive names, standard, family, 2, 3, 5, 8, 13, 20, 40, 100, xxx-large.

It's as easy as that. The thing to remember is that size is actually a constant but the filling might greatly influence how much we can eat. I like pizza and can eat quite a lot given toppings like different cheeses, ham, pineapple for example. Give me anchovies and you'll have me struggling an evening to come close to finishing even a child size bite. The size haven't changed, my aptitude and motivation did.

If you're the one placing orders and want to get as much pizza eaten as possible during any period of time it can be wise to ask your team for their taste preferences. But real life sometimes dictates that we put anchovies on their plate, that's a big responsibility.

To summarize, think size not filling, match fillings to team, expect size to vary depending on team. Also expect mature, adult, teams to eat more than children.

And don't forget to order planning pizza as a reminder during long estimation sessions.

Monday, February 9, 2009

The story about TypeMock.

To mock or not. That's the question. Here's how I think some BDDers and Mockists labled their Kool-Aid before drinking it.

Given TypeMock
When I want to test
Then everything looks like a mock object.

Tuesday, February 3, 2009

Pencil.Unit and Micro Lightweight Unit Testing

Joe Armstrong of Erlang fame has the following to say on how he write unit tests Micro Lightweight Unit Testing
Here's a condenced retrace of his steps using F# and Pencil.Unit
Step 1) Write Micro Unit Test
Theory "Fib should work for known values from Wikipedia"
    [(0,0); (1, 1); (2, 1); (3, 2); (20, 6765)]
    (fun (n, e) -> Fib n |> Should Equal e)
Step 2) Implement Fib
let rec Fib = function
    | 0 -> 0
    | 1 -> 1
    | _ as n -> Fib(n - 1) + Fib(n - 2)
Step 3) Theorize about FastFib
Theory "FastFib should give same result as Fib"
    [0; 1; 2; 3; 25]
    (fun n -> FastFib n |> Should Equal (Fib n))
Step 4)Implement FastFib
let FastFib n =
    let rec loop n a b =
        match n with
        | 0 -> a
        | _ -> loop (n - 1) b (a + b)
    loop n 0 1

Monday, February 2, 2009

Taking Pencil.Unit for a spin, F# syntax highlighting.

Decided to take the current iteration of the testing code posted earlier for a spin by trying to actually build something usefull with it. Since Im yet to find a decent syntax highlighter that supports F# and doesn't generate utterly disgusting HTML I decided to try to test and hack my way to one that at least suits my quite humble needs. The result was this:
(* Building a (very simple) syntax higligher with Pencil.Unit *)
#light

open System
open System.Text
open System.IO
open Pencil.Unit

type Token =
    | Comment of string
    | Keyword of string
    | Preprocessor of string
    | String of string array
    | Text of string
    | WhiteSpace of string
    | NewLine
    | Operator of string

let Classify x =
    match x with
    | "abstract" | "and" | "as" | "assert"
    | "base" | "begin"
    | "class"
    | "default" | "delegate" | "do" | "done" | "downcast" | "downto"
    | "elif" | "else" | "end" | "exception" | "extern"
    | "false" | "finally" | "for" | "fun" | "function"
    | "if" | "in" | "inherit" | "inline" | "interface" | "internal"
    | "lazy" | "let"
    | "match" | "member" | "module" | "mutable"
    | "namespace" | "new" | "null"
    | "of" | "open" | "or" | "override"
    | "private" | "public"
    | "rec" | "return"
    | "static" | "struct"
    | "then" | "to" | "true" | "try" | "type"
    | "upcast" | "use"
    | "val" | "void"
    | "when" | "while" | "with"
    | "yield" -> Keyword x
    | _ when x.[0] = '#' -> Preprocessor x
    | _ -> Text x

let IsKeyword = function
    | Keyword _ -> true
    | _ -> false

let IsPreprocessor = function
    | Preprocessor _ -> true
    | _ -> false

Theory "Classify should support all F# keywords"

    ("abstract and as assert base begin class default delegate do done
    downcast downto elif else end exception extern false finally for
    fun function if in inherit inline interface internal lazy let
    match member module mutable namespace new null of open or
    override private public rec return static struct then to
    true try type upcast use val void when while with yield"
    .Split([|' ';'\t';'\r';'\n'|], StringSplitOptions.RemoveEmptyEntries))

    (fun x -> Classify x |> IsKeyword |> Should Equal true)

Fact "Classify should treat leading # as Preprocessor"
    (Classify "#light" |> IsPreprocessor |> Should Equal true)

let Tokenize (s:string) =
    let start = ref 0
    let p = ref 0
    let next() = p := !p + 1
    and hasMore() = !p < s.Length
    and sub() = s.Substring(!start, !p - !start)
    and current() = s.[!p]
    and prev() = s.[!p - 1]
    let peek() = if (!p + 1) < s.Length then
                    s.[!p + 1]
                 else
                    (char)0
    and isWhite() =
        match current() with
        | ' ' | '\t' -> true
        | _ -> false
    and isOperator() = "_(){}<>,.=|-+:;[]".Contains(string (current()))
    and isNewLine() = current() = '\r' || current() = '\n'
    let notNewline() = not (isNewLine())
    and notBlockEnd() = not(current() = ')' && prev() = '*')
    let inWord() = not (isWhite() || isNewLine() || isOperator())
    let read p eatLast =
        while hasMore() && p() do
            next()
        if eatLast then
            next()
        sub()
    let readWhite() = WhiteSpace(read isWhite false)
    and readNewLine() =
        next()
        if isNewLine() then
            next()
        NewLine
    and readWord() = Classify(read inWord false)
    and readOperator() = Operator(read isOperator false)
    and readString() =
        let isEscaped() = prev() = '\\'
        let inString() = isEscaped() || current() <> '\"'
        next()
        let s = read inString true
        String(s.Split([|'\r';'\n'|], StringSplitOptions.RemoveEmptyEntries))
    seq {
        while hasMore() do
            start := !p
            let token =
                match current() with
                | '\"' -> readString()
                | '/' when peek() = '/' -> Comment(read notNewline false)
                | '(' when peek() = '*' -> Comment(read notBlockEnd true)
                | _ when isWhite() -> readWhite()
                | _ when isOperator() -> readOperator()
                | _ when isNewLine() -> readNewLine()
                | _ -> readWord()
            yield token}

let ToString x =
    let encode = function
        | Comment _ -> "c"
        | Keyword _ -> "k"
        | Preprocessor _ -> "p"
        | String _ -> "s"
        | Text _ -> "t"
        | WhiteSpace _ -> "w"
        | NewLine -> "n"
        | Operator _ -> "o"
    x |> Seq.fold (fun (r:StringBuilder) -> encode >> r.Append) (StringBuilder())
    |> string

Fact "Tokenize should categorize"(
    Tokenize "#light let foo" |> ToString |> Should Equal "pwkwt")

Fact "Tokenize should handle string"(
    Tokenize "\"Hello World\"" |> ToString |> Should Equal "s")

Fact "Tokenize should split string into lines"(
    let lines = function
        | String x -> x
        | _ -> [||]
    Tokenize "\"Hello\r\nWorld\"" |> Seq.hd |> lines |> Seq.length |> Should Equal 2)

Theory "Tokenize should separate start on operators"
    ("_ ( ) { } < > [ ] , = | - + : ; .".Split([|' '|]))
    (fun x -> Tokenize x |> ToString |> Should Equal "o")

Fact "Tokenize should end on separators"(
    Tokenize "foo)" |> ToString |> Should Equal "to")

Fact "Tokenize should handle escaped char in string"(
    Tokenize "\"\\\"\"" |>  ToString |> Should Equal "s")

Fact "Tokenize should handle //line comment"(
    Tokenize "//line comment" |> ToString |> Should Equal "c")

Fact "Tokenize should handle (* block comments *)"(
    Tokenize "(* block comment )*) " |> ToString |> Should Equal "cw")

Fact "Tokenize should handle newline"(
    Tokenize "\r\n" |> ToString |> Should Equal "n")

Fact "Tokenize should separate whitespace and newline"(
    Tokenize "    \r\n" |> ToString |> Should Equal "wn")

let Sanitize (s:string) = s.Replace("&", "&amp;").Replace("<", "&lt;").Replace(" ", "&nbsp;")

Fact "Sanitize should replace < with &lt;"(
    Sanitize "<" |> Should Equal "&lt;")

Fact "Sanitize should repalce & with &amp;"(
    Sanitize "&" |> Should Equal "&amp;")

Fact "Sanitize should repalce ' ' with &nbsp;"(
    Sanitize " " |> Should Equal "&nbsp;")

type IHtmlWriter =
    abstract Literal : string -> unit
    abstract Span : string -> string -> unit
    abstract NewLine : unit -> unit

let HtmlEncode (w:IHtmlWriter) =
    let span style s =
        w.Span style s
    function
    | Comment x -> span "c" x
    | Keyword x -> span "kw" x
    | Preprocessor x -> span "pp" x
    | String x ->
        span "tx" x.[0]
        for i = 1 to x.Length - 1 do
            w.NewLine()
            span "tx" x.[i]
    | Operator x -> span "op" x
    | Text x | WhiteSpace x -> w.Literal x
    | NewLine -> w.NewLine()

let AsHtml s =
    let r = StringBuilder("<div class='f-sharp'>")
    let encode = HtmlEncode {new IHtmlWriter with
        member this.Literal s = r.Append(Sanitize s) |> ignore
        member this.Span c s = r.AppendFormat("<span class='{0}'>{1}</span>", c, Sanitize s) |> ignore
        member this.NewLine() = r.Append("<br>") |> ignore}
    Tokenize s |> Seq.iter encode
    string (r.Append("</div>"))

Fact "AsHtml sample"(
    let sample = "#light\r\nlet numbers = [1..10]"
    let expected =
        String.Concat [|"<div class='f-sharp'><span class='pp'>#light</span><br>"
        ;"<span class='kw'>let</span>&nbsp;numbers&nbsp;<span class='op'>=</span>&nbsp;"
        ;"<span class='op'>[</span>1<span class='op'>..</span>"
        ;"10<span class='op'>]</span></div>"|]
    sample |> AsHtml |> Should Equal expected)

//Render myself.
File.ReadAllText(__SOURCE_FILE__)
|> AsHtml |> (fun x -> File.WriteAllText(__SOURCE_FILE__ + ".html", x))
As outputed from itself. I really like how "Fact" and "Theory" turned out and it seems to suite my current needs just fine.

Friday, January 30, 2009

Fact about Pizza.

I find this test as amusing as it's silly:
#light

open Pencil.Unit

Fact "Pizza should have cheese."
    ("Pizza" |> Should (Contain "Cheese"))
And the output:
Pizza should have cheese. Failed with "Pizza" doesn't contain "Cheese".