如何在dotnet核心测试项目中使用用户机密

时间:2017-01-30 17:06:34

标签: unit-testing configuration .net-core app-secret

我想将集成测试的数据库连接字符串存储为用户密码。我的project.json看起来像这样:

function rescheduleDriversJobs() {

//Get an exlusive lock on the sheet

var lock = LockService.getScriptLock();
try {
   lock.waitLock(2000);
 } catch (e) {

 //Displayes a browser message if unable to get an exclusive lock on the sheet
   Browser.msgBox('Another script is running. Please try again later');

//Releases the lock if unable to get an exclusive lock on the sheet
   lock.releaseLock();

//Cancels the Script   
   return;
 }

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.setActiveSheet(ss.getSheetByName('Sheet Name'));
  var sheet = ss.getSheetByName('Sheet Name');
  var clearrange = sheet.getRange(3, 1, sheet.getLastRow() - 1, sheet.getLastColumn());
    var targetSheet = ss.getSheetByName('Completed Jobs');
    var val = sheet.getRange(3, 1, sheet.getLastRow() - 1, sheet.getLastColumn())
        .getValues();

//Builds the arrays    
   var arr = [],
        rowsToWriteBack = [];
        rowsToWriteBack.push();

//populates the arrays    

    val.forEach(function (r, i) {
    if (r[3] === 'Completed') {

    //Adds Date and Time stamp to Column N of the "Completed Jobs" sheet
      r[13] = Utilities.formatDate(new Date(), "GMT-4", "MM-dd-yyyy EEE hh:mm a");

//Adds the name of the driver completing the job to Column O of the "Completed Jobs" sheet
      r[14]="Driver Name";
      arr.push(r)
    } else {
      rowsToWriteBack.push(r)
   }
});


   if (arr.length > 0) {

    //Inserts empty rows after the header row of the "Completed Jobs" sheet to populate with array data
    targetSheet.insertRowsBefore(2, arr.length)

    //Selects the range on the target sheet to be populated with data from the array (The empty rows we just created with the above line)
    targetSheet.getRange(2, 1, arr.length, arr[0].length)

    //Send the data to the target sheet
    .setValues(arr);

//Clears that data that has been moved
     clearrange.clear({contentsOnly:true});
      sheet.getRange(3, 1, rowsToWriteBack.length, rowsToWriteBack[0].length)
      .setValues(rowsToWriteBack);
    }

//Releases the lock so other scripts can run    
lock.releaseLock();

}

我已将以下内容添加到我的测试类的构造函数中:

{
  ...

  "dependencies": {
    ...
    "Microsoft.Extensions.Configuration.UserSecrets": "1.1.0"        
  },

  "tools": {
    "Microsoft.Extensions.SecretManager.Tools": "1.1.0-preview4-final"
  },

  "userSecretsId": "dc5b4f9c-8b0e-4b99-9813-c86ce80c39e6"
}

然而,当我运行测试时,当它到达该行时抛出以下异常:

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddUserSecrets();

我是否遗漏了某些内容,或者是我试图不支持的内容?

3 个答案:

答案 0 :(得分:4)

请参阅https://patrickhuber.github.io/2017/07/26/avoid-secrets-in-dot-net-core-tests.html中的说明,特别是在InitialiseTest add

// the type specified here is just so the secrets library can 
            // find the UserSecretId we added in the csproj file
            var builder = new ConfigurationBuilder()
                .AddUserSecrets<HttpClientTests>();

            Configuration = builder.Build()

但请注意,它不允许在构建服务器上运行测试

答案 1 :(得分:2)

您必须在应用程序的Startup中指定UserSecretsId。

[assembly: UserSecretsId("xxx")]
namespace myapp
{
    public class Startup
    {
    ...

然后你必须在测试项目中使用.AddUserSecrets(Assembly assembly)的重载。例如:

.AddUserSecrets(typeof(Startup).GetTypeInfo().Assembly)

来源:https://stackoverflow.com/a/40775511/5270073

答案 2 :(得分:-3)

对于设置,您可以使用appsettings.json,而不是project.json。它看起来像这样:

{
    "userSecretsId": "dc5b4f9c-8b0e-4b99-9813-c86ce80c39e6"
}

确保通过更改project.json:

将文件复制到输出
"buildOptions": {
    "copyToOutput": "appsettings.json"
}

现在您可以像这样检索秘密:

[Fact]
public MyTest()
{
    var appSettings = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    var secret = appSettings["userSecretsId"]
}