Test async webservice call with a Task

We have a number of services in our project. Our clients include WPF, iOS, Android and Web. To have the best interoperability we communicate over http and expose WSDL for proxy generation. This means we cannot change the contracts or introduce new versions when we break compatibility. We plan to test the compatibility of our changes with unit tests.

The unit tests host services based on the latest contract. Then every released proxy is used to call the known operations. When the call succeeds, the results and parameters are validated on both ends. This way we know what is broken.

To test the async calls to the services I’m using a Task. See the code below, other methods are left out for clarity.

[TestMethod]
public void Print_async()
{
    // Arrange
    var mock = GenerateServiceMock();
    mock.Expect(x => x.Print(null)).IgnoreArguments().Return(1)
        .WhenCalled((x) => Thread.Sleep(3000)); // included to simulate lag

    // Act
    var actual = default(int);
    using (var host = StartService(mock))
    {
        var proxy = GenerateProxy();
        // call print direct
        // var actual = proxy.Print("Hello World");        
        // call print async
        var async = proxy.BeginPrint("Hello World", null, null);
        // task to handle async
        var task = Task.Factory.FromAsync(async, (x) => actual = proxy.EndPrint(x));
        // wait for it
        task.Wait();
        // cleanup
        host.Close();
    }

    // Assert
    Assert.AreEqual<int>(1, actual);
    var args = mock.GetArgumentsForCallsMadeOn(x => x.Print(null));
    mock.VerifyAllExpectations();
    Assert.AreEqual("Hello World", args[0][0]);
}

Because our project is on the 4.0 version of the dotnet framework we can’t use async/await. The FromAsync method takes the IAsyncResult from the BeginPrint call and waits for it to be completed. When it completes the EndPrint method is called to receive the result from the server. Until the task we’ve created finishes the execution is put on hold with task.Wait().

The code for testing the service direct or async only differs in the call of the operation. The Arrange and Assert sections are untouched.

Complete sample below

// you'll  need rhino mocks: http://hibernatingrhinos.com/downloads/rhino-mocks/latest
[ServiceContract]
public interface IPrintable
{
    [OperationContract]
    int Print(string document);

    [OperationContract (AsyncPattern = true)]
    IAsyncResult BeginPrint(string document, AsyncCallback callback, object state);

    int EndPrint(IAsyncResult async);
}

private IPrintable GenerateServiceMock()
{
    Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add<ServiceContractAttribute>();
    var mock = MockRepository.GenerateStrictMock<IPrintable>();
    return mock;
}
private ServiceHost StartService(IPrintable mock)
{
    var service = new ServiceHost(mock, new Uri("http://localhost:1233/printservice"));
    // ! enable hosting an instance (not a type)
    service.Description.Behaviors.Find<ServiceBehaviorAttribute>().InstanceContextMode = 
        InstanceContextMode.Single;
    service.Open();
    return service;
}
private IPrintable GenerateProxy()
{
    // abc for proxy
    var address = new EndpointAddress("http://localhost:1233/printservice");
    var binding = new BasicHttpBinding();
    var channel = ChannelFactory<IPrintable>.CreateChannel(binding, address);
    return channel;
}

[TestMethod]
public void Print()
{
    // Arrange
    var mock = GenerateServiceMock();
    mock.Expect(x => x.Print(null)).IgnoreArguments().Return(1);

    // Act
    var actual = default(int);
    using (var host = StartService(mock))
    {
        // abc for proxy
        var proxy = GenerateProxy();
        // call print async
        actual = proxy.Print("Hello World");
        // cleanup
        host.Close();
    }

    // Assert
    Assert.AreEqual<int>(1, actual);
    var args = mock.GetArgumentsForCallsMadeOn(x => x.Print(null));
    mock.VerifyAllExpectations();
    Assert.AreEqual("Hello World", args[0][0]);
}

[TestMethod]
public void Print_async()
{
    // Arrange
    var mock = GenerateServiceMock();
    mock.Expect(x => x.Print(null)).IgnoreArguments().Return(1)
        .WhenCalled((x) => System.Threading.Thread.Sleep(3000));

    // Act
    var actual = default(int);
    using (var host = StartService(mock))
    {
        // abc for proxy
        var proxy = GenerateProxy();
        // call print async
        var async = proxy.BeginPrint("Hello World", null, null);
        // wait for it
        var task = Task.Factory.FromAsync(async, (x) => actual = proxy.EndPrint(x));
        task.Wait();
        // cleanup
        host.Close();
    }

    // Assert
    Assert.AreEqual<int>(1, actual);
    var args = mock.GetArgumentsForCallsMadeOn(x => x.Print(null));
    mock.VerifyAllExpectations();
    Assert.AreEqual("Hello World", args[0][0]);
}

