Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            //Register XpoWebApiProvider
            XpoWebApiProvider.Register();



            var ConnectionString = XpoWebApiProvider.GetConnectionString("https://localhost:44389", "/XpoWebApi", string.Empty, "001");

            XpoInitializer xpoInitializer = new XpoInitializer(ConnectionString, typeof(Invoice), typeof(Customer));

            xpoInitializer.InitSchema();

            using (var UoW = xpoInitializer.CreateUnitOfWork())
            {
                var faker = new Bogus.Faker <Customer>().CustomInstantiator(c => new Customer(UoW))
                            .RuleFor(p => p.Code, f => f.Random.Guid())
                            .RuleFor(p => p.Name, f => f.Name.FullName())
                            .RuleFor(p => p.Active, p => p.Random.Bool());

                var Customers = faker.Generate(100);
                if (UoW.InTransaction)
                {
                    UoW.CommitChanges();
                }

                var UoWFromApi       = xpoInitializer.CreateUnitOfWork();
                var CustomersFromApi = new XPCollection <Customer>(UoWFromApi);
                foreach (var item in CustomersFromApi)
                {
                    Console.WriteLine(item.Name);
                }
                Console.ReadKey();
            }
        }
Ejemplo n.º 2
0
        public LGTokenFaker(IManageDatabase databaseManager, ILogger logger)
        {
            var random       = new Random();
            int randomNumber = random.Next();

            Bogus.Randomizer.Seed = new Random(randomNumber);

            var parentFaker      = new LGAccountFaker(databaseManager, logger);
            var parent           = parentFaker.GetOne();
            var parentRepository = new LGAccountRepository(databaseManager, new LGAccountRepositorySql(), logger);
            var parentAddResult  = parentRepository.Create(parent);

            parent = parentAddResult.Model;

            _faker = new Bogus.Faker <LGToken>()
                     .StrictMode(false)
                     .Rules((f, m) =>
            {
                m.LGTokenId   = null;
                m.LGAccountId = parent.LGAccountId;
                m.Token       = f.Lorem.Sentence(10);
                m.Created     = f.Date.Past();
                m.LastUsed    = f.Date.Past();
                m.Expires     = f.Date.Past();
            });
        }
Ejemplo n.º 3
0
            protected override void Seed(ApiDbContext context)
            {
                string[] ativos = { "AZUL4", "GOLL4", "ELET3", "USIM5", "ELET6", "GOAU4", "EMBR3", "COGN3", "PETR4", "PETR3", "GGBR4", "BRML3", "BBAS3", "CMIG4", "CVCB3", "CSNA3", "BRAP4", "SMLS3", "ENBR3", "MRVE3" };

                var orderIds      = 0;
                var fakeOperacoes = new Bogus.Faker <Operation>()
                                    .StrictMode(true)
                                    .RuleFor(x => x.Id, f => orderIds++)
                                    .RuleFor(x => x.DateTime, f => f.Date.Between(DateTime.Now.AddDays(-1), DateTime.Now))
                                    .RuleFor(x => x.OperationType, f => f.PickRandom("C", "V"))
                                    .RuleFor(x => x.Active, f => f.PickRandom(ativos))
                                    .RuleFor(x => x.Quantity, f => f.Random.Int(10, 2000))
                                    .RuleFor(x => x.Price, f => f.Random.Decimal(10, 100))
                                    .RuleFor(x => x.AccountNumber, f => f.Random.Int(1111, 999999));

                context.Operations.AddRange(fakeOperacoes.Generate(20000).ToList());
                context.SaveChanges();

                foreach (var file in Directory.GetFiles(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory?.Replace("WebApi", "DataAccess"), "StoredProcedures")), "*.sql"))
                {
                    context.Database.ExecuteSqlCommand(File.ReadAllText(file), new object[0]);
                }

                base.Seed(context);
            }
        public async Task GetAccounts_WithoutAccess_ShouldFail()
        {
            Bogus.Faker faker    = new Bogus.Faker();
            var         identity = faker.Random.Identity();

            var accountUserFaker    = new Common.Fakers.AccountUserFaker();
            var master              = accountUserFaker.Generate();
            var newAccountUserFaker = accountUserFaker
                                      .RuleFor(au => au.UserId, master.UserId)
                                      .RuleFor(au => au.UserDescription, master.AccountDescription);

            var originalAccountUserList = newAccountUserFaker.Generate(3);

            var mockAuthorizationService = new Mock <IAuthorizationService>();

            mockAuthorizationService.Setup(a => a.CheckAuthorizedUser(identity, master.UserId, AccessType.Read)).ReturnsAsync(false);

            var mockUserRepository = new Mock <IUserRepository>();

            mockUserRepository.Setup(ur => ur.GetAccounts(master.UserId)).ReturnsAsync(originalAccountUserList);

            var userQueryHandler = new UserQueryHandler(mockAuthorizationService.Object, mockUserRepository.Object);
            await Assert.ThrowsAsync <UnauthorizedAccessException>(async() => await userQueryHandler.GetAccounts(identity, master.UserId));

            mockUserRepository.VerifyNoOtherCalls();
        }
