RSS
Facebook
Twitter

Monday, June 10, 2013

Tip: Using Notepad++ to read log files

I had to read a log file containing a few hundred lines today at work.

My first instinct was to open it using my trusty Notepad++. While the file was not huge it was still difficult to traverse it and my eyes kept jumping between lines. Finding the  errors and warning was proving to be a hard task.

Since each line started with the severity of the message (trace/debug/info/warning/error) all I was missing was basic text highlighting – now where can I find such a tool :)

image

 

I’ve set out for work - the only question being – how hard would it be (spoiler: easy).

 

Step 1 – under Language choose Define your language

image

 

A new dialog will be opened. If you prefer you can dock it to the screen.

Choose Keywords tab

image

 

Define new keywords for Error, Warning  and any other severity you wish to highlight.

Choose the Styler button and set custom background (or foreground) for each severity.

image

 

And finally use Save as and name your new “language” – and a new language is born.

image

 

This is what the log looks like now – easy to read and spot the errors. I only wish I could have marked the whole line but at least now I can tell where the errors are.

image

 

Not too bad for less than one minute of work.

Tuesday, June 04, 2013

In search of a Better Place

Leave by inf3ktion, on FlickrLast week the company I was employed at went bankrupt. It was the end of a long process which started about a year ago. It was a sad experiencer - I believed in the company and its goals. I hoped that the company’s amazing vision would become reality - and it did for a while.

Don’t feel too sorry for me - the truth is that I was looking for the next challenge for some time now, and I had problems deciding what to do next.

During my career I’ve worked for both big corporates and small start-ups. I’ve developed all sorts of applications and enjoyed it.

It took me a few job interviews to find a place I’d like to work for. Then I did a few more job interviews just to make sure that this is what I want…

 

During the time I’ve worked of my last employer things have changed. C++ 11, .NET 4.5 (soon to be 5) and windows without a start button (to be returned) – I felt left out, I wanted to use all those cool new technologies. And so I’ve looked for a place of work where I will learn the latest & greatest always on the bleeding edge of technology while keeping my old skills in practice.

In short after looking at a few options I’ve decided that it’s time to give advices professionally, in short - I’m a consultant!

I’ve signed up with CodeValue, and I’m happy to offer my services.

 

So if you need someone to help you add unit testing to your project – let’s talk. In case you what to learn more about the topics covered in this blog – I do training as well.

But enough marketing – I’ll keep updating this blog for time to time with my new job experience.

Happy coding…

Tuesday, May 28, 2013

Ruby on Rails - A Jumpstart for .NET Developers review

ruby-v1

I’ve just finished watching Dustin’s Ruby on rails course last week – and the new things I’ve learnt are still sinking in.

PluralSight is a great resource, it  has a huge library of online training and I have used them from time to time to learn new technologies and methodologies.

And so I jumped on the opportunity to check a new course by Dustin Davis – a ruby on rails introduction for .NET developers.

In 2 hours and 39 minutes Dustin shows just enough of Ruby and Rails to create a website from the data layer (SQL) up to the html views.

 

The course consists from 6 parts the first being a short (and to the point) introduction followed by a chapter on Ruby that manages to teach a new language without being trivial, afterwards a dive into the Rails framework, chapters on views and Active Record and finally a “putting it all together” section that uses the lessons learnt during this course to create a fully functional web site.

This course is intended for .NET developers with some web development under their wing – ASP.NET WebForms/MVC, but you don't need to be an expert that written a Facebook clone in order to benefit from this training.

I found this course interesting and informative – and after finishing it I know just enough Rails to start using it – should the opportunity arise.

 

I recommend this course to .NET developers that want to learn a new way of creating websites along with the added benefit of learning a new language – it won’t make an expert out of you but afterwards you would look on web development in a different way.

Wednesday, May 15, 2013

How to write a unit test

Last week I had the pleasure of participating in Sela Developer Practice.
Before my session I sat through Gil ZIlberfeld’s session “7 steps for writing your first unit test” and I found myself thinking – what are steps I take when writing a new unit test?
I’ve been writing them for so long and never noticed I’ve been following a “methodology” of sort. And so without further ado – here is the steps I take when writing a new unit test:

The code under test

In order to write a unit test I’ll need an example and so  I came up with the following scenario:
This is the latest and greatest bug tracking software and we need to add a feature – send an email when a bug with certain severity is created.
The code we want to test looks something (read: exactly) like this:
public class BugTracker
{
    private readonly IBugRepository _repository;
    private readonly IEmailClient _emailClient;

    public BugTracker(IBugRepository repository, IEmailClient emailClient)
    {
        _repository = repository;
        _emailClient = emailClient;
    }

