Git squash multiple commits into one

If you ever have a scenario where you have to make a lot of changes to a branch but commit regularly so you can go back during this process if something fails BUT when you are done as a whole none of those commits actually matter except the last one (historically it will be off no use to see what was changing between revisions) you can do this in git:

Note: Before you do this all your changes need to have been committed, make sure you have nothing staged.

git reset –soft <sha_of_initial_commit>
git commit -a –amend -m “commit message”

Advertisements

Making Nunit tests execute in order

Have you ever wanted to run a given suite of Nunit tests in order? Normally your tests should be created in such a way that execution order is no concern. I stand by that rule, however there is that one edge case were you need to break that rule. The one scenario I came across was with R.NET whereby in a given process you can only initialize one R Engine and once disposed you cannot reinitialize. One of my test happened to deal with disposing the engine and if this test were to run before any other test(s) they would fail.

You will find below a code snippet of how I managed to get this to run in order using Nunit.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using RSamples;

    public class OrderedTestAttribute : Attribute
    {
        public int Order { get; set; }

        public OrderedTestAttribute(int order)
        {
            this.Order = order;
        }
    }

    public class TestStructure
    {
        public Action Test;
    }

    public class SampleTests
    {
        [TearDown]
        public void CleanUpAfterTest()
        {
            REngineExecutionContext.ClearLog();
        }

        [OrderedTest(0)]
        public void Test1(){}

        [OrderedTest(1)]
        public void Test2(){}

        [OrderedTest(2)]
        public void Test3(){}

        [TestCaseSource(sourceName: "TestSource")]
        public void MainTest(TestStructure test)
        {
            test.Test();
        }

        public static IEnumerable<TestCaseData> TestSource
        {
            get
            {
                var assembly = Assembly.GetExecutingAssembly();
                Dictionary<int, List<MethodInfo>> methods = assembly
                    .GetTypes()
                    .SelectMany(x => x.GetMethods())
                    .Where(y => y.GetCustomAttributes().OfType<OrderedTestAttribute>().Any())
                    .GroupBy(z => z.GetCustomAttribute<OrderedTestAttribute>().Order)
                    .ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());

                foreach (var order in methods.Keys.OrderBy(x => x))
                {
                    foreach (var methodInfo in methods[order])
                    {
                        MethodInfo info = methodInfo;
                        yield return new TestCaseData(
                            new TestStructure
                            {
                                Test = () =>
                                {
                                    object classInstance = Activator.CreateInstance(info.DeclaringType, null);
                                    info.Invoke(classInstance, null);
                                }
                            }).SetName(methodInfo.Name);
                    }
                }
            }
        }
    }

Why can’t I use Assert.Equals?

Ever wondered why you cannot use Assert.Equals() for both Nunit and MSTest. If you have not then maybe as a start you need to be aware that you cannot use this method. Instead you would use Assert.AreEqual() to compare two objects for equality.

The reason here is very simple. Like any class the Assert class is inheriting from System.Object that has a public virtual Equals method meant to check if a given object is equal to the current object. Therefor calling that equals method would be a mistake as in a unit test you would instead to compare two objects that have nothing to do with the Assert class. As a result Nunit and MSTest both chose to provide a method Assert.AreEqual for that purpose.

Furthermore to ensure that you do not use the Equals method by mistake they have decided to throw Exceptions to warn you if you do use this by mistake.

Nunit Implementation:


        [EditorBrowsable(EditorBrowsableState.Never)]
        public static new bool Equals(object a, object b)
        {
            // TODO: This should probably be InvalidOperationException
            throw new AssertionException("Assert.Equals should not be used for Assertions");
        }

MSTest Implementation:


        public new static bool Equals(object objA, object objB)
        {
            Assert.Fail((string)FrameworkMessages.DoNotUseAssertEquals);
            return false;
        }

Can you interact with user in current context?

Ever had to write a generic implementation of a feature that should interact with a user if possible otherwise use an alternative.

An example would be an exception handling manager that would show a message box to the user for certain exception if there is a U.I say in a WPF app else log to the event viewer say in a Windows service. Fortunately there is an easy way to find out if the current context is interactive as follows:

Environment.UserInteractive

 

InternalsVisibleTo useful

One of the not so commonly usage attributes targeting assemblies is the InternalsVisibleTo attribute. This attribute declares that a given assembly will be given access to internal items in the assembly it is declared on.

This can be very useful with unit testing if you want to have access to internal items or in scenarios were you want to create a new assembly as a wrapper around one of your existing assemblies you may want to give it those privileges. A good place to stick this in is the AssemblyInfo.cs class with usage as shown below. By using this feature you create what can be called Friend libraries.

[assembly: InternalsVisibleTo("TargetAssembly, PublicKey=<key>")]

Multiple usings bundled

Interesting thing to note. While you can bundle multiple using together by nesting as shown in example 1, you can totally avoid the nesting by removing some braces and still have the same effect as shown in example 2. You may expect that the first object will immediately be disposed before the next line executes but this is syntactic sugar to work as the first example.

Example 1:


            using (var a = new Test())
            {
                using (var b = new Test())
                {

                }
            }

Example 2:


            using (var a = new Test())
            using (var b = new Test())
            {

            }

 

Make custom types support object initializers

In C# you can easily make your custom types support object initializers by doing two things

  • Implement IEnumerable<T>
  • Add a public void method called Add accepting the type desired intializer type as a parameter

Example:

Implement IEnumerable<T>


    public class ProgrammingLanguage:IEnumerable&lt;string&gt;
    {
        private readonly HashSet&lt;string&gt; supportedTypes = new HashSet&lt;string&gt;();

        public IEnumerator&lt;string&gt; GetEnumerator()
        {
            return this.supportedTypes.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }

Add the Add method


        public void Add(string name)
        {

        }

Sample usage:


            var javaScript = new ProgrammingLanguage{&quot;int&quot;,&quot;bool&quot;,&quot;string&quot;};

Update:

Interestingly for an object to be enumerable and say qualify to be iterated by foreach it does not have implement IEnumerable. Instead it simply has to have a public method GetEnumerator that returns a type with a public bool MoveNext and public void Current. The compiler does not actually check to see if the interface is implemented.