Ejemplo n.º 5
0
        public TodoEntryFaker(IManageDatabase databaseManager, ILogger logger)
        {
            var random       = new Random();
            int randomNumber = random.Next();

            Bogus.Randomizer.Seed = new Random(randomNumber);

            var entryStatusFaker      = new TodoStatusFaker(databaseManager, logger);
            var entryStatusFake       = entryStatusFaker.GetOne();
            var entryStatusRepository = new TodoStatusRepository(databaseManager, new TodoStatusRepositorySql(), logger);
            var entryStatusFakeResult = entryStatusRepository.Create(entryStatusFake);

            entryStatusFake = entryStatusFakeResult.Model;

            _faker = new Bogus.Faker <TodoEntry>()
                     .StrictMode(false)
                     .Rules((f, m) =>
            {
                m.TodoEntryId      = null;
                m.Summary          = f.Lorem.Sentence(10);
                m.Details          = f.Lorem.Sentence(10);
                m.DueDate          = f.Date.Past();
                m.EntryStatusIdRef = entryStatusFake.TodoStatusId;
            });
        }
        private void AddTaskResults()
        {
            var candidates = _identityDbContext.Users
                             .Where(u => u.Roles
                                    .Any(r => r.RoleId == _identityDbContext.Roles
                                         .FirstOrDefault(s => s.Name == GlobalInfo.Candidate).Id));

            if (!candidates.Any())
            {
                throw new InvalidOperationException("No candidates exist.");
            }

            if (!_appDbContext.CandidateTasks.Any())
            {
                throw new InvalidOperationException("No tasks exist.");
            }

            foreach (var candidate in candidates)
            {
                int i           = 0;
                var taskResults = new Bogus.Faker <TaskResult>()
                                  .RuleFor(r => r.CreatorId, candidate.DomainId)
                                  .RuleFor(r => r.ModifierId, candidate.DomainId)
                                  .RuleFor(r => r.CandidateExercise, f => _appDbContext.CandidateTasks.ToArray().ElementAt(i++))
                                  .RuleFor(r => r.UsedTipsNumber, (f, r) => f.Random.Number(((Task)r.CandidateExercise).Tips.Count()))
                                  .RuleFor(r => r.IsCompleted, true)
                                  .RuleFor(r => r.Score, (f, r) => r.CandidateExercise.MaximumScore - r.UsedTipsNumber)
                                  .RuleFor(r => r.Code, (f, r) => ((Task)r.CandidateExercise).CodeTemplate)
                                  .Generate(_appDbContext.CandidateTasks.Count());
                _appDbContext.CandidateTaskResults.AddRange(taskResults);
            }

            _appDbContext.SaveChanges();
        }
Ejemplo n.º 7
0
        private async Task CheckAuthorizedAccount(bool hasIdentity, bool admin)
        {
            Bogus.Faker faker    = new Bogus.Faker();
            var         identity = faker.Random.Identity();

            var accountUserFaker = new Common.Fakers.AccountUserFaker();
            var master           = accountUserFaker.Generate();

            var mockUserRepository = new Mock <IUserRepository>();

            mockUserRepository.Setup(ur => ur.CheckAdminScope(identity, AccessType.Read)).ReturnsAsync(admin);

            var mockAccountRepository = new Mock <IAccountRepository>();

            mockAccountRepository.Setup(ar => ar.CheckIdentity(master.AccountId, identity)).ReturnsAsync(hasIdentity);

            var authorizationService = new AuthorizationService(mockUserRepository.Object, mockAccountRepository.Object);
            var result = await authorizationService.CheckAuthorizedAccount(identity, master.AccountId, AccessType.Read);

            Assert.Equal(hasIdentity || admin, result);

            if (!hasIdentity)
            {
                mockUserRepository.Verify(ur => ur.CheckAdminScope(identity, AccessType.Read));
            }
            mockUserRepository.VerifyNoOtherCalls();

            mockAccountRepository.Verify(ar => ar.CheckIdentity(master.AccountId, identity));
            mockAccountRepository.VerifyNoOtherCalls();
        }
        public async Task GetAccount_ShouldSucceed()
        {
            Bogus.Faker faker    = new Bogus.Faker();
            var         identity = faker.Random.Identity();

            var accountId    = faker.Random.Guid();
            var accountFaker = new AccountFaker().RuleFor(a => a.Id, accountId);
            var account      = accountFaker.Generate();

            var logger = new Mock <ILogger <UserController> >();
            var mapper = new MapperConfiguration(c => c.AddProfile <AutoMapperProfile>()).CreateMapper();

            var mockIdentityRetriever = new Mock <IIdentityRetriever>();

            mockIdentityRetriever.Setup(uqh => uqh.GetIdentity(It.IsAny <ControllerBase>())).Returns(identity);

            var mockAccountQueryHandler = new Mock <IAccountQueryHandler>();

            mockAccountQueryHandler.Setup(aqh => aqh.GetAccount(identity, accountId)).ReturnsAsync(account);

            var accountController = new AccountController(logger.Object, mapper, mockIdentityRetriever.Object, mockAccountQueryHandler.Object);

            var result = await accountController.GetAccount(accountId);

            var actionResult    = Assert.IsType <ActionResult <AccountResponse> >(result);
            var okObjectResult  = Assert.IsType <OkObjectResult>(actionResult.Result);
            var accountResponse = Assert.IsType <AccountResponse>(okObjectResult.Value);

            Assert.Equal(accountId, accountResponse.Id);
            accountResponse.ShouldDeepEqual(account);

            mockAccountQueryHandler.Verify(aqh => aqh.GetAccount(It.Is <string>(s => s.Equals(identity)), It.Is <Guid>(s => s.Equals(accountId))));
            mockAccountQueryHandler.VerifyNoOtherCalls();
        }