    public Bug CreatNewBug(string title, Severity severity)
    {
        if (string.IsNullOrEmpty(title))
        {
            throw new ApplicationException("Title cannot be empty");
        }

        var newBug = new Bug
             {
                 Title = title,
                 Severity = severity
             };

        SaveBugToDb(newBug);

        // Here be code        

        return newBug;
    }

And so since we’re avid TDD (Test Driven Design) practitioners we’ll start by writing the test first.

Decide what you’re testing

Although this might sound trivial – deciding what to test is a step that many developers tend to forget - instead they write a chunk of code and assert whatever they can.
I found that naming the test method in such a way that forces me (and my fellow developers) to think about what they are about to do:

[TestFixture]
public class BugTrackerTests
{
    [Test]
    public void CreatNewBug_CreateBugHasHighestSeverity_SendEmailToProjectManager()
    {
        
    }
}

I didn't invent this naming convention but I find it very useful. The name is divided into three parts:

  1. The method I’m testing - not description, scenario just the name of the method
  2. The scenario I’m testing
  3. What I expect to happen
The added benefit is that when this test would fail – all I need is to read the name of the test to know what went wrong – take that F5!
There are other similar naming schemas – choose one and be persistent about it.
So now I know what I’m about to test and the next step is to write exactly that.

Write the method under test

I’m starting from the bare minimum and building my test from the inside out.
First I’ll create the class I’m testing and then I’ll run the method I’m testing.
[Test]
public void CreatNewBug_CreateBugHasHighestSeverity_SendEmailToProjectManager()
{
    var cut = new BugTracker();

    cut.CreatNewBug("my title", Severity.OhMyGod);
}
Unfortunately this does not even compile. The problem is that I need to “feed” the BugTracker class two dependencies of type IBugRepository and IEmailClient – so let’s add them courtesy of an Isolation framework (in this case FakeItEasy):
[Test]
public void CreatNewBug_CreateBugHasHighestSeverity_SendEmailToProjectManager()
{
    var fakeBugRepository = A.Fake<IBugRepository>();
    var fakeEmailClient = A.Fake<IEmailClient>();

    var cut = new BugTracker(fakeBugRepository, fakeEmailClient);

    cut.CreatNewBug("my title", Severity.OhMyGod);
}
And now we can write the actual assertion.

Write the assertion

Since we need to check that our email client has sent a message we need to use the power of our isolation framework to assert exactly that
[Test]
public void CreatNewBug_CreateBugHasHighestSeverity_SendEmailToProjectManager()
{
    var fakeBugRepository = A.Fake<IBugRepository>();
    var fakeEmailClient = A.Fake<IEmailClient>();

    var cut = new BugTracker(fakeBugRepository, fakeEmailClient);

    cut.CreatNewBug("my title", Severity.OhMyGod);

    A.CallTo(() => fakeEmailClient.Send("manager@project.com", "Don't Panic!")).MustHaveHappened();
}

Run the test

Now that we have all the parts placed it’s time to run the test and see it fails.
The test did fail but from the wrong reasons:
image

It appear I have a code inside the method “SaveBugToDb” that throws an exception:
private void SaveBugToDb(Bug newBug)
{
    if (!_repository.Connected)
    {
        throw new ApplicationException("Cannot access bug repository");
    }

    _repository.Save(newBug);
}
This means going back to the drawing board for us.

Add more code

In order to make the test fail from the correct reason I’ll add one more line courtesy of our Isolation framework to make sure that a call to Connected will always return true:
[Test]
public void CreatNewBug_CreateBugHasHighestSeverity_SendEmailToProjectManager()
{
    var fakeBugRepository = A.Fake<IBugRepository>();
    A.CallTo(() => fakeBugRepository.Connected).Returns(true);

    var fakeEmailClient = A.Fake<IEmailClient>();

    var cut = new BugTracker(fakeBugRepository, fakeEmailClient);

    cut.CreatNewBug("my title", Severity.OhMyGod);

    A.CallTo(() => fakeEmailClient.Send("manager@project.com", "Don't Panic!")).MustHaveHappened();
}

Run the test (again)

No I run the test again and it fails on the assertion. If it wasn’t the case I would go back and add more code to make sure that the test follow the correct path until I’m satisfied that I’m testing the correct thing.

Write the code to make the test pass

This one is simple – just add the code that makes the test pass:
public Bug CreatNewBug(string title, Severity severity)
{
    if (string.IsNullOrEmpty(title))
    {
        throw new ApplicationException("Title cannot be empty");
    }

    var newBug = new Bug
         {
             Title = title,
             Severity = severity
         };

    SaveBugToDb(newBug);

    if (severity == Severity.OhMyGod)
    {
        _emailClient.Send("manager@project.com", "Don't Panic!");
    }

    return newBug;
}

Conclusion


  1. So what did we do:
  2. Decided what to test
  3. Write the method under test
  4. Add assertion
  5. Run the test
  6. Add more code
  7. Repeat steps 4,5 if necessary
  8. Write the code that makes the test pass


A few comments before the end:

