Crayon syntax highlighter

I’ve tried to install a couple of different syntax highlighters in the past and was thoroughly unimpressed. They either failed to install cleanly, didn’t work or had numerous issues that rendered them useless.

Anyway, after manually formatting source code snippets for years, I’m giving Crayon a go. The install was easy and the output looks good. Let’s see how we go :-)

You can find it here: https://wordpress.org/plugins/crayon-syntax-highlighter/

The fundamentals of unit testing : draw attention to ‘interesting’ values

3 is the magic number? No. No, it’s not. Magic numbers/strings/other values in all walks of programming are a readability and maintenance liability. It’s quite common to see all kinds of literals being littered through test code. It’s quite easy to simply switch off and treat test code as a second class citizen.

To illustrate this point, please tell me what this does

[Test]
public void TestInvalidFuelAmount()
{
    // Arrange
    var car = CreateLittleCar();

    // Act & Assert
    var exception = Assert.Throws<ArgumentException>(() =>  car.AddFuel(500));
}

It’s not exactly crystal clear, is it? Although the naming of this test can and should be improved, bear in mind that it’s an extremely simple case (one method call with one argument being passed). Despite this, the intent is still obscured because of a literal.


Replace literals with named consts

Let’s change 500 to a named constant. Let’s also change the test name while we’re at it.

[Test]
public void when_the_car_fuel_tank_capacity_is_too_low_and_fuel_is_added_an_exception_is_thrown()
{
    // Arrange
    var car = CreateLittleCar();
    const int LitresOfFuelThatIsTooLargeForTankCapacity = 500;

    // Act & Assert
    var exception = Assert.Throws<ArgumentException>(() => 
            car.AddFuel(LitresOfFuelThatIsTooMuchForTankCapacity));
}

Now that’s much clearer. We can see what the value represents, the units it’s measured in and its place in the test. Some people shit the bed when they see really long story-like variable names in tests, but they’re generally a help, not a hindrance.

While the previous example is simple, this tip makes much more of a difference in situations where a function/method/constructor has numerous parameters, but the test is largely focused on only one of them. How do you know which one to pay attention to?

[Test]
public void when_account_balance_is_low_money_transfers_fail_when_would_be_overdrawn()
{
    // Arrange
    var currentAccount = GetCurrentAccountWithBalanceInUSD(10);

    // Act    
    bool transferSucceeded = currentAccount.TryTransfer(1000, 42, 602402);

    // Assert
    Assert.That(transferSucceeded, Is.False);
}

Fine, this is a crufty-looking API, but in certain circumstances, it’s quite common to see functions/constructors that take multiple arguments of a similar type. At a glance, how can you tell which of the arguments is the one of interest to the test? Is it 1000, 42 or 602402? What is the significance of any of them? Which one is causing the transfer to fail?

Let’s use a named const to draw attention to the interesting argument.

[Test]
public void when_account_balance_is_low_money_transfers_fail_when_would_be_overdrawn()
{
    // Arrange
    var currentAccount = GetCurrentAccountWithBalanceInUSD(10);
    const int AmountInUSDThatWillForceAccountIntoOverdraft = 1000;    

    // Act    
    bool transferSucceeded = currentAccount.TryTransfer(AmountInUSDThatWillForceAccountIntoOverdraft , 42, 602402);

    // Assert
    Assert.That(transferSucceeded, Is.False);
}

Turns out the 42 is the number of cents in the transfer, and that 602402 is just a dummy customer number we’re passing through.

We can go further than this to clean things up still further by doing things such as:

  • Extract a wrapper test method that calls TryTransfer, but only has one parameter: the amount of USD to withdraw (the other parameters can be satisfied with constants). This draws attention to the important part of the test (varying the value of the USD transfer amount) and also helps insulate the tests from changes to the TryTransfer method.
  • In the production code, using types that are more appropriate to reduce ambiguity (e.g. in the case of a customer account number, an AccountCredentials class would be more suitable than an int!)
  • Finally, if lots of things are changed in the tests, but in slightly different ways each time, consider the use of a Test Data Builder. Test data builders are very useful, as the provided defaults are sensible for most cases. As a result, when arranging your test, the only things that are changed in the builder are the things that actually matter. Test data builders can also insulate the tests from breaking changes.

The fundamentals of unit testing : Arrange, Act, Assert

Arrange, Act, Assert” (aka “AAA”) is a very simple way to structure your tests – I thoroughly recommend it. It is especially helpful when learning the ropes.