Ejemplo n.º 9
0
        private static void FillTable()
        {
            DbContextOptionsBuilder bld = new DbContextOptionsBuilder();

            bld.UseSqlServer(conStr);
            PeopleContext ctx = new PeopleContext(bld.Options);

            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();

            var hobbies = new Bogus.Faker <Hobby>()
                          .RuleFor(h => h.Description, fk => fk.Company.CatchPhrase())
                          .Generate(1000).ToArray();

            var people = new Bogus.Faker <Person>()
                         .RuleFor(p => p.FirstName, fk => fk.Name.FirstName())
                         .RuleFor(p => p.LastName, fk => fk.Name.LastName())
                         .RuleFor(p => p.Age, fk => fk.Random.Int(0, 123))
                         .Generate(100).ToArray();

            var ph = new Bogus.Faker <PersonHobby>()
                     .RuleFor(ph => ph.Hobby, fk => fk.Random.ArrayElement(hobbies))
                     .RuleFor(ph => ph.Person, fk => fk.Random.ArrayElement(people))
                     .Generate(100).ToList();

            foreach (var p in ph)
            {
                ctx.PersonHobbies.Add(p);
            }
            ctx.SaveChanges();
        }
Ejemplo n.º 10
0
        public static async Task CreateTooManyTransactionsAsync()
        {
            using (var client = new DocumentClient(_endpointUri, _primaryKey))
            {
                await client.OpenAsync();

                var collectionLink = UriFactory.CreateDocumentCollectionUri(_databaseId, _transactionCollectionId);
                var transactions   = new Bogus.Faker <Transaction>()
                                     .RuleFor(
                    t => t.amount,
                    fake => Math.Round(fake.Random.Double(5, 500), 2))
                                     .RuleFor(
                    t => t.processed,
                    fake => fake.Random.Bool(0.6f))
                                     .RuleFor(
                    t => t.paidBy,
                    fake => $"{fake.Name.FirstName().ToLower()}.{fake.Name.LastName().ToLower()}")
                                     .RuleFor(
                    t => t.costCenter,
                    fake => fake.Commerce.Department(1).ToLower())
                                     .GenerateLazy(5000);
                var tasks = new List <Task <ResourceResponse <Document> > >();
                foreach (var transaction in transactions)
                {
                    var resultTask = client.CreateDocumentAsync(collectionLink, transaction);
                    tasks.Add(resultTask);
                }
                Task.WaitAll(tasks.ToArray());
                foreach (var task in tasks)
                {
                    await Console.Out.WriteLineAsync($"Document Created\t{task.Result.Resource.Id}");
                }
            }
        }
Ejemplo n.º 11
0
        public LGAccountFaker(IManageDatabase databaseManager, ILogger logger)
        {
            var random       = new Random();
            int randomNumber = random.Next();

            Bogus.Randomizer.Seed = new Random(randomNumber);

            var roleFaker      = new LGRoleFaker(databaseManager, logger);
            var roleFake       = roleFaker.GetOne();
            var roleRepository = new LGRoleRepository(databaseManager, new LGRoleRepositorySql(), logger);
            var roleFakeResult = roleRepository.Create(roleFake);

            roleFake = roleFakeResult.Model;

            _faker = new Bogus.Faker <LGAccount>()
                     .StrictMode(false)
                     .Rules((f, m) =>
            {
                m.LGAccountId = null;
                m.LastName    = f.Name.LastName(0);
                m.FirstName   = f.Name.FirstName(0);
                m.MiddleName  = f.Name.FirstName(0);
                m.UserName    = f.Internet.UserName(m.FirstName, m.LastName);
                m.Email       = f.Internet.Email(m.FirstName, m.LastName);
                m.Password    = f.Lorem.Sentence(10);
                m.RoleIdRef   = roleFake.LGRoleId;
            });
        }
