Wednesday, 27 December 2017

Mercurial hooks to enforce commit rules

If you've been in the software industry for a while, there's something that's very clear, no software can be done on your own for too long. Working as a team requires some form organisation, some rules, some standards so everyone is on the same page. The more standardised, the easier to automate processes. Let's start on simple day to day tasks such as committing code to source control.

In the team where I'm working, we set a couple of rules for all to follow.

Commit messages normalized

Since we are supposed to associate every commit with a corresponding ticket on our trello board, that is a fundamental part of the commit message. The format we set is as follows:

[Committer/Committer] - ticket ### - commit message

Where:

Committer is the initials of the dev(s) involved in that particular commit

Ticket ### is the trello card number associated with the task

Commit message is a meaningful message that summarises what has changed

spaces and dashes are mandatory

Limiting the maximum number of committed files

A common rule of thumb is that we should limit the number of modified files to a maximum so we can trace and understand what has changed in order to review when we need to find some specific change. However, it's not set in stone what that maximum is, so we opted for a manageable amount of files, initially 10 but it turns out that it works better with 20 and it's still a manageable amount.

How do we enforce this?

After some research, I put my bet on mercurial hooks, since we use mercurial as source control and bitbucket as code repository. Mercurial hooks allows the possibility of executing custom code when some event happens, for example before the commit transaction is finished. At this point, we can know all about the changes that are about to be committed. The main point of interest is the number of files in the current changeset and the description aka commit message.

Before considering a commit as valid, the previously mentioned rules are verified and if one of them is invalid, the commit is aborted.

What if we are merging ?

There is a scenario that needs to be treated differently, it's when a commit is done after the result of a merge. Even if every single commit is limited to a maximum number of modified files, when merging with a different branch such as stable cut, inevitably there will be a lot more files than the maximum and that's acceptable, so in this case, we ignore the rule of the number of files and the commit message should be different i.e Merge with stable.

Putting it all together

Installing the hook.

Inside .hg folder, there is a file named hgrc, it defines mercurial configuration for the current repository. Add the following lines.

[hooks]
pretxncommit = python:hooks/commit-rules.py:checkCommit

Here we assign the python function checkCommit to pretxtcommit event hook, and such function is located inside hooks/commit-rules.py file relative to the repository root. I was tempted to keep this file inside .hg but this is not possible.

Let's inspect what's inside this commit-rules.py

import re

maximum_files = 20

def checkCommit(ui, repo, **kwargs):
 
 # Check the commit message for compliance with our team rules, if not compliant
 # Then abort the commit transaction displaying useful information to the user
 hg_commit_message = repo['tip'].description()
 is_incorrect_message = checkMessage(ui, hg_commit_message)
 if is_incorrect_message:
  return True

 # Check if the current revision has more than one parent
 # if more than one, the we are on a merge => do not check the number of files
 revision_parents = len(repo['tip'].parents())
 if revision_parents > 1:
  return False
 
 # Check the number of files on current revision, if they're more than the maximum 
 # Then abort the commit transaction displaying useful information to the user
 repo_files_count = len(repo['tip'].files()) 
 is_incorrect_commit_files = checkFiles(ui, repo_files_count)
 if is_incorrect_commit_files:
  return True
  
 return False

def checkMessage(ui, message): 
 
 # Regular expression to check the commit message structure - for a single commit
 # Valid examples:
 #
 # [DG/APM] - ticket 123 - Two committers text for a valid commit
 # [APM] - ticket 123 - Single committer text for a valid commit 
 #
 commit_re = re.compile(r'(\[[A-Za-z\/]+\])\s\-\sticket\s(\d+)\s\-\s(.*)')
 commit_check = commit_re.match(message)
 
 # regular expression to check the commit message structure - for a merge commit
 # Valid examples:
 #
 # Merge with stable
 # Merge with default
 #
 merge_re = re.compile(r'Merge with [A-Za-z0-9- ]+')
 merge_check = merge_re.match(message)
 
 if not commit_check and not merge_check:
  ui.warn('Commit message does not comply with our team rules\n')
  ui.warn('\n')
  ui.warn('Use format "[Committer/Commiter] - ticket ### - commit message"\n')
  ui.warn('\n')
  ui.warn('* Committer initials should be separated by /\n')
  ui.warn('* Ticket ### should match Trello ticket number\n')
  ui.warn('\n')
  ui.warn('For merge, use format "Merge with branch-name"\n')
  ui.warn('\n')
  
  # return true if is invalid 
  return True
 
 return False