Posted in Test | Tagged , , , , , | Leave a comment

Compat inspector fiddler rule

Origional post here. My version of the fiddler CustomRules.js file below.

import System;
import System.Windows.Forms;
import Fiddler;

// INTRODUCTION
// This is the FiddlerScript Rules file, which creates some of the menu commands and
// other features of Fiddler. You can edit this file to modify or add new commands.
//
// The original version of this file is named SampleRules.js and it is in the
// \Program Files\Fiddler\ folder. When Fiddler first starts, it creates a copy named
// CustomRules.js inside your \Documents\Fiddler2\Scripts folder. If you make a 
// mistake in editing this file, simply delete the CustomRules.js file and restart
// Fiddler. A fresh copy of the default rules will be created from the original
// sample rules file.

// GLOBALIZATION NOTE:
// Be sure to save this file with UTF-8 Encoding if using any non-ASCII characters
// in strings, etc.

// JScript Reference
// http://www.fiddler2.com/redir/?id=msdnjsnet
//
// FiddlerScript Reference
// http://www.fiddler2.com/redir/?id=fiddlerscriptcookbook
//
// FiddlerScript Editor: 
// http://www.fiddler2.com/redir/?id=fiddlerscripteditor
class Handlers
{
 static function OnBeforeResponse(oSession: Session) {
// Snippet 1: Place this inside the "OnBeforeResponse" handler in your FiddlerScript
InjectInspectorScript(oSession);
}

// Snippet 2: Place this near the end of your FiddlerScript (within the Handlers class)
public static RulesOption("Use Compat Inspector")
var m_UseCompatInspector: boolean = false;
static function InjectInspectorScript(oSession: Session)
{
	if(!m_UseCompatInspector) return;
	
	// Ensure we only inject into HTML
	if (oSession.url.EndsWith(".js")) return;
	if (oSession.url.EndsWith(".css")) return;
	if (!oSession.oResponse.MIMEType.Contains("text/html")) return;
	
	// Retrieve the response body
	var sBody = oSession.GetResponseBodyAsString();
	// One final check to ensure the content looks like HTML
	if (!/^\uFEFF?\s*</.exec(sBody)) return;
	
	// Prepare to inject
	var pos = 0; // Initial position is start of document
	
	// Locate important elements in the page
	var doctype = sBody.IndexOf("<!doctype", StringComparison.OrdinalIgnoreCase);
	var meta = sBody.IndexOf("X-UA-Compatible", StringComparison.OrdinalIgnoreCase);
	var script = sBody.IndexOf("<script", StringComparison.OrdinalIgnoreCase);
	
	// Place after doctype (if present)
	if (doctype != -1) doctype = sBody.IndexOf(">", doctype + 1);
	if (doctype != -1 && doctype != sBody.Length - 1) pos = doctype + 1;
	
	// Place after first X-UA-Compatible meta tag (if present)
	if (meta != -1) meta = sBody.IndexOf(">", meta + 1);
	if (meta != -1 && meta != sBody.Length - 1) pos = meta + 1;
	
	// Place before any script tags that occur before the current position (if present)
	if (script != -1 && script < pos) pos = script;
	
	// Perform the injection at the detected location
	oSession.utilSetResponseBody(
		sBody.Insert(pos, "<script src='http://ie.microsoft.com/testdrive/HTML5/CompatInspector/inspector.js'></script>")
	);
}
}
Posted in Tooling | Tagged , , , | Leave a comment

if this than that

Every programmer knows the if statement. Now there is a service that provides a visual way of defining the statement called IFTTT.

Gift without the ‘G’

What is so special about that, we all know Visual Programming languages?

iftttIFTTT uses other services as triggers like Twitter, Gmail and YouTube. But also RSS feeds, SMS and dropbox. Every fifteen minutes your channels are polled and when the trigger fires your action is executed.

With 59 channels (on time of post) and multiple triggers and actions for every channel, the possibilities are limitless. Signup it’s free!

Below a list of my triggers so far:

  • Use Instagram to update your Twitter profile picture
  • Mark Watch Later on Youtube and save it to Pocket!
  • Post personal blog entries to Yammer
  • Send weekly digest of Lifehacker’s most popular posts to Pocket
  • Add new items from an RSS Feed to Pocket
  • Get all the updates to IFTTT via email!
