using System.Reflection; using AutoFixture; using AutoFixture.Kernel; using AutoMapper; using Bit.Core.Settings; using Bit.Core.Test.Helpers.Factories; using Bit.Infrastructure.EntityFramework.Models; using Bit.Infrastructure.EntityFramework.Repositories; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Moq; namespace Bit.Core.Test.AutoFixture.EntityFrameworkRepositoryFixtures { internal class ServiceScopeFactoryBuilder : ISpecimenBuilder { private DbContextOptions _options { get; set; } public ServiceScopeFactoryBuilder(DbContextOptions options) { _options = options; } public object Create(object request, ISpecimenContext context) { var fixture = new Fixture(); var serviceProvider = new Mock(); var dbContext = new DatabaseContext(_options); serviceProvider .Setup(x => x.GetService(typeof(DatabaseContext))) .Returns(dbContext); var serviceScope = new Mock(); serviceScope.Setup(x => x.ServiceProvider).Returns(serviceProvider.Object); var serviceScopeFactory = new Mock(); serviceScopeFactory .Setup(x => x.CreateScope()) .Returns(serviceScope.Object); return serviceScopeFactory.Object; } } public class EfRepositoryListBuilder : ISpecimenBuilder where T : BaseEntityFrameworkRepository { public object Create(object request, ISpecimenContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var t = request as ParameterInfo; if (t == null || t.ParameterType != typeof(List)) { return new NoSpecimen(); } var list = new List(); foreach (var option in DatabaseOptionsFactory.Options) { var fixture = new Fixture(); fixture.Customize(x => x.FromFactory(new ServiceScopeFactoryBuilder(option))); fixture.Customize(x => x.FromFactory(() => new MapperConfiguration(cfg => { cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); cfg.AddProfile(); }) .CreateMapper())); var repo = fixture.Create(); list.Add(repo); } return list; } } public class IgnoreVirtualMembersCustomization : ISpecimenBuilder { public object Create(object request, ISpecimenContext context) { if (context == null) { throw new ArgumentNullException("context"); } var pi = request as PropertyInfo; if (pi == null) { return new NoSpecimen(); } if (pi.GetGetMethod().IsVirtual && pi.DeclaringType != typeof(GlobalSettings)) { return null; } return new NoSpecimen(); } } }