1
0
mirror of https://github.com/bitwarden/server.git synced 2024-11-25 12:45:18 +01:00
bitwarden-server/test/Common/Helpers/BitAutoDataAttributeHelpers.cs
Matt Gibson f9fd83d809 Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.

Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
2021-11-12 20:48:59 -05:00

56 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoFixture;
using AutoFixture.Kernel;
using AutoFixture.Xunit2;
using Bit.Test.Common.AutoFixture.Attributes;
namespace Bit.Test.Common.Helpers
{
public static class BitAutoDataAttributeHelpers
{
public static IEnumerable<object[]> GetData(MethodInfo testMethod, IFixture fixture, object[] fixedTestParamters)
{
var methodParameters = testMethod.GetParameters();
var classCustomizations = testMethod.DeclaringType.GetCustomAttributes<BitCustomizeAttribute>().Select(attr => attr.GetCustomization());
var methodCustomizations = testMethod.GetCustomAttributes<BitCustomizeAttribute>().Select(attr => attr.GetCustomization());
fixedTestParamters = fixedTestParamters ?? Array.Empty<object>();
fixture = ApplyCustomizations(ApplyCustomizations(fixture, classCustomizations), methodCustomizations);
var missingParameters = methodParameters.Skip(fixedTestParamters.Length).Select(p => CustomizeAndCreate(p, fixture));
return new object[1][] { fixedTestParamters.Concat(missingParameters).ToArray() };
}
public static object CustomizeAndCreate(ParameterInfo p, IFixture fixture)
{
var customizations = p.GetCustomAttributes(typeof(CustomizeAttribute), false)
.OfType<CustomizeAttribute>()
.Select(attr => attr.GetCustomization(p));
var context = new SpecimenContext(ApplyCustomizations(fixture, customizations));
return context.Resolve(p);
}
public static IFixture ApplyCustomizations(IFixture fixture, IEnumerable<ICustomization> customizations)
{
var newFixture = new Fixture();
foreach (var customization in fixture.Customizations.Reverse().Select(b => b.ToCustomization()))
{
newFixture.Customize(customization);
}
foreach (var customization in customizations)
{
newFixture.Customize(customization);
}
return newFixture;
}
}
}