Ejemplo n.º 12
0
        public static async Task PopulateCollectionWithDifferentDataType()
        {
            using (var client = new DocumentClient(_endpointUri, _primaryKey))
            {
                await client.OpenAsync();

                var collectionLink = UriFactory.CreateDocumentCollectionUri(
                    "EntertainmentDatabase",
                    "CustomCollection");

                var tvInteractions = new Bogus.Faker <WatchLiveTelevisionChannel>()
                                     .RuleFor(i => i.type, (fake) => nameof(WatchLiveTelevisionChannel))
                                     .RuleFor(i => i.minutesViewed, (fake) => fake.Random.Number(1, 45))
                                     .RuleFor(i => i.channelName, (fake) => fake.PickRandom(new List <string> {
                    "NEWS-6", "DRAMA-15", "ACTION-12", "DOCUMENTARY-4", "SPORTS-8"
                }))
                                     .Generate(500);
                foreach (var interaction in tvInteractions)
                {
                    var result = await client.CreateDocumentAsync(collectionLink, interaction);

                    await Console.Out.WriteLineAsync(
                        $"Document #{tvInteractions.IndexOf(interaction):000} Created\t{result.Resource.Id}");
                }
            }
        }
Ejemplo n.º 13
0
        public static async Task PopulateCollection()
        {
            using (var client = new DocumentClient(_endpointUri, _primaryKey))
            {
                await client.OpenAsync();

                var collectionLink = UriFactory.CreateDocumentCollectionUri(
                    "EntertainmentDatabase",
                    "CustomCollection");

                var foodInteractions = new Bogus.Faker <PurchaseFoodOrBeverage>()
                                       .RuleFor(i => i.type, (fake) => nameof(PurchaseFoodOrBeverage))
                                       .RuleFor(i => i.unitPrice, (fake) => Math.Round(fake.Random.Decimal(1.99m, 15.99m), 2))
                                       .RuleFor(i => i.quantity, (fake) => fake.Random.Number(1, 5))
                                       .RuleFor(i => i.totalPrice, (fake, user) => Math.Round(user.unitPrice * user.quantity, 2))
                                       .Generate(500);
                foreach (var interaction in foodInteractions)
                {
                    var result = await client.CreateDocumentAsync(collectionLink, interaction);

                    await Console.Out.WriteLineAsync(
                        $"Document #{foodInteractions.IndexOf(interaction):000} Created\t{result.Resource.Id}");
                }
            }
        }
        public MaterialProductDecorator(IProduct product) : base(product)
        {
            string _name = new Bogus.Faker().Commerce.ProductMaterial();

            Name = String.Format("{0} {1}", char.ToUpper(_name[0]) + _name.Substring(1), Name);
            DecoratedWith.Add("Material");
        }
Ejemplo n.º 15
0
        public ImprovedProductDecorator(IProduct product) : base(product)
        {
            string _name = new Bogus.Faker().Commerce.ProductAdjective();

            Name = String.Format("{0} {1}", char.ToUpper(_name[0]) + _name.Substring(1), Name);
            DecoratedWith.Add("Improved");
        }
Ejemplo n.º 16
0
        public DatabaseFixture()
        {
            DbContextOptionsBuilder <TestDbContext> builder = new();

            var personid  = 1;
            var addressId = 1;

            Bogus.Faker <Address> addressGen(Person p, int addressId)
            => new Bogus.Faker <Address>()
            .RuleFor(x => x.Id, f => addressId++)
            .RuleFor(x => x.Street, f => f.Address.StreetAddress())
            .RuleFor(x => x.ZipCode, f => f.Address.ZipCode())
            .RuleFor(x => x.Person, f => p)
            .RuleFor(x => x.PersonId, f => p.Id);

            var personGen = new Bogus.Faker <Person>()
                            .RuleFor(x => x.Id, f => personid++)
                            .RuleFor(x => x.Name, f => f.Name.FirstName())
                            .RuleFor(x => x.Surname, f => f.Name.LastName())
                            .RuleFor(x => x.Address, (f, u) => addressGen(u, addressId++));



            _people = Enumerable.Range(0, 200).Select(x => personGen.Generate()).ToList();
        }
Ejemplo n.º 17
0
        public void SendSMSTest()
        {
            var target = Moq.Mock.Of <SnailAbroadController>();

            var moqController = Moq.Mock.Get(target);

            moqController.Setup(c => c.DecreaseCredit()).Verifiable();
            // unit tests should never be delayed
            moqController.Setup(c => c.ApplyDelay()).Verifiable();


            var results = new List <WebApi.Models.SMSResult>();

            // send 100 mesagges
            for (var i = 0; i < 100; i++)
            {
                var faker = new Bogus.Faker();

                var httpResult = target.SendSMS(new Models.SmsRequest()
                {
                    username          = faker.Internet.UserName(),
                    password          = "******",
                    message           = faker.Lorem.Sentence(),
                    mobileNumber      = faker.Phone.PhoneNumber(),
                    messageExternalId = faker.Random.UInt().ToString()
                });

                results.Add(httpResult);
            }

            Assert.AreEqual(100, results.Count);
        }
