AutoFixture > Customize objects creation with ICustomization interface

In this post we will look at AutoFixture basic customization features starting with ICustomization interface.

We will use following DateRange class as demonstration example.

    public class DateRange
    {
        public DateTime Start { get; private set; }
        public DateTime Finish { get; private set; }

        public DateRange(DateTime start, DateTime finish)
        {
            if (start > finish)
            {
                throw new ArgumentException("Finish date must be less than or equal to Start date");
            }

            Start = start;
            Finish = finish;
        }
    }

If we write test method using DateRange as parameter:

using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit2;
using Xunit;

public class DateRangeTests
    {
        [Theory, AutoData]
        public void ShowCaseTest(DateRange sut)
        {
            //skip the body to focus at the DateRange object creation
        }
    }

Test will sometimes fail with “System.ArgumentExceptionFinish date must be less than or equal to Start date”. Because by default AutoFixture library will just pass two random DateTime as constructor parameter and the validation logic inside constructor is not considered.

Let’s fix it by implementing ICustomization interface to create valid DateRange object.

 public class CustomAutoDataAttribute : AutoDataAttribute
    {
        public CustomAutoDataAttribute()
            : base(new Fixture()
            .Customize(new ValidDateRangeCustomization()))
        { }
    }

    public class ValidDateRangeCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Register(() =>
            {
                var start = fixture.Create<DateTime>();
                return new DateRange(start, start.AddDays(1));
            });
        }
    }

The last step is to to use CustomAutoData in the test instead of default AutoData.

    [Theory, CustomAutoData]
    public void DoSomeTest(DateRange sut)
    {

    }
Posted in programming, Unit test | Tagged , | Leave a comment

Using discriminated unions to fix Liskov substitution principle violation

As an example of LSP violation, I will consider e-commerce payment system design. One needs to develop generic mechanism for multiple payment service providers (PSP) that are using on checkout step.

From the requirements there are different kinds of PSP in terms of integration. There are PSP that require customer to be redirected to PSP portal page, where customer needs to enter payment information, e.g. credit card. On the other hand, there are PSP that provide possibility to integrate through the API where the response is synchronous, e.g. direct payments.

Knowing that, we could start to design simple interface with two methods for different type of payments, and trying to provide several implementations.


    public interface IPaymentProvider
    {
        PaymentFormDetails GetPaymentFormDetails(Order order);
        PaymentResponse MakeDirectPayment(Order order);
    }

    public class PayPalDirectPaymentProvider : IPaymentProvider
    {
        public PaymentFormDetails GetPaymentFormDetails(Order order)
        {
            throw new NotSupportedException("Not supported for Direct payments. Used only for 3D secure payments.");
        }

        public PaymentResponse MakeDirectPayment(Order order)
        {
           //do some real job here, e.g. call real services etc
            return new PaymentResponse()
            {
                TransactionId = Guid.NewGuid().ToString()
            };
        }
    }

    public class PayPalStandartPaymentProvider : IPaymentProvider
    {
        public PaymentFormDetails GetPaymentFormDetails(Order order)
        {
            return new PaymentFormDetails();
        }

        public PaymentResponse MakeDirectPayment(Order order)
        {
            throw new NotSupportedException("Direct payments are not supported by PayPal direct.");
        }
    }

    public class PaymentResponse
    {
        public string TransactionId { get; set; }
    }

    public class Order
    {
        public decimal Amount { get; set; } 
        public string OrderNumber { get; set; }
    }

    public class PaymentFormDetails
    {
        public string PaymentGatewayUrl { get; set; }
        public string OrderNumber { get; set; }
        public decimal Amount { get; set; }
    }

Unfortunately there is no way for specific payment provider to implement both of methods, so we have to throw NotSupportedException. That is clearly indicates LSP violation.

As we try to adhere to SOLID principles, let’s try to fix the violation.

LSP violation fix#1 – NotSupportedException

