Configuration settings and tests in a Continuous Delivery world

Today I’ll write about an anti-pattern that I see quite often, regarding the usage of configuration settings. Settings stored in configuration files such as web.config or app.config are a dependency that should be abstracted in order to make your code more flexible and testable!

In this article I’ll show you:

  • Some of the problems of using the configuration settings
  • How to refactor your code in order to make it more testable
  • How to refactor your tests in order to make them CI/CD friendly

The problem – testing code that uses configuration settings

Let’s suppose you are creating a service class that uses a 3rd party REST API. API’s username, password and endpoint are stored in the configuration file as follows:

<appSettings>
    <add key="myApi.Username" value="myusername" />
    <add key="myApi.Password" value="mypassword" />
    <add key="myApi.Endpoint" value="https://www.myapi.com/v1" />
</appSettings>

Consider the following code:

public class FooService
{
	private readonly string _myApiUsername;
	private readonly string _myApiPassword;
	private readonly string _myApiEndpoint;

	public FooService()
	{
		_myApiUsername = GetConfigValue("myApi.Username");
		_myApiPassword = GetConfigValue("myApi.Password");
		_myApiEndpoint = GetConfigValue("myApi.Endpoint");
	}

	private string GetConfigValue(string key)
	{
		string value = ConfigurationManager.AppSettings[key];

		if (string.IsNullOrWhiteSpace(value))
		{
			string message = $"Could not find AppSettings[\"{key}\"]!";
			throw new InvalidOperationException(message);
		}

		return value;
	}

	// code omitted for brevity
}

The first problem comes when you try to write some unit tests for this class. Using this approach will force you to have a configuration file in your unit test project, which is not a big deal.

What if you needed to use different values to test other scenarios, such as testing if an InvalidOperationException is thrown when the username, password or endpoint are null or whitespace? You’d have to find a way to override the AppSettings section of the configuration file (ugly stuff, trust me). I’ll show you next how to refactor the code to make it more testable.

Making the code unit-test friendly

Please note that this is not the best solution but just the first step to make your code more testable. This is ideal for people that, for some reason, cannot spend much time refactoring the code.

The trick is to change the constructor to take an optional NameValueCollection parameter. If this parameter is not set then it will try to get the values from the configuration file (using the ConfigurationManager.AppSettings object):

public class FooService
{
    private readonly NameValueCollection _appSettings;

    private readonly string _myApiUsername;
    private readonly string _myApiPassword;
    private readonly string _myApiEndpoint;

    public FooService(NameValueCollection appSettings = null)
    {
        _appSettings = appSettings ?? ConfigurationManager.AppSettings;

        _myApiUsername = GetConfigValue("myApi.Username");
        _myApiPassword = GetConfigValue("myApi.Password");
        _myApiEndpoint = GetConfigValue("myApi.Endpoint");
    }

    private string GetConfigValue(string key)
    {
        string value = _appSettings[key];

        if (string.IsNullOrWhiteSpace(value))
        {
            string message = $"Could not find AppSettings[\"{key}\"]!";
            throw new InvalidOperationException(message);
        }

        return value;
    }

    // service methods go here
}

Setting the values in a unit test is easy:

// arrange 
var settings = new NameValueCollection {
    {"myApi.Username", "myusername"},
    {"myApi.Password", "mypassword"},
    {"myApi.Endpoint", "myendpoint"}
};

var service = new FooService(settings);

// act
// ....

// assert
// ....

Another example – testing if an exception is thrown when the username is empty:

// arrange 
var settings = new NameValueCollection {
    {"myApi.Username", ""},
    {"myApi.Password", "mypassword"},
    {"myApi.Endpoint", "myendpoint"}
};

FooService service = null;

// act/ assert
Assert.Throws<InvalidOperationException>(() => {
    service = new FooService(settings);
});

Code is now testable, cool! I am now able to use different settings and run tests on my machine (“it works on my machine”, hurray!). But this is not good enough!

Making the code testable and CI/CD friendly

The previous refactoring is a very quick way to make code testable, but it can be improved in terms of testability and readability. The first thing I don’t like is the usage of a NameValueCollection object that contains the settings, I’d rather define an interface and a class like these ones:

public interface IApiSettings
{
    string MyApiEndpoint { get; }
    string MyApiPassword { get; }
    string MyApiUsername { get; }
}

public class ApiSettings : IApiSettings
{
    public string MyApiUsername { get; }
    public string MyApiPassword { get; }
    public string MyApiEndpoint { get; }