Ejemplo n.º 18
0
        private static void WriteRandomDocuments(int noItems, string databaseId, string collectionId)
        {
            Stopwatch stopWatch = new Stopwatch();

            Console.WriteLine("Creating " + noItems.ToString() + " documents...");


            var categories = new[] { "apples", "bananas", "oranges", "grapes" };

            var productId = 0;
            var products  = new Bogus.Faker <Product>()
                            .StrictMode(true)
                            .RuleFor(o => o.Id, f => productId++)
                            .RuleFor(o => o.Category, f => f.PickRandom(categories))
                            .RuleFor(o => o.Description, f => f.Lorem.Paragraph())
                            .RuleFor(o => o.Image, f => f.Image.Food());

            var y = products.Generate(8);

            var orderItems = new Bogus.Faker <OrderItem>()
                             .StrictMode(true)
                             .RuleFor(o => o.Quantity, f => f.Random.Number(1, 1000))
                             .RuleFor(o => o.Product, f => products.Generate());

            var customerId = 0;
            var customers  = new Bogus.Faker <Customer>()
                             .StrictMode(true)
                             .RuleFor(o => o.CustomerID, f => customerId++)
                             .RuleFor(o => o.OrderTotal, f => f.Random.Double(0, 1000000))
                             .RuleFor(o => o.Person, f => new Bogus.Person());

            var orderId = 0;
            var orders  = new Bogus.Faker <Order>()
                          .StrictMode(true)
                          .RuleFor(o => o.Id, f => orderId++)
                          .RuleFor(o => o.Items, f => orderItems.Generate(10))
                          .RuleFor(o => o.DatePlaced, f => f.Date.Between(DateTime.Now.AddMonths(-15), DateTime.Now))
                          .RuleFor(o => o.Shipped, f => f.Random.Bool())
                          .RuleFor(o => o.ShippingState, f => f.Address.State())
                          .RuleFor(o => o.Customer, f => customers.Generate());

            var randomOrderDocuments = orders.Generate(noItems);

            Console.WriteLine();


            stopWatch.Start();
            foreach (Order order in randomOrderDocuments)
            {
                _client.CreateDocumentAsync(
                    UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), order);
            }

            stopWatch.Stop();

            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Finished creating " + noItems.ToString() + " documents in " + stopWatch.ElapsedMilliseconds + "ms.");
        }
Ejemplo n.º 19
0
        public MainViewModel(INavigation navigation)
        {
            var fake = new Bogus.Faker <BrandModel>()
                       .RuleFor(x => x.ColorCode, o => o.PickRandom(
                                    new[] {
                Color.AliceBlue.ToHex(),
                Color.Aqua.ToHex(),
                Color.BlueViolet.ToHex(),
                Color.Chocolate.ToHex(),
                Color.Cornsilk.ToHex(),
                Color.DarkGreen.ToHex(),
                Color.DarkOrange.ToHex(),
                Color.DeepPink.ToHex(),
                Color.Indigo.ToHex(),
            }
                                    ))
                       .RuleFor(x => x.HighlightUrl, o => o.Image.PicsumUrl())
                       .RuleFor(x => x.LogoUrl, o => o.Image.PicsumUrl())
                       .RuleFor(x => x.LongestWaitingTime, o => o.Random.Int(15, 60))
                       .RuleFor(x => x.Name, o => o.Company.CompanyName())
                       .RuleFor(x => x.Rating, o => o.Random.Double(0, 1))
                       .RuleFor(x => x.Remark, o => o.Lorem.Slug())
                       .RuleFor(x => x.ShortestWaitingTime, o => o.Random.Int(3, 12))
                       .RuleFor(x => x.PricingCategory, o => o.Random.CollectionItem(new[] { "$", "$$", "$$$", "$$$" }));

            var items = fake.Generate(100);

            Brands = new ObservableCollection <BrandModel>(items);

            ViewProductsCommand = new Command <BrandModel>(brand =>
            {
                navigation.PushAsync(new ProductsPage(brand));
            });
        }