First attempt could be to introduce marker interface, it could greatly simplified interface and implementations themselves,
But now calling side should perform downcasting from interface to its implementation in order to correctly interpret the result.

 public interface IPaymentProvider
    {
        IPaymentRequestProcessingResult ProcessPaymentRequest(Order order);
    }

    public interface IPaymentRequestProcessingResult
    {
    }

    public class PaymentResponse : IPaymentRequestProcessingResult
    {
        public string TransactionId { get; set; }
    }

    public class PaymentFormDetails : IPaymentRequestProcessingResult
    {
        public string PaymentGatewayUrl { get; set; }
        public string OrderNumber { get; set; }
        public decimal Amount { get; set; }
    }

    public class PayPalDirectPaymentProvider : IPaymentProvider
    {
        public IPaymentRequestProcessingResult ProcessPaymentRequest(Order order)
        {
            //do some real job here, e.g. call real services etc
            return new PaymentResponse()
            {
                TransactionId = Guid.NewGuid().ToString()
            };
        }
    }

    public class PayPalStandartPaymentProvider : IPaymentProvider
    {
        public IPaymentRequestProcessingResult ProcessPaymentRequest(Order order)
        {
            return new PaymentFormDetails()
            {
                Amount = order.Amount,
                OrderNumber = order.OrderNumber,
                PaymentGatewayUrl = "https://www.paypal.com"
            };
        }
    }

Remove LSP violation#2 – Downcasting and type checking. Introduce discriminated union

Discriminated union is terms came from functional langauges, particularly from F#. Base on Microsoft documentation

Discriminated unions provide support for values that can be one of a number of named cases, possibly each with different values and types. Discriminated unions are useful for heterogeneous data;

https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/discriminated-unions

Discriminated unions and not supported out of the box in C#, but there are several ready to use implementations over the Internet. I used implementation from here http://pastebin.com/EEdvVh2R

public sealed class Union2<A, B>
    {
        readonly A Item1;
        readonly B Item2;
        int tag;

        public Union2(A item) { Item1 = item; tag = 0; }
        public Union2(B item) { Item2 = item; tag = 1; }

        public T Match<T>(Func<A, T> f, Func<B, T> g)
        {
            switch (tag)
            {
                case 0: return f(Item1);
                case 1: return g(Item2);
                default: throw new Exception("Unrecognized tag value: " + tag);
            }
        }
    }

Than we will remove from

  public interface IPaymentProvider
    {
        PaymentRequestProcessingResult ProcessPaymentRequest(Order order);
    }

    public class PaymentRequestProcessingResult: Union2<PaymentResponse, PaymentFormDetails>
    {
        public PaymentRequestProcessingResult(PaymentResponse item) : base(item)
        {
        }

        public PaymentRequestProcessingResult(PaymentFormDetails item) : base(item)
        {
        }
    }

And implementations now:

 public class PayPalDirectPaymentProvider : IPaymentProvider
    {
        public PaymentRequestProcessingResult ProcessPaymentRequest(Order order)
        {
            //do some real job here, e.g. call real services etc
            return new PaymentRequestProcessingResult(
                new PaymentResponse()
                {
                    TransactionId = Guid.NewGuid().ToString()
                });
        }
    }

    public class PayPalStandartPaymentProvider : IPaymentProvider
    {
        public PaymentRequestProcessingResult ProcessPaymentRequest(Order order)
        {
            return new PaymentRequestProcessingResult(new PaymentFormDetails()
            {
                Amount = order.Amount,
                OrderNumber = order.OrderNumber,
                PaymentGatewayUrl = "https://www.paypal.com"
            });
        }
    }

And finally usage,

public static void Main()
        {
            var order = new Order
            {
                Amount = 20m,
                OrderNumber = "00001"
            };

            Console.WriteLine("Select payment provider (1 - PayPal Direct, 2 - PayPal standart):");
            var pl = int.Parse(Console.ReadLine());
            var paymentProvider = GetPaymentProvider(pl);

            var res = paymentProvider.ProcessPaymentRequest(order);

            Console.WriteLine(res.Match(
                r => "Direct payment succeed. Transaction ID:" + r.TransactionId,
                fd => "Standart payment providers. Redirecting to PSP. Paymew gateway url:" + fd.PaymentGatewayUrl));

            Console.Read();
        }

ProcessPaymentRequest method results are clearly defined and allow to use them in type-safe manner.