def checkFiles(ui, files):
 if (files > maximum_files):
  ui.warn("Commit with too many files (" + str(files) + ") - Maximum files (" + str(maximum_files) +")\n")
  # return true if is invalid 
  return True
 
 return False

Since this code has to run on each dev computer and does not propagate for security reasons according to mercurial documentation, we made a way to "install" it when the build operation is run in Visual Studio by creating a pre build event that runs a powershell script.

Here is the powershell script that installs the hook when it's not already there.

Param(
    [Parameter(Mandatory=$True)]
    [string]$hgrcFile
)

if (-not (Test-Path $hgrcFile) ) {
    exit
}

#$hgrcFile = ".\.hg\hgrc"
$hgrc = Get-Content $hgrcFile -ErrorAction Stop

$lineHook = "[hooks]"
$linePreTxnCommit = "pretxncommit = python:hooks/commit-rules.py:checkCommit"
$containsHooks = $hgrc.Contains($lineHook)
$containsPreTxtCommit = $hgrc.Contains($linePreTxnCommit)

if (-not ($containsHooks -and $containsPreTxtCommit)) 
{
    Write-Host "hook not installed. Installing ..."

    $hgrc += ""
    $hgrc += $lineHook
    $hgrc += $linePreTxnCommit
    
    $hgrc | Out-File $hgrcFile -Encoding utf8

    Write-Host "Done"
}

And here is the pre build event fragment from the main .csproj file in our solution

<PropertyGroup>
    <PreBuildEvent>
        powershell -ExecutionPolicy ByPass -File "$(SolutionDir)install-hook.ps1" -hgrcFile "$(SolutionDir).hg\hgrc"
    </PreBuildEvent>
</PropertyGroup>

For more reference about mercurial hooks, check Mercurial hooks examples

Monday, 27 November 2017

A bug hidden for 4 years !

I have to admit I've abandoned my file uploader for some time, and I've been revisiting the code recently as part of some experiments with .NET Core 2.

After some work done to make it work with the new framework, to my surprise, it just looked to work perfectly until I tried to validate one of the basic implicit requirements: the uploaded copy must be exactly the same as the original file. It turned out that even if the files had the same exact size, to the byte, they weren't identical, how was that possible ?

Symptom:

After uploading a file larger than the packet size (default to 4 MB), the resulting copy was not identical to the original.

Simple test:

Upload a zip file larger than 4 MB, try to open it. It was corrupt.

The most uprising fact was that if I ran the .NET 4 version it still worked as expected ! Next, I migrated the solution to .NET 4.7 and still worked as expected, apparently it was only affecting to .NET Core version. So, under the circumstance, I tried to compare request / response side by side working version vs bugged version.

A few things looked a bit suspicious:

  • some extra headers sent on .NET working version
  • Transfer-Encoding: chunked from .NET Core bugged version

None of those were related. Back to square one.

I tried reducing the packet size to 1024 bytes and upload a text file so I could see how the content differed but no luck, it was indeed the same (verified comparing documents with Diff tool) Well now deep debugging showed that the buffer wasn't being written completely to output file, that would explain the corrupted resulting file but not the size difference. Let's see the code.

Original version

var buffer = new byte[contentLength];
var bytesread = inputStream.Read(buffer, 0, buffer.Length);
if (bytesread > 0)
{
    using (var fs = File.Open(actualfile, FileMode.Append, FileAccess.Write))
    {
        fs.Write(buffer, 0, buffer.Length);
    }
    //json.Data = new {guid, packet};
    return new UploadPacketResult(guid, packet);
}