Ejemplo n.º 20
0
 public async Task GennerateUser(List <Guid> countryEntities)
 {
     Bogus.Faker <UserViewModel> User = new Bogus.Faker <UserViewModel>()
                                        .StrictMode(true)
                                        .RuleFor(first => first.FirstName, f => f.Name.FirstName())
                                        .RuleFor(last => last.LastName, f => f.Name.LastName())
                                        .RuleFor(full => full.FulllName, f => f.Name.FullName())
                                        .RuleFor(avatar => avatar.Avatar, f => f.Internet.Avatar())
                                        .RuleFor(gender => gender.Gender, f => f.PickRandom <Gender>().GetStringValue())
                                        .RuleFor(date => date.DateOfBirth, f => f.Date.Soon())
                                        .RuleFor(ct => ct.CountryId, f => f.PickRandom(countryEntities))
                                        .RuleFor(pass => pass.Password, f => f.Internet.Password())
                                        .RuleFor(username => username.UserName, f => f.Internet.UserName())
                                        .RuleFor(t => t.Id, f => f.Internet.UserName())
                                        .RuleFor(t => t.TwoFactorEnabled, f => true)
                                        .RuleFor(t => t.SecurityStamp, f => f.Internet.Mac())
                                        .RuleFor(t => t.Roles, f => null)
                                        .RuleFor(t => t.PhoneNumberConfirmed, f => true)
                                        .RuleFor(t => t.PhoneNumber, f => f.Phone.PhoneNumber())
                                        .RuleFor(t => t.PasswordHash, f => f.Internet.Password())
                                        .RuleFor(t => t.Logins, f => null)
                                        .RuleFor(t => t.LockoutEndDateUtc, f => DateTime.Now)
                                        .RuleFor(t => t.LockoutEnabled, f => true)
                                        .RuleFor(t => t.EmailConfirmed, f => true)
                                        .RuleFor(t => t.Email, f => f.Internet.Email())
                                        .RuleFor(t => t.AccessFailedCount, f => f.Random.Int());
     UserService userService = new UserService();
     await userService.RegisterAccountUser(User.Generate());
 }
        public async Task GetIdentities_ShouldSucceed()
        {
            Bogus.Faker faker    = new Bogus.Faker();
            var         identity = faker.Random.Identity();

            var userIdentityFaker    = new Common.Fakers.UserIdentityFaker();
            var master               = userIdentityFaker.Generate();
            var newUserIdentityFaker = userIdentityFaker
                                       .RuleFor(au => au.UserId, master.UserId);

            var originalUserIdentityList = newUserIdentityFaker.Generate(3);

            var mockAuthorizationService = new Mock <IAuthorizationService>();

            mockAuthorizationService.Setup(a => a.CheckAuthorizedUser(identity, master.UserId, AccessType.Read)).ReturnsAsync(true);

            var mockUserRepository = new Mock <IUserRepository>();

            mockUserRepository.Setup(ur => ur.GetIdentities(master.UserId)).ReturnsAsync(originalUserIdentityList);

            var userQueryHandler   = new UserQueryHandler(mockAuthorizationService.Object, mockUserRepository.Object);
            var userIdentitiesList = await userQueryHandler.GetIdentities(identity, master.UserId);

            originalUserIdentityList.ShouldDeepEqual(userIdentitiesList);

            mockAuthorizationService.Verify(a => a.CheckAuthorizedUser(identity, master.UserId, AccessType.Read));
            mockAuthorizationService.VerifyNoOtherCalls();

            mockUserRepository.Verify(ur => ur.GetIdentities(master.UserId));
            mockUserRepository.VerifyNoOtherCalls();
        }
Ejemplo n.º 22
0
        public void GennerateCountry()
        {
            Bogus.Faker <CountryEntity> country = new Bogus.Faker <CountryEntity>()
                                                  .StrictMode(true)
                                                  .RuleFor(id => id.Id, f => Guid.NewGuid())
                                                  .RuleFor(zipcode => zipcode.ZipCode, f => f.Address.ZipCode())
                                                  .RuleFor(city => city.City, f => f.Address.City())
                                                  .RuleFor(streetadd => streetadd.StreetAddress, f => f.Address.StreetAddress())
                                                  .RuleFor(citypre => citypre.CityPrefix, f => f.Address.CityPrefix())
                                                  .RuleFor(citysuf => citysuf.CitySuffix, f => f.Address.CitySuffix())
                                                  .RuleFor(strname => strname.StreetName, f => f.Address.StreetName())
                                                  .RuleFor(building => building.BuildingNumber, f => f.Address.BuildingNumber())
                                                  .RuleFor(strsuffix => strsuffix.StreetSuffix, f => f.Address.StreetSuffix())
                                                  .RuleFor(ct => ct.Country, f => f.Address.Country())
                                                  .RuleFor(fulladd => fulladd.FullAddress, f => f.Address.FullAddress())
                                                  .RuleFor(code => code.CountryCode, f => f.Address.CountryCode())
                                                  .RuleFor(state => state.State, f => f.Address.State())
                                                  .RuleFor(stateAbb => stateAbb.StateAbbreviation, f => f.Address.StateAbbr())
                                                  .RuleFor(latitube => latitube.Latitude, f => f.Address.Latitude().ToString())
                                                  .RuleFor(longitube => longitube.Longitude, f => f.Address.Longitude().ToString())
                                                  .RuleFor(dir => dir.Direction, f => f.Address.Direction())
                                                  .RuleFor(card => card.CardinalDirection, f => f.Address.CardinalDirection())
                                                  .RuleFor(ord => ord.OrdinalDirection, f => f.Address.OrdinalDirection())
                                                  .RuleFor(date => date.CreateDate, f => DateTime.Now);
            CountryEntity result = country.Generate();

            db.Set <CountryEntity>().Add(result);
        }