Review

Let’s review what we achieved so far:

  • Removed throwing NotSupportedException
  • Eliminate downcasting to specific class types
  • Enable type-safe way of working with possible payment processing results
Posted in object-oriented-principles, software-patterns | Leave a comment

FAKE.IIS Add application to existing IIS site

Recently I had a task to change IIS application path in existing IIS site.
That was repetitive operation so I decided to write script for it.

I recently began to study F# and function programming so decided to try FAKE.
There is also cool explanation of FAKE here: http://blog.tamizhvendan.in/blog/2015/01/06/step-4-build-automation-using-fake/.

I have easily find IIS() function, that allows to get all the things ready at once: setup site/application pool/applications.
IIS() works in way that it will not create new site or application pool, if the same already exists.
But it will always add new version of site bindings even if the same is already exists. It makes IIS site stopped and there extra binding are to be taken care manually.

That said, I created interactive script, *.fsx file.
It is “hardcoded” and not error safe, but contains some parts, that I spent time struggling with, like figuring out where to take instance of ServerManager to create application etc.


#r @"packages/FAKE/tools/Fake.IIS.dll"
#r @"packages/FAKE/tools/FakeLib.dll"
#r @"packages/FAKE/tools/Microsoft.Web.Administration.dll"

open System
open System.Security.Principal
open Microsoft.Web
open Microsoft.Web.Administration
open Fake
open Fake.IISHelper

let siteName = "site"
let vdir = "/dir"
let path = @"C:\IIS\site\dir"

let addNewApp vdir path = 
    use mgr = new ServerManager()
    let site = mgr.Sites.[siteName]
    let app = Application vdir path site mgr
    commit mgr
Posted in F# | Tagged , | Leave a comment

Tools and libraries to consider when writing autotests

Below is a summary of tools/libraries I have used to build maintainable suite of auto tests on large ecom project.

While it is hard to start without test framework :), some autaaof the libraries listed below could be easily omitted by developers.

XUnit

xUnit.net is a developer testing framework, built to support Test Driven Development, with a design goal of extreme simplicity and alignment with framework features. (copied from nuget package description)

AutoFixture

AutoFixture makes it easier for developers to do Test-Driven Development by automating non-relevant Test Fixture Setup, allowing the Test Developer to focus on the essentials of each test case. (copied from nuget package description)

I could not stress enough how useful the library is. It allows to greatly decrease the lines of code for your test suits and make tests more readable.

FluentAssertions

A very extensive set of extension methods that allow you to more naturally specify the expected outcome of a TDD or BDD-style unit test. (copied from nuget package description)

It providesa a lot more possibilities to assert the test outcome than standard test frameworks do.

Simple.Data.SqlServer

Simple.Data is a lightweight framework that uses the dynamic features of .NET 4 to provide an expressive, ORM-ish way of accessing and manipulating data without any of the code pre-generation and boilerplate required by other frameworks. (copied from nuget package description)

Greatly could help when need to quickly verify the test that makes side effects in DB. Or perform test data setup.

Posted in Unit test | Tagged | Leave a comment

How to identify process ID in PerfMon

Last time I need to troubleshoot memory leak in IIS process hosted on productions server I decided to start with PerfMon and got stuck on Add Counters screen, where I saw seventeen w3wp (IIS process name) processes up to w3wp#17.

Here for the demo I used two instances of the same console application. It is enough to get the idea.

Add Counters

It occurs that there are some advice how to identify PID of the process, most of them about changing registry settings, and it  does not always help.

Others suggest to use third-party tools to match PerfMon process identification with real PID.

I used another solution. Add another performance counter, like on the screen below.

Add Counters 2016-03-22 22.59.16

Now I have possibility to identify that process I was interested in was #1.

Performance Monitor 2016-03-22 23.03.39

Happy using PerfMon. It is amazing!

Posted in SysInternals | Tagged | Leave a comment

Software developer productivity

From the starting of my software developer career I wanted to be as productive as possible. And the worst feeling I could have, was when I  was working on a problem that I have already solved before, and need to refresh my memory to solve it again with applying efforts again.