For this post, I’ll use the following example test scenario: When a stack is empty, pushing an item increments the count to one (this example was previously discussed in Narrow & Focused, if you want more context)

[Test]
public void pushing_an_item_onto_an_empty_stack_increments_count()
{
    // Arrange
    var stack = new Stack<bool>();

    // Act
    stack.Push(false);

    // Assert
    Assert.That(stack.Count, Is.EqualTo(1));   
}

Each ‘phase’ of the test happens in order and occurs precisely once. Arrange precedes Act, Act precedes Assert. I’ll go into a little more detail later as to why this is a useful property.

A brief description of each “A” follows.

Read more »

Integer to binary string in c#

Python has the terribly useful functionality of bin() to do this, but what about C#?

On the rare occasion I have to monkey around with bitwise operators, I always keep this handy. It has the added bonus of printing the leading zeros – I find this very useful when writing/debugging bitwise code, as it makes it easy to line up bitmasks etc. in the immediate window / console.

public static class BinaryPrinter
{
    public static string ToBinaryString(long _long)
    {
        // have to do this or it won’t print the leading 0 values       
        return Convert.ToString(_long, 2).PadLeft(sizeof(long) * 8, ‘0’); 
    }
}

Similarly, you could write a few of these (for all of the various inbuilt types) and chuck them in extension methods.

Python 3.4 and the three P’s: pyvenv, pip & pycharm

Pip

… is a nice little package manager for Python, but it was somewhat hamstrung by the clunky install procedure in Python 2.X and early versions of Python 3. With Python 2.x, you’d have to do something like use curl to get setuptools, then use easy install to get pip, then use pip to install packages. Happily, 3.4 now includes pip by default.

Pyvenv

… is a virtual environment manager. Rather than installing packages in your site-packages directory (modifying your python environment – something that is a bit sucky when you have conflicting needs for different projects), developers have traditionally used virtualenv. In Python 3.X, you can use pyvenv instead and it seems to Just Work™.

All Together Now

On Windows, getting pip and pyvenv working together is pretty simple, but I had a little trouble finding the bare minimum “getting started” documentation, so here’s a version for frantic googlers.

First, set up a virtual environment using pyvenv:

Open a command prompt in the directory you’d like to create the virtual environment, then run the following command:

> C:\your_python_dir\python C:\your_python_dir\Tools\Scripts\pyvenv my_env_name

Then, run:

> my_env_name\Scripts\activate.bat

This will give you a command prompt with the environment name prepended to signify that it’s active.

At this point, you can start installing stuff with pip!

> pip install beautifulsoup4

image

Not bad. Much simpler than in olden times.

A bonus – PyCharm & pyvenv

PyCharm is my IDE of choice for python editing and it comes with a lot of niceties, including allowing you to associate projects with specific python interpreters. Even better, PyCharm allows you to associate a project with a particular virtual environment, too!

I’m running v3.0 of PyCharm at home, so I can’t speak for earlier versions. To associate a virtual environment with your project, click File –> Settings, then find “Python Interpreters” under “Project Interpreter”.

image

Click the + at the top right hand pane of the window, then select “Local”. Navigate to the virtual env directory you just created, then find the Python executable under the scripts dir.

image

You can now associate this virtual environment with your project. PyCharm automatically switches it up when you load your projects. No more cross contamination of packages!

Python data-driven testing, ddt and @unpack

Several eons ago, I wrote a blog post about using the python ddt package. My only criticism was that you had to manually pack/unpack the test case arguments.

Happily, the developers of ddt were nice enough to add an @unpack decorator! You can now provide lists/tuples/dictionaries and, via the magic of @unpack, the list will be split into method arguments.

Documentation is here: http://ddt.readthedocs.org/en/latest/example.html

Empathetic Code

I always liked the phrase, “if you’re incapable of empathy, then you shouldn’t be designing APIs”.

I’ve worked with some terrible libraries in the past and the worst ones all had a common design flaw: the author didn’t put themselves in the user’s place. Worse still, sometimes the author just didn’t give one. When someone using the code pointed out that something was hard to understand or didn’t make sense, they were met with a snarl and shouted down; “it makes sense; you’re just using it wrong”.

On the other hand, I’ve occasionally picked up libraries/frameworks that make an extra effort to guide you along the correct path. The author of the code understood where users were likely to stumble.

image

It doesn’t matter whether it’s a carefully designed API you’re crafting for external use or internal code that will only be viewed and modified by engineers inside the company, you can always do something extra, especially if it’s something that’s already tripped you up.