Ejemplo n.º 23
0
        private void AddCandidates(int amount = 60)
        {
            var testCandidates = new Bogus.Faker <ApplicationUser>()
                                 .RuleFor(i => i.Email, f => f.Internet.ExampleEmail())
                                 .RuleFor(i => i.UserName, (f, i) => i.Email)
                                 .RuleFor(i => i.DomainId, Guid.NewGuid)
                                 .RuleFor(i => i.IsActive, true)
                                 .RuleFor(i => i.EmailConfirmed, true);

            var userProfiles = new Bogus.Faker <UserProfileInfo>()
                               .RuleFor(i => i.FirstName, f => f.Name.FirstName())
                               .RuleFor(i => i.LastName, f => f.Name.LastName())
                               .Generate(amount);

            var candidateRole = _identityDbContext.Roles.FirstOrDefault(role =>
                                                                        role.Name.Equals(GlobalInfo.Client, StringComparison.Ordinal));

            int j = 0;

            foreach (var candidate in testCandidates.Generate(amount))
            {
                if (_userManager.CreateAsync(candidate, "1").Result == IdentityResult.Success)
                {
                    _userManager.AddToRoleAsync(candidate.Id, candidateRole.Name).Wait();
                    _userManager.AddProfileAsync(candidate.DomainId, userProfiles[j++]).Wait();
                }
            }

            _identityDbContext.SaveChanges();
            _appDbContext.SaveChanges();
        }