Spot something weird ?

It turns out that Stream.Read can perform a blocking operation that reads up to the length specified but not necessarily the whole buffer, now it's obvious! but how it didn't fail before !! I don't have an answer for that :)

Well, here is the fixed version

var buffer = new byte[contentLength];
using (var fs = File.Open(actualfile, FileMode.Append, FileAccess.Write))
{
    int read = 0;
    while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fs.Write(buffer, 0, read);
    }
}
//json.Data = new {guid, packet};
return new UploadPacketResult(guid, packet);

And that's the way it was supposed to be done in the first place, but there was no test case that proved otherwise (until now, 4 years later)

Monday, 3 February 2014

Reusing common mocking functionality using Moq

Last month I wrote how to mock a repository in a generic way using mocking framework Moq. The example I used to illustrate the scenario was a pure generic repository, let's see it again:
public interface IIdentityKey<Tkey>
{
    TKey Id { get; set; }
}

public interface IRepository<Tkey,TEntity> 
    where TEntity : IIdentityKey<Tkey>
{
    IQueryable<TEntity> All();
 
    TEntity FindBy(TKey id);
 
    TEntity Add(TEntity entity);
 
    void Update(TEntity entity);
 
    void Delete(TEntity entity);
}
However, in real life, this is not always achievable, sometimes we need specific repositories per entity, let's make a change to that example, for instance, adding a new field named GroupId to Person entity.
public class Person :  IIdentityKey<long>
{
    public long Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public long GroupId { get; set; }
}
Thus, the new repository would need a new method named GetByGroup, but only for this repository, hence the new repository interface looks like this:
public interface IPersonRepository : IRepository<long, Person>
{
    IQueryable<Person> GetByBroup(long groupId); 
}
When trying to mock the behaviour it's more or less the same as in previous example except for the fact that we have an additional method GetByGroup, so it's not fair having to implement or even worst, copy and paste the boilerplate previously implemented. We need some way to set up the common behaviour to any inheritor of IRepository<TK,TE>. However, an object of type Mock<IPersonRepository> can not be assigned to an object of type Mock<IRepository<TK,TE>>. What to do?

Well, the class Mock<T> inherits from Mock without generics, we can create a method that accepts a Mock as parameter, but how do we treat that parameter as concrete typed object? Fortunately, the Mock class contains a method As<T> which returns the mock as a typed object specified in generic argument.

Finally, the rest is only to move the common set up to that new method, here is my sample:
public static void SetupRepositoryMock<TK, TE>(Mock mockRepo, List<TE> data)
    where TE : class, IIdentityKey<TK>
{
    var mock = mockRepo.As<IRepository<TK, TE>>();

    // setup All method
    mock.Setup(x => x.All()).Returns(data.AsQueryable());

    // setup Add method
    mock.Setup(x => x.Add(It.IsAny<TE>()))
        .Returns(new Func<TE, TE>(x =>
        {
            dynamic lastId = data.Last().Id;
            dynamic nextId = lastId + 1;
            x.Id = nextId;
            data.Add(x);
            return data.Last();
        }));

    // setup Update method
    mock.Setup(x => x.Update(It.IsAny<TE>()))
        .Callback(new Action<TE>(x =>
        {
            var i = data.FindIndex(q => q.Id.Equals(x.Id));
            data[i] = x;
        }));

    // setup FindBy (id)
    mock.Setup(x => x.FindBy(It.IsAny<TK>()))
        .Returns(new Func<TK, TE>(
            x => data.Find(q => q.Id.Equals(x))
        ));

    // setup Delete
    mock.Setup(x => x.Delete(It.IsAny<TE>()))
        .Callback(new Action<TE>(x =>
        {
            var i = data.FindIndex(q => q.Id.Equals(x.Id));
            data.RemoveAt(i);
        }));
}
Now, our method CreateController would look like this.
private PersonController CreateController()
{
    // create the mock to specific repository
    var mock = new Mock<IPersonRepository>();

    // set up the common methods 
    SetupRepositoryMock<long, Person>(mock, _fakedata);

    // start mocking specific methods
    mock.Setup(x => x.GetByBroup(It.IsAny<long>()))
        .Returns(new Func<long, IQueryable<Person>>(
            gid => _fakedata.Where(x => x.GroupId == gid).AsQueryable())
        );

    PersonController target = new PersonController(mock.Object);
    return target;
}
As the goal was only to implement the mock for the specific method to the repository interface, it was achieved by invoking SetupRepositoryMock<TK,TE> for common base methods and followed by the implementation of specific method. The full sample source code can be downloaded here.