If you encounter a gotcha, why not write a bit of code to clearly document the case, particularly if it is time-consuming to debug in the first place?

Read more »

Benq XL2411T Monitor Review

Before I review the Benq, it’s worth giving a bit of background about the monitors I’ve owned up till now.

Dell P1110

image

My first ‘serious’ bit of monitor kit was a Dell P1110 21” Trintron ‘Flat Screen’ CRT (it was flat screen in the sense that it wasn’t a fishbowl and the viewable area was only 19.8” – how the advertisers got away with this for so long always mystified me). The P1110 could easily pump out 100hz and beyond at anything below 1600×1200. It was circa ~2002 and I was a poor student, so I picked it up refurbished for a couple of hundred quid, half-expecting to get ripped off or scammed.

Best purchase ever.

Read more »

A R#/Visual Studio style keymap for PyCharm

PyCharm is a lovely little IDE for Python by the splendid JetBrains, but the built-in Visual Studio keymap is not much like the default VS/R# settings I’m accustomed to. I’ve rustled up a quick version that restores all of the easy to remember refactoring key combinations (Ctrl-Shift-R, Ctrl-R, Action Key etc.) along with some of the common navigation ones (Ctrl, comma for recent files and so forth).

There’s a few things missing and I’ve unbound some of the PyCharm functionality as it clashed with the R# style keymap, so your mileage may vary. Give it a try, though!

You can download it here: http://defragdev.com/files/RStyle.xml

The fundamentals of unit testing : Tests shouldn’t ape the production code

Aping the logic of the class under test is an bad idea when writing tests, but it’s an easy mistake to make.

Aping… Bueller?

"Aping" simply means imitating/repeating the logic used in the class under test. In its simplest form, the problem can be illustrated like so:

Production code:

public class Calculator
{
        public int Add(int a, int b)
        {
                return a + b; // actual logic of the class under test
        }
}

A test for the above class:

[Test]
public void adding_two_numbers_returns_the_sum()
{
        // Arrange
        var calculator = CreateCalculator();

        // Act
        int result = calculator.Add(1, 2);

        // Assert
        Assert.That(result, Is.EqualTo(1 + 2)); // ape alert, ooh ooh ooh! >:O
}

Although this doesn’t look like the end of the world, we can see that the test method line "Assert.That(result, Is.EqualTo(1 + 2))" is directly replicating the logic in the Add method.  This is “aping”.

Why is this a bad thing?

This is bad for a few reasons. Firstly, if the class under test is bugged and the test apes its logic to get an expected answer, we’ve just reproduced the bug in our test code and erroneously passed the test. So, instead of having working production code, we have two bits of bugged code and a false sense of security.

Secondly, when writing tests, if state can be tested, it should be done using as declarative a style as possible — we don’t want to say how we get to the answer, just what it should be.

I don’t want to see the test code literally add 1 and 2 to get 3. Instead, I want to see 3 in the test.  Here’s a fixed-up version of the test that does not ape the production code:

[Test]
public void adding_two_numbers_returns_the_sum()
{
        // Arrange
        var calculator = CreateCalculator();

        // Act
        int result = calculator.Add(1, 2);

        // Assert
        Assert.That(result, Is.EqualTo(3));   
}

You should always scan your test code looking for this anti-pattern.  The example I’ve cited is very simple, but I’ve seen a lot of real world code that has succumbed to aping the production code resulting in bugs going undiscovered.

Validating your answers

You may be thinking, “OK genius, so you skipped adding 1 and 2 in the test code, but you must’ve known to follow the addition algorithm in your head to be able to come up with the answer of 3.  How do you know your brain didn’t get it wrong and the test is bugged?” 

It’s a good question and the truth is, it’s often the case that it’s not clear-cut.  However, there are steps you can take to validate your answers (or at least be a little more sure of them).

  • Don’t just assume you’ve got it right first time.  Double check it for a few minutes more.
  • Write out some notes on paper (I sometimes do the testing version of truth tables).
  • Maybe you have a specification for this particular part.  Use it to check the answer  (stop laughing at the back, there! – it occasionally does happen; e.g. conventions for a maths library).
  • Use an alternative method to come up with the same answer (it’s often the case that the same value can be calculated via multiple algorithms / schemes).
  • Use an existing implementation to corroborate your findings.  E.g. if you’re writing a test to make sure that JSON is validated correctly, then check that JSONLint.com agrees with your test results.
  • If you’re not sure how to corroborate an exact answer, then check any invariants you’re aware of as a smoke test.  If any of the invariants don’t hold, your answer is probably wrong.