Posted in Tooling | Tagged | 1 Comment

Implement Interface as virtual methods

A best pratice in Object Oriented Programming is the use of Interfaces. When applied correctly it simplifies unit testing. But watch out for the pitfall of default implementation by Visual Studio. Below is an example how this can bite you.

A Document can be printed using the IPrintable interface. The implementation of the interface calls the more specific print methods based on the paper size.

public interface IPrintable
{
    void Print();
    string GetPaperSize();
}
public class Document : IPrintable
{
    public void Print()
    {
        if (GetPaperSize() == "A4") PrintOnA4();
        else PrintOnDefault();
    }
    // implementation ignored for demo purpose
    public string GetPaperSize() { return string.Empty; }
    public virtual void PrintOnA4() { }
    public virtual void PrintOnDefault() { }
}

Now the unit test of the Print method. The test below wants to validate PrintOnA4 is called when the PaperSize is A4 and the Print method of IPrintable is called on the Document. For my unit tests I use Rhino mocks.

[TestMethod]
public void Document_Print_Papersize_A4_calls_PrintOnA4()
{
    // Arrange
    // PartialMock to call origional methods when no expectation is set up
    var testObject = MockRepository.GeneratePartialMock<Document>();
    // Return PaperSize "A4"
    testObject.Expect(x => x.GetPaperSize()).Return("A4");
    // Expect PrintOnA4 to be called
    testObject.Expect(x => x.PrintOnA4());
    // Expect PrintOnDefault *NOT* to be called
    testObject.Expect(x => x.PrintOnDefault()).Repeat.Never();

    // Act
    testObject.Print();

    // Assert
    testObject.VerifyAllExpectations();
}

Running the test results in an InvalidOperationException because GetPaperSize is not overridable on Document.
InvalidOperationException when mocking non-virtual method
It is part of the IPrintable interface and can be mocked there. This can be done by adding a second parameter to the GeneratePartialMock call. One mock is generated for both Document and IPrintable combined.

var testObject = MockRepository.GeneratePartialMock<Document, IPrintable>();
((IPrintable)testObject).Expect(x => x.GetPaperSize()).Return("A4");

Now the test fails because the PrintOnDefault method is called and the PrintOnA4 is not. What happened? We mocked the GetPaperSize to return “A4”.
The method is mocked on IPrintable, but not on Document. To use the IPrintable method we need to cast to it.

public void Print()
{
    if (((IPrintable)this).GetPaperSize() == "A4") PrintOnA4();
    else PrintOnDefault();
}

Now the test Passes. But do I want to cast every time I use something from an Interface?
The solution is to implement the interface with virtual methods. That way I can mock the methods directly on the class and don’t have to cast every time. Why is this not the default in Visual Studio?
Implement interface in Visual Studio

public interface IPrintable
{
    void Print();
    string GetPaperSize();
}
public class Document : IPrintable
{
    public virtual void Print()
    {
        if (GetPaperSize() == "A4") PrintOnA4();
        else PrintOnDefault();
    }
    // implementation ignored for demo purpose
    public virtual string GetPaperSize() { return string.Empty; }
    public virtual void PrintOnA4() { }
    public virtual void PrintOnDefault() { }
}

The first unit test in this post can be used to verify that PrintOnA4 is called and not PrintOnDefault when GetPaperSize returns “A4”.

Posted in Test | Tagged , , , | Leave a comment

Disable Hyper-V internal virtual switch to get instant internet after boot-up

Recently I noticed getting a usable internet connection took a long time after boot-up. After the login screen, I would switch to the desktop and start Internet Explorer. The window was empty for quite some time, but when it showed my frequent webpages everything worked fine.

The installation of SSD cut the boottime. But not being able to instantly go on the internet or check for new messages was slowing me down.

Yesterday I looked at the Network Control Panel\Network and Internet\Network Connections and noticed the Internal Virtual Switch state. It was “Identifying…” for a long time and when it finally got to “Unidentified network” my Internet Explorer was ready for use. So I disabled it and got my usable internet connection right after boot-up. Problem solved!

Hyper-V Internal Virtual Switch disabled

Hyper-V networking uses virtual switches to connect to physical networks and virtual (VM-VM and VM-Host) networks. The internal virtual switch is used to connect to virtual networks. Whenever I need such a connection I will enable it again. No reboot required, just some patience.

Posted in Tooling | Tagged , , , , , | 1 Comment