Sunday, 19 January 2014

Mocking a repository using Moq

Some time ago, I wrote about how to mock a repository in a generic way, so the it behaves accordingly using the supplied fake data which is no more than a list of objects of the same type of the repository we are mocking, of course. When I did that, I used RhinoMocks as mocking framework and I confess I'm a big fan of that as I consider it very versatile and powerful, but after having read this news about the current state of RhinoMocks, I decided to switch to another one.

I'm not trying to say that as soon as a good project is left behind from its creator, it means that the users should go away from it, as Ayende says as for this goal, it's done, in my opinion that latest release of RhinoMocks could be useful for the next 5 years. The new owner seems to have good ideas for the next versions of RhinoMocks. However, the community and life in general is moving at a different speed and sometimes we have to find a substitute even if we like the current one item.

According to the community, after some research on the internet and based on several well-documented stackoverflow answers, Moq is the best alternative, it's based on Linq and Expressions and it can be used in very simple ways which is good for the increasing amount of developers who are starting to use TDD or just trying to automate some tests.
Let's refresh the simple repository interfaces to be mocked:
public interface IIdentityKey<Tkey>
{
    TKey Id { get; set; }
}
public interface IRepository<Tkey,TEntity> where TEntity : IIdentityKey<Tkey>
{
    IQueryable<TEntity> All();
 
    TEntity FindBy(TKey id);
 
    TEntity Add(TEntity entity);
 
    void Update(TEntity entity);
 
    void Delete(TEntity entity);
}
In our controller we use this interface as it will be injected using any IoC such as Ninject, but important here is that the controller doesn't know or even cares the actual implementation of this repository, this is a fragment of our controller:
public class PersonController : ApiController
{
    private readonly IRepository<long, Person> _repository;  
 
    public PersonController(IRepository<long, Person> repository)
    {
        _repository = repository;
    }
 
    // GET api/person
    public IEnumerable<Person> Get()
    {
        return _repository.All().ToArray();
    }
 
    // the rest of the code removed for brevity ...
}
We need to create the 5 methods previously mentioned in the interface in a way that they make the operations on a list with initial data, such as this:
private List<Person> _fakedata = new List<Person> {
    new Person { Id = 1, Name = "Person1", Email = "person1@nomail.com" },
    new Person { Id = 2, Name = "Person2", Email = "person2@nomail.com" },
    //  ( ... )
    new Person { Id = 8, Name = "Person8", Email = "person8@nomail.com" }
};
Let's start with the actual mock creation and set up now using Moq
private IRepository<TK, TE> CreateRepository<TK, TE>(List<TE> data)
    where TE : class, IIdentityKey<TK>
{
    var mock = new Mock<IRepository<TK, TE>>();

    // all the mocking setup goes here ...

    return mock.Object;
}
The actual mock procedure is made through the combination of Setup(...).Returns(...) and Setup(...).Callback(...) for methods that return something and void respectively. The All() method is done this way.
// setup All method
mock.Setup(x => x.All()).Returns(data.AsQueryable());
The Returns() method accepts an object of the same type as the return type in Setup() argument or a Func with return type the same as declared in Setup, so it matches the signature at runtime. In that example it's just return the raw list previously declared.
// setup Add method
mock.Setup(x => x.Add(It.IsAny<TE>()))
    .Returns(new Func<TE, TE>(x => {
        dynamic lastId = data.Last().Id;
        dynamic nextId = lastId + 1;
        x.Id = nextId;
        data.Add(x);
        return data.Last();
    }));