    public ApiSettings(string myApiUsername, string myApiPassword, string myApiEndpoint)
    {
        if (string.IsNullOrWhiteSpace(myApiUsername))
        {
            throw new ArgumentException("Username cannot be null or whitespace.", nameof(myApiUsername));
        }

        if (string.IsNullOrWhiteSpace(myApiPassword))
        {
            throw new ArgumentException("Password cannot be null or whitespace.", nameof(myApiPassword));
        }

        if (string.IsNullOrWhiteSpace(myApiEndpoint))
        {
            throw new ArgumentException("Endpoint cannot be null or whitespace.", nameof(myApiEndpoint));
        }

        MyApiUsername = myApiUsername;
        MyApiPassword = myApiPassword;
        MyApiEndpoint = myApiEndpoint;
    }
}

Refactoring FooService, one more time:

public class FooService
{
    private readonly IApiSettings _settings;

    public FooService(IApiSettings settings)
    {
        _settings = settings ?? throw new ArgumentNullException(nameof(settings));
    }

    // service methods go here
}

Now let’s talk again about the tests – things are a bit different when we’re running tests in a build or deployment pipeline, comparing to our local machine.

Different environments will have different configuration settings (connection strings, API endpoints, etc) so it’s extremely important to know what is the current environment and load the corresponding settings.

Also, where do we store these settings? We have at least these options:

  • Create one configuration file per environment
  • Configure environment variables per environment

It’s probably easier to use configuration files locally, what about the build/deployment pipeline? Using the configuration files might be an option for some environments but not for others such as Production (for security reasons). These settings can be set (manually or dynamically) using environment variables in the build/deployment pipeline.

I have used the following approach that works for both scenarios:

  • if the environment variable exists then use it
  • otherwise, use the value from the configuration file

Just to be completely clear, the environment variable takes precedence over the setting from the configuration file. I have created an helper class that will be used to get the right values to be used in the tests, according to the approach above:

public static class ConfigurationHelper
{
    public static string GetEnvironmentOrConfigValue(string key, string defaultValue = null)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            throw new ArgumentException("Value cannot be null or whitespace.", nameof(key));
        }

        string value = GetEnvironmentValue(key);

        if (!string.IsNullOrWhiteSpace(value))
        {
            return value;
        }

        value = GetConfigValue(key);

        if (!string.IsNullOrWhiteSpace(value))
        {
            return value;
        }

        return defaultValue;
    }

    private static string GetConfigValue(string key)
    {
        string value = ConfigurationManager.AppSettings[key];

        return value;
    }

    private static string GetEnvironmentValue(string key)
    {
        string variableName = string.Concat("appSettings_", key.Replace(".", "_"));
        string value = Environment.GetEnvironmentVariable(variableName);

        return value;
    }

Refactoring the tests:

// arrange
var username = ConfigurationHelper.GetEnvironmentOrConfigValue("myApi.Username");
var password = ConfigurationHelper.GetEnvironmentOrConfigValue("myApi.Password");
var endpoint = ConfigurationHelper.GetEnvironmentOrConfigValue("myApi.Endpoint");

var settings = new ApiSettings(username, password, endpoint);
var service = new FooService(settings);

// act
// ....

// assert
// ....

A quick note – you can have the same names for both the appSettings and the environment variables or follow a naming convention. In my example above, configuration setting “myApi.Username” would correspond to the environment variable “appSettings_myApi_Username“. You can use any convention you want.

So, for the following configuration settings

<appSettings>
    <add key="myApi.Username" value="myusername" />
    <add key="myApi.Password" value="mypassword" />
    <add key="myApi.Endpoint" value="https://www.myapi.com/v1" />
</appSettings>

I’d need to configure the corresponding environment variables in the build server, for each environment. Something like this:

vsts_env_variables

(Please note that this screenshot was taken from a demo release definition I created in Visual Studio Team Services (VSTS) that contains 3 environments: QA, UAT, Production).

That’s it! When the tests are run in the build server they will use the environment variables values defined above. Another good thing of this approach is that you can use both values from the configuration file and the environment variables in the build server.

Happy coding!

On software job interviews: asking the right questions

Sometimes all it takes is a few buzzwords such as microservices, serverless, cloud, DevOps etc for us, software developers, to get excited when reading a job offer – we all like to work with the latest trends, tools and programming languages, but that is not enough if you you want to work on a good team with good practices. Who doesn’t dream about working for a company with a great culture and engineering practices such as Amazon, Microsoft, Facebook, Google or Netflix? I surely do!

One of the mistakes that some software developers do when applying for a new job is not trying to understand what is the level of quality of the current software team of the company you’re applying for – I confess I did that mistake in the past! The technologies might be cool but that doesn’t say much about the team and/or working culture. Just to give you an idea, I worked recently for a company that was using cool technologies but didn’t even have a build server when I started working there! Nor were they using any methodology such as SCRUM. Luckily things improved a bit but it took a while (too long, IMO) before that happened.