Most of us (so did I) are quite lazy in applying such patterns. When the problem first occurs we usually do not want to apply patterns that would save us time in future. Until it really hurts 🙂 Then we really start working on solution.

The list of things I was not doing from the start and am sorry about that :

Using browser bookmarks

It really helps to keep already found answers close to you. So you are not obliged to search again for information that already was found. Especially when there is browser bookmark is synchronised within multiple client devices (like in Chrome). When there will be more than *some figure*, you could reorganise your collection of bookmarks into folders etc.

Keep your source code on github

Previously I kept my source code, that I often use in Dropbox. But using github makes it much easier. Things I put on github are for instance: project skeleton of unit tests project with all its packages; or skeleton of reactjs project with all required dependencies. So I do not waste time setup it all over again. I download it from well-known location and start doing valuable things.

Don’t mess around your folder structure

Formerly any file I downloaded I stored in “Downloads” folder. It is obvious that since some time I barely could found any stuff there. That said I want to say that folders structure is important and keeping information in its place is important too.

When I think about getting things fast, I always remember the comparison of searching in array of unordered items and search in search binary tree. Search in sorted binary tree is much faster. The same principle applies to many aspects of the life, including the information organisation.

Posted in Uncategorized | Leave a comment

Better handling ‘NoSuchElementException’ using simple remote web driver wrapper

While implementing test scenarios, I often write some element selectors wrong and finally get ‘NoSuchElementException’ when run the test. Unfortunately it does not specify, which selector caused the problem. Its message only says the following:

OpenQA.Selenium.NoSuchElementException: no such element
(Session info: chrome=45.0.2454.99)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.3 x86_64)

So I need to waste time to locate exact failed selector using debugging…
Wouldn’t be nicer to have not found selector specified right in exception message? So it would be possible to troubleshoot the problems easily.
Ok, let’s  add it!

First prepare the environment. I use Visual studio 2013, update 5.
1. Create test project. Ensure that you have NUnit runner extension installed in VS.
2. Install following packages:

<packages>
  <package id="CuttingEdge.Conditions" version="1.2.0.0" targetFramework="net45" />
  <package id="NUnit" version="2.6.4" targetFramework="net45" />
  <package id="Selenium.WebDriver" version="2.47.0" targetFramework="net45" />
  <package id="WebDriverChromeDriver" version="2.10" targetFramework="net45" />
</packages>

3. Modify UnitTest1 class to use NUnit.

 [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            using (var myDriver = new ExceptioHandleDriver(new ChromeDriver(new ChromeOptions())))
            {
               var element = myDriver
                    .GoTo("https://wordpress.com/wp-login.php")
                    .FindElement(By.Id("unique-id"));

                Assert.IsTrue(element != null);
            }
        }
    }

4. Add driver implementation. Driver is wrapper around RemoteWebDriver and implements only few functionality, just to fit the demonstration purpose:

 public class ExceptioHandleDriver : IDisposable
    {
        private readonly RemoteWebDriver _innerDriver;

        public ExceptioHandleDriver(RemoteWebDriver innerDriver)
        {
            Condition.Requires(innerDriver).IsNotNull();
            _innerDriver = innerDriver;
        }

        public ExceptioHandleDriver GoTo(string url)
        {
            _innerDriver.Navigate().GoToUrl(url);
            return this;
        }

        public IWebElement FindElement(By by)
        {
            try
            {
                return _innerDriver.FindElement(@by);
            }
            catch (NoSuchElementException e)
            {
                throw new NoSuchElementException(string.Format("Element '{0}' was found.", @by), e);
            }
        }

        #region Dispose pattern implementation

        ~ExceptioHandleDriver()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_innerDriver != null)
                {
                    _innerDriver.Dispose();
                }
            }
        }

        #endregion
    }

Now when we run the test (it assumes to be failed, do not worry), we could happily see better error representation:

Result Message:
OpenQA.Selenium.NoSuchElementException : Element ‘By.Id: unique-id’ was found.
—-> OpenQA.Selenium.NoSuchElementException : no such element
(Session info: chrome=45.0.2454.99)
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.3 x86_64)
Result StackTrace:
….

Posted in Selenium | Tagged | Leave a comment