The Add() method is implemented using a bit more complex behaviour in order to simulate the auto incremental in database helped by dynamics for not to force a concrete type as in C# there's no generic constraint for only numeric types.
// setup Update method
mock.Setup(x => x.Update(It.IsAny<TE>()))
    .Callback(new Action<TE>(x =>
    {
        var i = data.FindIndex(q => q.Id.Equals(x.Id));
        data[i] = x;
    }));

// setup FindBy (id)
mock.Setup(x => x.FindBy(It.IsAny<TK>()))
    .Returns(new Func<TK, TE>(
        x => data.Find(q => q.Id.Equals(x))
    ));

// setup Delete
mock.Setup(x => x.Delete(It.IsAny<TE>()))
    .Callback(new Action<TE>(x => {
        var i = data.FindIndex(q => q.Id.Equals(x.Id));
        data.RemoveAt(i);
        }
    ));

Following the same idea, we've got the remaining methods from the interface implementation. Earlier I mentioned a generic method which accepts two arguments: TK and TE related to type of key and of entity, now it will be called by another method for this specific controller.
        
private PersonController CreateController()
{
    IRepository<long, Person> repo = CreateRepository<long, Person>(_fakedata);
    PersonController target = new PersonController(repo);
    return target;
}
Finally, the test should look like this fragment:
  
[TestMethod]
public void Get()
{
    // Arrange
    PersonController controller = CreateController();

    // Act
    IEnumerable<Person> result = controller.Get();

    // Assert
    Assert.IsNotNull(result);
    Assert.AreEqual(8, result.Count());
    Assert.AreEqual("Person1", result.ElementAt(0).Name);
    Assert.AreEqual("Person8", result.ElementAt(7).Name);
}

[TestMethod]
public void GetById()
{
    // Arrange
    PersonController controller = CreateController();

    // Act
    Person result = controller.Get(5);

    // Assert
    Assert.AreEqual("Person5", result.Name);
}
We invoke the CreateController method on each test so the logic previously described is encapsulated and then a new instance of the controller with the mocked repository inside. The sample code can be downloaded here.

Saturday, 29 June 2013

ExcelHandler updated version

About a year ago, I published the first release of the ExcelHandler library with the corresponding first NuGet package, it was the first experience with these powerful way of sharing code with the community. Since then, the time has passed and several things have happened, I received a pull request from Paulo Rezende that came with a good addition regarding to be able to get the number of sheets for a workbook, he also has some good ideas that I want to discuss with him and some of those are already in an experimental branch.

When looking for some kind of automatization at the moment of generating and publishing the NuGet Package, found an interesting Visual Studio Extension named NuGet.PackageNPublish.Extension that adds a new project template with the skeleton of a nuget package, it uses the text templating for recreate the .nuspec file each time the project is rebuilt and extracts as much as it can form the metadata in AssemblyInfo.cs file which is a good idea because the version and file names are prone to be out of synchronization when done manually.

Some of the improvement added to this library include: updated dependencies to newer versions, the NPOI and EPPlus libraries also evolved through the months, so there were some breaking changes that were changed in internal implementations for each dependency. Finally I added an automated test project, so it's not more necessary to run the console application sample. New elements in interfaces are:
  • NumberOfSheets property in IExcelHandler interface, now it's possible to know the amount of sheets in a workbook.
  • CreateSheet(string) method in IExcelHandler interface, now it's possible to add new sheets to a workbook.
  • LoadExelFile(string) doesn't require the file exists in both implementations, so it can also be used to create new Excel files and not just for editing existing ones.
The current version of source code can be found at https://bitbucket.org/abelperezok/excelhandler/ and the NuGet Package at https://nuget.org/packages/ExcelHandler/. Hope this to be useful and any comment or issue will be welcome.

Tuesday, 30 April 2013

Using Web API filter for Polymorphic results

