1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-30 13:33:24 +01:00
bitwarden-server/test/Common/AutoFixture/Attributes/EnvironmentDataAttribute.cs

43 lines
1.7 KiB
C#
Raw Normal View History

using System.Reflection;
using Xunit.Sdk;
2022-08-29 22:06:55 +02:00
namespace Bit.Test.Common.AutoFixture.Attributes;
/// <summary>
/// Used for collecting data from environment useful for when we want to test an integration with another service and
/// it might require an api key or other piece of sensitive data that we don't want slipping into the wrong hands.
/// </summary>
/// <remarks>
/// It probably should be refactored to support fixtures and other customization so it can more easily be used in conjunction
/// with more parameters. Currently it attempt to match environment variable names to values of the parameter type in that positions.
/// It will start from the first parameter and go for each supplied name.
/// </remarks>
public class EnvironmentDataAttribute : DataAttribute
{
2022-08-29 22:06:55 +02:00
private readonly string[] _environmentVariableNames;
public EnvironmentDataAttribute(params string[] environmentVariableNames)
2022-08-29 20:53:16 +02:00
{
2022-08-29 22:06:55 +02:00
_environmentVariableNames = environmentVariableNames;
}
2022-08-29 22:06:55 +02:00
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
var methodParameters = testMethod.GetParameters();
2022-08-29 22:06:55 +02:00
if (methodParameters.Length < _environmentVariableNames.Length)
2022-08-29 20:53:16 +02:00
{
2022-08-29 22:06:55 +02:00
throw new ArgumentException($"The target test method only has {methodParameters.Length} arguments but you supplied {_environmentVariableNames.Length}");
}
2022-08-29 20:53:16 +02:00
2022-08-29 22:06:55 +02:00
var values = new object[_environmentVariableNames.Length];
2022-08-29 22:06:55 +02:00
for (var i = 0; i < _environmentVariableNames.Length; i++)
{
values[i] = Convert.ChangeType(Environment.GetEnvironmentVariable(_environmentVariableNames[i]), methodParameters[i].ParameterType);
}
2022-08-29 22:06:55 +02:00
return new[] { values };
}
}