m1nkeh
m1nkeh

Reputation: 1397

Read values from local.setting.json while debugging test

i don't seem to be able to read anything from this file in an azure functions when running or debugging a test, however it works fine when debugging the whole application locally.. can anyone explain why at all ?

{
  "IsEncrypted": false,
  "Values": {
    "xyz": 123
  }
}

var res = ConfigurationManager.AppSettings.Get("xyz");

ty..

my suspicion is that it is due to the 'debug' being initiated from another project (Test project), and the local.settings.json does not get bundled up with the project being tested ?

Upvotes: 9

Views: 7863

Answers (2)

sillo01
sillo01

Reputation: 614

I added the settings programatically to minify the chances that sensitive data reach version control.

class LocalSettings
{
    public bool IsEncrypted { get; set; }
    public Dictionary<string, string> Values { get; set; }
}

public static void SetupEnvironment()
{
    string basePath = Path.GetFullPath(@"..\..\..\MyAzureFunc");
    var settings = JsonConvert.DeserializeObject<LocalSettings>(
        File.ReadAllText(basePath + "\\local.settings.json"));

    foreach (var setting in settings.Values)
    {
        Environment.SetEnvironmentVariable(setting.Key, setting.Value);
    }
}

Upvotes: 21

Drew Marsh
Drew Marsh

Reputation: 33379

Your suspicion is spot on. Only the Azure Functions Runtime Host actually knows to read settings from that file and merge them into the overall AppSettings. When you run in a test project, the Azure Functions Runtime Host is not involved and therefore you don't get access to them.

The simplest way to solve this would be to reflect all the same setting keys/values into your test project's app.config file under the standard <appSettings> section.

Upvotes: 6

Related Questions