When starting a little deeper with Web API I found a block on the road: if I returned any object different of the return type declared in the action method signature, then the serialization mechanism throw an exception related to the type instantiated is not expected, the error message is like this: "Type 'Mvc4AppFilter.Models.Student' with data contract name 'Student:http://schemas.datacontract.org/2004/07/Mvc4AppFilter.Models' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer." when trying to serialize as XML, JSON works like a charm, why is this happening?
If we find the source code for class System.Net.HttpHttpRequestMessageExtensions at method with this signature, because there are several overloads:
public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, HttpConfiguration configuration)
We found the things related to content negotiation and checking for proper values from configuration, but at the end there's something like this:
return new HttpResponseMessage
{
    Content = new ObjectContent<T>(value, result.Formatter, mediaType),
    StatusCode = statusCode,

    RequestMessage = request
};
and the key point is that if the typeof(T) is not equal to value.GetType() then the ObjectContent throws the exception because of the mismatching of types and that occurs when for example we declare the method with return type Person and for some reason we return either a Worker object or Student object (where both inherit from Person)

The first solution was to extract the important sentences from this source code and create my own extension for CreateResponse and using the ObjectContent non generic version, but later I decided to group this code in a Filter, in this case an Action filter, and it will be executed after each action is executed, the goal is to transform the any object return type action to a properly configured HttpResponseMessage. Here's the code.
public class HttpResponseFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var request = actionExecutedContext.Request;
        var response = actionExecutedContext.Response;
        if (response.Content != null && !response.Content.IsHttpResponseMessageContent() && response.Content is ObjectContent) 
        {
            var objContent = response.Content as ObjectContent;
            var value = objContent.Value;
            var result = request.CreateResponse(System.Net.HttpStatusCode.OK);
            if (value != null)
            {
                var config = request.GetConfiguration();
                var negociator = config.Services.GetContentNegotiator();
                var nresult = negociator.Negotiate(value.GetType(), request, config.Formatters);
                result.Content = new ObjectContent(value.GetType(), value, nresult.Formatter);
            }
            actionExecutedContext.Response = result;
        }
    }
}

Finally, we need to register the filter in application startup, i.e. in the file out of the box WebApiConfig.cs by adding this line:
config.Filters.Add(new HttpResponseFilter());
Hope it helps you to improve your code, the source can be downloaded here.

Monday, 1 April 2013

Mocking a repository using RhinoMocks

Unit testing is often a tedious and repetitive task, even if we are testing controllers for Web API, the main goal for the code to be testable is the separation of concerns, so the parts can be tested separately and in an isolated way. To achieve this it's necessary to supply the dependencies to our target testing code. Here is where the mocks come to the scene.

One code that is usually mocked is the repositories, the mocked objects are in the form: when the method X is invoked with argument Y then return Z, or something around that. An actual repository can be mocked using an in memory list of the same entity.

We can do this by two ways: one is to implement the repository interface with an actual class that hides that in memory list, but as the application grows, the number of these fake classes will grow too, I discourage this practice as non-scalable. The other way is to use a mocking framework and there are a lot of them and can be found at nuget, I'll use RhinoMocks for this post.

The code for mocking can be quite cryptic using this kind of framework, but in the long term is better than writing actual fake code, the goal for faking repositories is to keep the data consistency so if we add a new item to the list, we can verify the count and see that there is one more or if we remove one item, and so on.

Let's start with the repository interface, this is very simple repository in order to have less things to do in the example and keep complexity off.
    
    public interface IIdentityKey<Tkey>
    {
        TKey Id { get; }
    }
    public interface IRepository<Tkey,TEntity> where TEntity : IIdentityKey<Tkey>
    {
        IQueryable<TEntity> All();

        TEntity FindBy(TKey id);

        TEntity Add(TEntity entity);

        void Update(TEntity entity);

        void Delete(TEntity entity);
    }