Ejemplo n.º 24
0
        public static async Task addDocuments()
        {
            DateTime start = DateTime.Today.AddDays(-30);
            DateTime end   = DateTime.Today;

            using (DocumentClient client = new DocumentClient(_endpoint, _primaryKey))
            {
                await client.OpenAsync();

                Uri collection = UriFactory.CreateDocumentCollectionUri("SparkDatabase", "Twitter");

                var tweets_Generated = new Bogus.Faker <Tweet>()
                                       .RuleFor(i => i.like_Count, (fake) => fake.Random.Number(0, 100000))
                                       .RuleFor(i => i.comments_Count, (fake) => fake.Random.Number(0, 100000))
                                       .RuleFor(i => i.repost_Count, (fake) => fake.Random.Number(0, 100000))
                                       .RuleFor(i => i.deleted, (fake) => fake.Random.Bool())
                                       .RuleFor(i => i.tweetID, (fake) => fake.Random.Uuid().ToString())
                                       .RuleFor(i => i.userID, (fake) => fake.Random.Uuid().ToString())
                                       .RuleFor(i => i.created_At, (fake) => fake.Date.Between(start, end))
                                       .RuleFor(i => i.tweet_Content, (fake) => fake.Lorem.Text())
                                       .RuleFor(i => i.type, f => f.PickRandom <Type>().ToString())
                                       .Generate(10000000);


                foreach (var tweets in tweets_Generated)
                {
                    tweets.sequenceNumber = countOfRecords++;
                    ResourceResponse <Document> result = await client.CreateDocumentAsync(collection, tweets);

                    await Console.Out.WriteLineAsync($"Document #{tweets_Generated.IndexOf(tweets):000} Created\t{result.Resource.Id}\t with sequence number:{tweets.sequenceNumber}");
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// This class initializes the DB with fake data  usig bogus
        /// </summary>
        /// <param name="context"></param>
        public void Seed()
        {
            var faker = new Bogus.Faker();

            // Mock companies
            using (var db = new InsuranceDb())
            {
                for (var i = 0; i < 10; i++)
                {
                    db.Companies.Add(new EFModel.Company()
                    {
                        Id          = faker.Random.UShort().ToString(),
                        Description = faker.Company.CompanyName()
                    }
                                     );
                }
                db.SaveChanges();
            }
            // populate DB with mock entities
            for (var i = 0; i < 1000; i++)
            {
                using (var db2 = new InsuranceDb())
                {
                    db2.Configuration.AutoDetectChangesEnabled = false;
                    CreateMockContract(db2);
                }
            }
        }
        public async Task GetAccount_ShouldSucceed()
        {
            Bogus.Faker faker    = new Bogus.Faker();
            var         identity = faker.Random.Identity();

            var accountUserFaker = new Common.Fakers.AccountFaker();
            var originalAccount  = accountUserFaker.Generate();

            var mockAuthorizationService = new Mock <IAuthorizationService>();

            mockAuthorizationService.Setup(a => a.CheckAuthorizedAccount(identity, originalAccount.Id, AccessType.Read)).ReturnsAsync(true);

            var mockAccountRepository = new Mock <IAccountRepository>();

            mockAccountRepository.Setup(ar => ar.GetAccount(originalAccount.Id)).ReturnsAsync(originalAccount);

            var accountQueryHandler = new AccountQueryHandler(mockAuthorizationService.Object, mockAccountRepository.Object);
            var account             = await accountQueryHandler.GetAccount(identity, originalAccount.Id);

            originalAccount.ShouldDeepEqual(account);

            mockAuthorizationService.Verify(a => a.CheckAuthorizedAccount(identity, originalAccount.Id, AccessType.Read));
            mockAuthorizationService.VerifyNoOtherCalls();

            mockAccountRepository.Verify(ar => ar.GetAccount(originalAccount.Id));
            mockAccountRepository.VerifyNoOtherCalls();
        }
Ejemplo n.º 27
0
        public ClientServiceTest()
        {
            this.callService = new Mock <ICallService>();

            this.clientRepository = new Mock <IClientRepository>();
            this.addressRepo      = new Mock <IAddressRepository>();
            this.clientService    = new ClientService(this.callService.Object, this.clientRepository.Object, this.addressRepo.Object);
            var f = new Bogus.Faker("es");

            this.client = new Client()
            {
                Profile     = f.Random.Int(10000, 99999),
                Name        = f.Person.FirstName,
                LastName    = f.Person.LastName,
                MontlyPrice = double.Parse(f.Commerce.Price(decimals: 2)),
                Address     = ModelFakers.AddressFaker.Generate(1)[0],
            };

            var calls = ModelFakers.CallFaker.Generate(10).ToList();

            calls.ForEach(c =>
            {
                c.StartTime = 1.January(2017);
                this.client.Calls.Add(c);
            });

            var calls2 = ModelFakers.CallFaker.Generate(5).ToList();

            calls2.ForEach(c =>
            {
                c.StartTime = 1.February(2017);
                this.client.Calls.Add(c);
            });
        }
Ejemplo n.º 28
0
        public async Task <InsertResponse> GenerateHistoriesAsync(GenerateItemsRequest request)
        {
            var patientIds = await UserManager.GetUsersIdAsync(new UsersIdRequest
            {
                Amount   = request.Count,
                UserType = UserType.Patient
            });

            var doctorIds = await UserManager.GetUsersIdAsync(new UsersIdRequest
            {
                Amount   = request.Count,
                UserType = UserType.Doctor
            });

            var historyPoints = Builder <HistoryPoint> .CreateNew()
                                .With(e => e.CreationDate = Date.Between(new DateTime(1930, 1, 1), DateTime.UtcNow))
                                .With(e => e.Report       = Faker.Lorem.Paragraph());

            var histories = new Bogus.Faker <History>()
                            .RuleFor(u => u.Id, f => ObjectId.GenerateNewId().ToString())
                            .RuleFor(bp => bp.DoctorId, f => f.PickRandom(doctorIds))
                            .RuleFor(bp => bp.PatientId, f => f.PickRandom(patientIds))
                            .RuleFor(u => u.HistoryPoints, f => f.Make(10, () => historyPoints.Build()))
                            .Generate(request.Count).ToList();

            return(await HistoryRepository.BulkInsertHistoriesAsync(histories));
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            string fileName   = "contactslist.csv";
            string headerLine = "FirstName,LastName,Email";
            int    usersCount = 50;

            var faker = new Bogus.Faker();

            if (args.Length > 0 && !string.IsNullOrEmpty(args[0]))
            {
                fileName = args[0];
            }

            var filePath = $".\\{fileName}";
            var csvFile  = System.IO.File.Create(filePath);

            using (var csvWriter = new System.IO.StreamWriter(csvFile))
            {
                csvWriter.WriteLine(headerLine);

                for (int i = 0; i < usersCount; i++)
                {
                    csvWriter.WriteLine($"{faker.Name.FirstName()},{faker.Name.LastName()},{faker.Internet.ExampleEmail()}");
                }
            }
        }
Ejemplo n.º 30
0
        public static async Task Main(string[] args)
        {
            using (DocumentClient client = new DocumentClient(_endpointUri, _primaryKey))
            {
                for (int i = 0; i < 2000000; i++)
                {
                    await client.OpenAsync();

                    Uri gamesCollection = UriFactory.CreateDocumentCollectionUri("slotmachines", "games");

                    var Games = new Bogus.Faker <Game>()
                                .RuleFor(u => u.playerId, f => f.Random.Number(111111, 999999).ToString())
                                .RuleFor(u => u.machineId, f => f.Random.Number(1001, 9999).ToString())
                                .RuleFor(u => u.gameCost, f => f.Random.Number(1, 10))
                                .RuleFor(u => u.prizeAward, f => f.Random.Number(0, 500) * f.Random.Number(0, 1) * f.Random.Number(0, 1) * f.Random.Number(0, 1) * f.Random.Number(0, 1))
                                .Generate(100);

                    foreach (var game in Games)
                    {
                        ResourceResponse <Document> result = await client.CreateDocumentAsync(gamesCollection, game);

                        Console.Write("*");
                    }
                }
            }
        }