  • This is nothing new if you’re been writing unit tests in the past – you’ve probably followed a similar process – I just needed to write is down explicitly.
  • It seems like a lot of steps just to create a single test? Don’t despair - writing all of them should not take too long and besides – can you write a test without going through all of them in one way or another.
  • I'm a true believer of writing the tests before the code but don’t worry this method sans step 7 will work even if you write your tests retroactively.


Happy coding…

Wednesday, April 24, 2013

Sela Developer Practice 2013

I’m speaking at SDP2013 – two weeks from now.

 

email_confirmation_banner_107127EE

 

I’ll be talking about mocking (surprise!) in “Battle of the Mocking Frameworks”.

 

So if you’re happen to come to the conference on May 7th – drop by and say hi.

 

Until then – happy coding…

Tuesday, March 26, 2013

Unit testing multi threaded code–Timers

Writing unit tests for multi-threaded is not simple and could even be impossible for some scenarios – how could you test that an asynchronous method was not called?
Since most unit testing examples tend to be rather trivial I’ve decided to try and explain other more complex scenarios – preferably without using any calculator examples.

The “Timer” problem

Consider the Timer class (or rather classes), .NET has several classes called Timer, In this post I’m referring to System.Threading.Timer and System.Timers.Timer which is built on top of the former.
Both perform an action in another thread (using the Thread Pool) in intervals (not accurately – but I won’t go there in this post).
Consider the following class:
public class ClassUnderTest
{
    private readonly Timer _timer;

    public ClassUnderTest()
    {
        _timer = new Timer(1000);
        _timer.Elapsed += PerformPeriodicAction;
        _timer.Start();
    }

    public ClassUnderTest(Timer timer)
    {
        _timer = timer;
        _timer.Elapsed += PerformPeriodicAction;
        _timer.Start();
    }

    private void PerformPeriodicAction(object sender, ElapsedEventArgs e)
    {
        // Perform very important task here!
    }
}
Testing code that employs timers can be tricky. Unfortunately there’s a tendency to write a test that looks like this when timers are involved:
[Test]
public void TestJustWrong()
{
    var cut = new ClassUnderTest();

    // Make sure the timer executed at least once
    Thread.Sleep(5000);

    // Check that something happens
}

So what is the problem?

Although it might seem like a valid unit test – in fact it’s a test that would fail from time to time - whenever the timer would happen to “tick” for more than the sleep period.
These kind of tests are known as the “the test that tends to fail” and usually “fixed” by running the build script another time.
You do not want a test that you cannot trust to fail only when a bug is introduced into your system.
Sadly I’ve seen this code – a lot! But no more - writing a good unit test for that class is simple, in fact there is more than one alternative that creates a simple, trustworthy unit test.

Solution 1 – invoke the handler instead

Instead of waiting for the time to execute why not call the method that handles the timer’s event?
First we need to make sure that the method we’re going to call is internal or public. I personally don’t like changing my production code that much in order to make the code “testable” but it’s a way.
Now all we have to do is call the method thus making sure that execution happens exactly when we want it – and a unit test is born:
[Test]
public void TestByMethod()
{
    var cut = new ClassUnderTestForTestability();

    // Let's call the method
    cut.PerformPeriodicAction(this, null);

    // Check that something happens
}

Solution 2 – invoke the timer at your leisure

Most modern Isolation (a.k.a Mocking) frameworks have the ability to invoke events as well as create fake objects.
We’re going to create a fake timer and invoke the elapsed event. Using simple constructor injection we’ll pass the timer to our class under test prior to invocation and we have a more robust unit test:
[Test]
public void TestWithFakeTimer()
{
    var fakeTimer = Isolate.Fake.Instance<Timer>();

    var cut = new ClassUnderTest(fakeTimer);

    // Let's invoke the event
    Isolate.Invoke.Event(() => fakeTimer.Elapsed += null, this, null);

    // Check that something happens
}
I’m using Typemock Isolator but you can use the isolation framework of your choice The syntax is strange but once you’ll get used to it, it’s simple.
The added value is that we’re causing the real flow of our program to execute – in a synchronized and timely manner.

Conclusion

Although there are many ways to test code that uses timers I find myself employing the two above most of the time.
I plan to write a few more posts on the other pitfall of testing multi-threaded code (and how to avoid them) but until then –

happy coding…

Friday, March 01, 2013

Spreading the agile joy

I finally hit critical mass!

I got a request from one of the project managers (not my project) to do a quick “introduction to Scrum” session.

It took quite a while – more than two years (and a downsizing) in order for other teams to notice that we have a different way to do things.

I did a very successful session – mainly because the audience “felt the pain”; it was fun explaining about Scrum with examples on how they can utilize it the very next day.

Since I’m not in daily contact with that team – I had no idea how well they implemented Scrum. Until yesterday when I walked on a meeting that had a task board on a big screen – so I guess it went well.

When I was first asked to do this session I wanted to create a simple and short presentation that can be re-used – And here it is:

 

It’s simple and short so I use it as a “background” for a discussion on how they are going to use Scrum in their work – today.

 

I guess I’m doing something right since I have another session next week!

 

And if you have an agile success story – please share…

Related Posts Plugin for WordPress, Blogger...