In our controller we use this interface as it will be injected using any IoC such as Ninject, but important here is that the controller doesn't know or even cares the actual implementation of this repository, this is a fragment of our controller:
    
    public class PersonController : ApiController
    {
        private readonly IRepository<long, Person> _repository;  

        public PersonController(IRepository<long, Person> repository)
        {
            _repository = repository;
        }

        // GET api/person
        public IEnumerable<Person> Get()
        {
            return _repository.All().ToArray();
        }

        // the rest of the code removed for brevity ...
    }

Now it's the time for constructing the mock object, but first a quick recipe on using RhinoMocks for creating mock objects:

    MockRepository mocks = new MockRepository();
    IRepository<long, Person> repo = mocks.Stub<IRepository<long, Person>>();
    using (mocks.Record())
    {
        // Method constructing here
    }

We need to create the 5 methods previously mentioned in the interface in a way that they make the operations on a list with initial data, such as this:

    private List<Person> _fakedata = new List<Person> {
        new Person { Id = 1, Name = "Person1", Email = "person1@nomail.com" },
        new Person { Id = 2, Name = "Person2", Email = "person2@nomail.com" },
        //  ( ... )
        new Person { Id = 8, Name = "Person8", Email = "person8@nomail.com" }
    };

Or if the objects are more complex with relationships, might be using for loop, nonetheless the data is created. Let's see the method stubs for the operations to be mocked, for that, we use the combination of the the Stub(...).Return(...) and Stub(...).Do(...) the easiest operation is the Get without parameters and looks like this:

// setup All method
repo.Stub(x => x.All()).Return(_fakedata.AsQueryable());

Here we are just saying, when you call the method All, then return the _fakedata object as queryable, this simple because the method have no parameters. Let's see now the Add method, which has a parameter and returns a value, it's intended to accept the object that is to be added and returns the object in a state after inserted.

    // setup Add method
    repo.Stub(x => x.Add(Arg<Person>.Is.Anything))
        .Do(new Func<Person, Person>(
            x =>
            {
                _fakedata.Add(x);
                return _fakedata.Last();
            }
        ));

In this operation we tell to the mock that when the Add method is invoked with an argument of type Person without any constraint, at this point it can be set any kind of constraint like if is null or not null or equals or greater than, etc. but as we are mocking the operation for customize the action, we use no constraint. The Do accepts a generic delegate, that's why it's necessary to specify the concrete delegate like Func<Person,Person> that matches the signature of the operation we want to mock and the parameter expressed as a lambda expression where x is the only parameter, the logic is simple but we can include more realistic work like set the Id by getting the maximum Id and adding one, the key point here is to add the item to our list.

Using a similar technique we can implement the Update, FindBy and Delete operations, as follows:

    // setup Update method
    repo.Stub(x => x.Update(Arg<Person>.Is.Anything))
        .Do(new Action<Person>(x =>
        {
            var i = _fakedata.FindIndex(q => q.Id == x.Id);
            _fakedata[i] = x;
        }));

    // setup FindBy
    repo.Stub(x => x.FindBy(Arg<long>.Is.Anything))
        .Do(new Func<long, Person>(
            x => _fakedata.Find(q => q.Id == x)
        ));

    // setup Delete
    repo.Stub(x => x.Delete(Arg<Person>.Is.Anything))
        .Do(new Action<Person>(
            x => _fakedata.Remove(x)
        ));

Now, the test should look like this fragment:

    [TestMethod]
    public void Get()
    {
        // Arrange
        PersonController controller = CreateController();

        // Act
        IEnumerable<Person> result = controller.Get();

        // Assert
        Assert.IsNotNull(result);
        Assert.AreEqual(8, result.Count());
        Assert.AreEqual("Person1", result.ElementAt(0).Name);
        Assert.AreEqual("Person8", result.ElementAt(7).Name);
    }

    [TestMethod]
    public void GetById()
    {
        // Arrange
        PersonController controller = CreateController();

        // Act
        Person result = controller.Get(5);

        // Assert
        Assert.AreEqual("Person5", result.Name);
    }

Where the CreateController method contains all the logic previously described and returns a new instance of the controller with the mocked object passed as parameter in the constructor, The sample code can be downloaded here.