So if you want to evaluate the quality of a software team you need to make the right questions – but what are these questions? You might start with the Joel Test, which contains 12 yes-no questions to rate the quality of a software team:

joel-test

Even though the original blog post was written on August, 2000 these questions are still very relevant in 2018, and this test is being used in StackOverflow Jobs portal (where I took the screenshot from), which contains some of the best software development job descriptions out there IMO. I’d love to see these test results in every single software development job description out there!

Other questions you might ask (some are related to Joel Test):

  • Which version control system do you use?
  • Do you write automated tests (unit tests, integration tests, etc)?
  • Do you use Continuous Integration/Continuous Delivery?
  • Do you do code reviews and/or pair programming?
  • Do you use design patterns/SOLID principles?
  • Which tools do you use?
  • Which methodologies do you use? SCRUM? Lean? Kanban? XP? Others?
  • Do you offer technical training to the team members or allow them to attend technical conferences?
  • Do you have technical meetings?
  • (Any other questions that might give you an idea about how the team works or is organised)

That’s it! Remember that a job interview works two ways:

  • A company wants to find the best candidate for a given position
  • A candidate (you!) wants to find the best company/team

So the interview it’s not only about answering some technical and HR questions, you need to ask the right questions about the company and working culture too. Don’t be afraid to prepare some sort of check-list containing some of the questions I mentioned above (and others that might be important to you) and ask them somewhere during the interview process – or, as an alternative, send an email asking someone (such as a team leader) to answer them. If it is a good company with good people I’m pretty sure they will get back to you!

This post is on how to rate the quality of a software team but there are many other questions you can (and should!) ask on an interview process – for example, take a look at  The Programmer’s Bill of Rights regarding working conditions for software developers.

Good luck!

Why I don’t pick up the phone

This happens to me all the time – recruiters trying to call me or sending me emails or messages on LinkedIn, telling me about a great role available and asking me if I’m available for a quick chat over the phone.

2bur32

My answer is NO – I don’t want to have a quick chat with the recruiters over the phone, at least not at the very beginning of the recruitment process.

I don’t want to make recruiter’s life difficult, but I feel that most of the times it’s a complete waste of time (no offense) – mine and recruiter’s time. Why? Here are some of the reasons:

  1. I have no interest in new opportunities. This is quite obvious – if I’m not interested in new opportunities it makes no sense to have a chat over the phone. No need to waste time.
  2. There’s no concrete project. Recruiters need to add profiles to their systems/databases and many times they will call candidates even if there is no opportunity available at the moment. Please don’t waste my time, send me an email when there is a concrete project and we’ll talk about it.
  3. I want to save the message for future reference. This is one of the most important reasons for not wanting to pick up the phone – it’s impossible to remember most or all the details for each role that recruiters send! Having an email with a job spec and other details such as benefits, salary, etc makes my life easier.
  4. I want to have some time to analyse the role. “What do you think, Rui?” – over the phone there is more pressure to give a yes-or-no response, at the moment. Having an email with the description of the role/company/etc means I can take a look at it when I have some spare time, and take my time to analyse it and even do some research about the company, etc and then decide if it is of interest or not.
  5. Role doesn’t match my profile. Sad but true – I receive many messages from recruiters regarding roles that have absolutely nothing to do with my profile! Java, PHP or Python opportunities? QA roles? Sysadmin roles? Network engineer roles? Seriously? I’m a .NET software engineer!
  6. Role is of no interest. Even if the role do match my profile, it doesn’t mean it is an interesting one. For example, I have absolutely no interest in support roles or roles that use old/obsolete technologies.
  7. Location is of no interest. There is a shortage of IT candidates with good experience, so recruiters will try to find talent everywhere, not only within their local recruitment market. I get messages from not only European but also other countries such as the United States! Most of the people won’t be available to move to other cities or countries without a very good reason.
  8. I’m at work. Recruiters need to get in touch with potential candidates and many times they will call during working time, but if I’m working I cannot (or shouldn’t) pick up the phone 3 or 4 times a day to talk with a recruiter – I have work to do. Also, that wouldn’t be very professional, don’t you think? And a complete lack of respect to my current employer. Just leave me an email and I’ll get back to you.

I believe there are many other IT guys like me that feel the same way about this. Let me say it again – I don’t want to make a recruiter’s life difficult, I just want to avoid wasting time (mine and theirs).

So, ideally a recruiter will send an email or LinkedIn message with a good job description (containing a quick description of the company, location, industry, summary of the role, responsibilities, skills and experience, salary, …) such as this one I saw on jobserve.com:

role1
If the role is of interest then yes! I will be available for a chat over the phone, to ask for more details or clarify any doubt 🙂